问:
DC/OS JMX Access
I have a dc/os cluster deployed to azure. I have deployed to the cluster a container with my java application. But I can't access it via jmx.

Let's take the example of deploying a standart tomcat image:

1) I opened a port 8081 according the next instruction: https://learn.microsoft.com/en-us/azure/container-service/container-service-enable-public-access#open-a-port-portal.

2) I deployed service using the next json:

```<code>{
  "id": "/tomcat",
  "instances": 1,
  "cpus": 1,
  "mem": 512,
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "tomcat:8.0",
      "network": "BRIDGE",
      "portMappings": [
        { "protocol": "tcp", "hostPort": 8080   , "containerPort": 8080 },
        { "protocol": "tcp", "hostPort": 8081   , "containerPort": 8081 }
      ]
    }
  },
  "requirePorts": true,
  "acceptedResourceRoles": [
    "slave_public"
  ],
  "env": {
    "JAVA_OPTS": "-Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=10.0.0.4 -Dcom.sun.management.jmxremote.port=8081 -Dcom.sun.management.jmxremote.rmi.port=8081 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
  },
  "healthChecks": [
    {
      "gracePeriodSeconds": 120,
      "intervalSeconds": 30,
      "maxConsecutiveFailures": 3,
      "path": "/",
      "portIndex": 0,
      "protocol": "HTTP",
      "timeoutSeconds": 5
    }
  ]
}
</code>```

To connect I use Oracle Java Mission Control. I fill fields 'Host' and 'Port' as 'prefixagents.westeurope.cloudapp.azure.com' and '8081'. But I can't connect and I get a message: 'Unable to connect'.

But for all that I can succesfully connect to this port using telnet client:

telnet prefixagents.westeurope.cloudapp.azure.com 8081

Also I can connect to port 8080 and I can open tomcat web console at the following URL: http://agents.westeurope.cloudapp.azure.com:8080

I installed one more jmx command line client - http://wiki.cyclopsgroup.org/jmxterm/ and tried to connect to the service:

```<code>java -jar jmxterm-1.0-alpha-4-uber.jar  --url service:jmx:rmi:///jndi/rmi://<prefix>agents.westeurope.cloudapp.azure.com:8081/jmxrmi
</code>```

I got the next exception: "java.rmi.ConnectException: Connection refused to host: 10.0.0.4". And 10.0.0.4 is hostname of my public agents node.

I connected to my dc/os cluster ( master node ) using https://learn.microsoft.com/en-us/azure/container-service/container-service-connect. I also installed there jmxterm and tried to connect to the service via jmx:

```<code>java -jar jmxterm.jar --url service:jmx:rmi:///jndi/rmi://10.0.0.4:8081/jmxrmi
</code>```

And I connected succesfully.

Does anybody have any ideas why I can connect to the service via jmx from my master node but I can't from my local machine? Port 8081 is opened.

答:
Does anybody have any ideas why I can connect to the service via jmx
  from my master node but I can't from my local machine? Port 8081 is
  opened.

You should connect jmx as the following command.

```<code>java -jar jmxterm.jar --url service:jmx:rmi:///jndi/rmi://<agent public IP>:8081/jmxrmi
</code>```

Update:

hostname should be public agent ip, then you could connect jmx from your local PC.

Title: DC/OS JMX Access

Body:
I have a dc/os cluster deployed to azure. I have deployed to the cluster a container with my java application. But I can't access it via jmx.

Let's take the example of deploying a standart tomcat image:

1) I opened a port 8081 according the next instruction: https://learn.microsoft.com/en-us/azure/container-service/container-service-enable-public-access#open-a-port-portal.

2) I deployed service using the next json:

{
  "id": "/tomcat",
  "instances": 1,
  "cpus": 1,
  "mem": 512,
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "tomcat:8.0",
      "network": "BRIDGE",
      "portMappings": [
        { "protocol": "tcp", "hostPort": 8080   , "containerPort": 8080 },
        { "protocol": "tcp", "hostPort": 8081   , "containerPort": 8081 }
      ]
    }
  },
  "requirePorts": true,
  "acceptedResourceRoles": [
    "slave_public"
  ],
  "env": {
    "JAVA_OPTS": "-Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=10.0.0.4 -Dcom.sun.management.jmxremote.port=8081 -Dcom.sun.management.jmxremote.rmi.port=8081 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
  },
  "healthChecks": [
    {
      "gracePeriodSeconds": 120,
      "intervalSeconds": 30,
      "maxConsecutiveFailures": 3,
      "path": "/",
      "portIndex": 0,
      "protocol": "HTTP",
      "timeoutSeconds": 5
    }
  ]
}

To connect I use Oracle Java Mission Control. I fill fields 'Host' and 'Port' as 'prefixagents.westeurope.cloudapp.azure.com' and '8081'. But I can't connect and I get a message: 'Unable to connect'.

But for all that I can succesfully connect to this port using telnet client:

telnet prefixagents.westeurope.cloudapp.azure.com 8081

Also I can connect to port 8080 and I can open tomcat web console at the following URL: http://agents.westeurope.cloudapp.azure.com:8080

I installed one more jmx command line client - http://wiki.cyclopsgroup.org/jmxterm/ and tried to connect to the service:

java -jar jmxterm-1.0-alpha-4-uber.jar  --url service:jmx:rmi:///jndi/rmi://<prefix>agents.westeurope.cloudapp.azure.com:8081/jmxrmi

I got the next exception: "java.rmi.ConnectException: Connection refused to host: 10.0.0.4". And 10.0.0.4 is hostname of my public agents node.

I connected to my dc/os cluster ( master node ) using https://learn.microsoft.com/en-us/azure/container-service/container-service-connect. I also installed there jmxterm and tried to connect to the service via jmx:

java -jar jmxterm.jar --url service:jmx:rmi:///jndi/rmi://10.0.0.4:8081/jmxrmi

And I connected succesfully.

Does anybody have any ideas why I can connect to the service via jmx from my master node but I can't from my local machine? Port 8081 is opened.

Body:
Does anybody have any ideas why I can connect to the service via jmx
  from my master node but I can't from my local machine? Port 8081 is
  opened.

You should connect jmx as the following command.

java -jar jmxterm.jar --url service:jmx:rmi:///jndi/rmi://<agent public IP>:8081/jmxrmi

Update:

hostname should be public agent ip, then you could connect jmx from your local PC.


来源: stackexchange

问:
How can I launch socket-io on a click event?
I want to make it so when I click an element with class chatroom, socketio will connect to flask.
Here is the server side:

```<code>@socketio.on('joined')
def handle_connections(data):
    username = session['Username']
    socketio.emit('status', {'msg': username + ' has entered the room.' });
</code>```

Here is the javascript

```<code>var socket = io.connect( 'http://' + document.domain + ':' + location.port );
$(document).ready(function(){
    $('.chatRoom').click(function(event){
            event.preventDefault();

            socket.on( 'connect', function() {
                socket.emit( 'joined', {});
            });
    });

    socket.on( 'status', function(data){
            console.log("user connected");
    });
});
</code>```

Without the jquery selector, the chatroom works. How can I make it work with the selector?

答:
You can send ajax call request for connect and handle that in socket.
In think below code snippet can help you other way round.</p>

```<code>`$(document).on('click', function(event){
    socket.emit('myClick', {id: event.target});
 }
 var socket = io.connect('http://localhost');
    socket.on('myClick', function (data) {
    $(data.id).trigger('click');
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to make it so when I click an element with class chatroom, socketio will connect to flask.
Here is the server side:

@socketio.on('joined')
def handle_connections(data):
    username = session['Username']
    socketio.emit('status', {'msg': username + ' has entered the room.' });

Here is the javascript

var socket = io.connect( 'http://' + document.domain + ':' + location.port );
$(document).ready(function(){
    $('.chatRoom').click(function(event){
            event.preventDefault();

            socket.on( 'connect', function() {
                socket.emit( 'joined', {});
            });
    });

    socket.on( 'status', function(data){
            console.log("user connected");
    });
});

Without the jquery selector, the chatroom works. How can I make it work with the selector?

Body:
You can send ajax call request for connect and handle that in socket.
In think below code snippet can help you other way round.

`$(document).on('click', function(event){
    socket.emit('myClick', {id: event.target});
 }
 var socket = io.connect('http://localhost');
    socket.on('myClick', function (data) {
    $(data.id).trigger('click');
 }


问:
Run two different simultaneous animations on a loop with CSS?
I am using images that float across, then fade out. (Some do the opposite, fade in.) It works the first time through the loop, but when it comes through the second time the fading just cuts out.

.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
  animation: drift 15s linear infinite, 3s fadeOut 12s ease-in;
}

@keyframes drift {
  from {
    transform: translateX(-175px);
  }
  to {
    transform: translateX(400px);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="candycane candycane_drift"></div></code>```

答:
You might consider combining the animations and setting keyframe percentages like this:

.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
  animation: drift 15s linear infinite;
}

@keyframes drift {
  0% {
    transform: translateX(-128px);
    opacity: 1;
  }
  66% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: translateX(400px);
  }
}

   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="candycane candycane_drift"></div></code>```

This has the disadvantage of tying both animations to one easing setting, but it might be easier to understand and a good solution in some circumstances.

Body:
You might consider combining the animations and setting keyframe percentages like this:

.candycane {
  width: 128px;
  height: 128px;
  position: absolute;
  background: transparent url(https://i.stack.imgur.com/qM90U.png) 0 0 no-repeat;
}

.candycane_drift {
  top: 55px;
  z-index: 100;
  animation: drift 15s linear infinite;
}

@keyframes drift {
  0% {
    transform: translateX(-128px);
    opacity: 1;
  }
  66% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: translateX(400px);
  }
}

<div class="candycane candycane_drift"></div>

This has the disadvantage of tying both animations to one easing setting, but it might be easier to understand and a good solution in some circumstances.


问:
Access violation in a multithreaded application, C++
I am not very good in multithreading programming so I would like to ask for some help/advice.

In my application I have two threads trying to access a shared object.
One can think about two tasks trying to call functions from within another object. For clarity I will show some parts of the program which may not be very relevant but hopefully can help to get my problem better.

Please take a look at the sample code below:

```<code>//DataLinkLayer.h
class DataLinkLayer: public iDataLinkLayer {

public:
DataLinkLayer(void);
~DataLinkLayer(void);
};
</code>```

Where iDataLinkLayer is an interface (abstract class without any implementation) containing pure virtual functions and a reference (pointer) declaration to the isntance of DataLinkLayer object (dataLinkLayer).

```<code>// DataLinkLayer.cpp
#include "DataLinkLayer.h"

DataLinkLayer::DataLinkLayer(void) {

/* In reality task constructors takes bunch of other parameters
 but they are not relevant (I believe) at this stage. */
dll_task_1* task1 = new dll_task_1(this);
dll_task_2* task2 = new dll_task_2(this);

/* Start multithreading */
task1->start(); // task1 extends thread class
task2->start(); // task2 also extends thread class
}

/* sample stub functions for testing */
void DataLinkLayer::from_task_1() {
printf("Test data Task 1");
}

void DataLinkLayer::from_task_2() {
printf("Test data Task 2");
}
</code>```

Implementation of task 1 is below. The dataLinLayer interface (iDataLinkLayer) pointer is passed to the class cosntructor in order to be able to access necessary functions from within the dataLinkLayer isntance.

```<code>//data_task_1.cpp
#include "iDataLinkLayer.h"  // interface to DataLinkLayer
#include "data_task_1.h"

dll_task_1::dll_task_1(iDataLinkLayer* pDataLinkLayer) {
this->dataLinkLayer = pDataLinkLayer; // dataLinkLayer declared in dll_task_1.h
}

// Run method - executes the thread
void dll_task_1::run() {
// program reaches this point and prints the stuff
this->datalinkLayer->from_task_1();
}
// more stuff following - not relevant to the problem
...
</code>```

And task 2 looks simialrly:

```<code>//data_task_2.cpp
#include "iDataLinkLayer.h"  // interface to DataLinkLayer
#include "data_task_2.h"

dll_task_2::dll_task_2(iDataLinkLayer* pDataLinkLayer){
this->dataLinkLayer = pDataLinkLayer; // dataLinkLayer declared in dll_task_2.h
}

// // Run method - executes the thread
void dll_task_2::run() {
// ERROR: 'Access violation reading location 0xcdcdcdd9' is signalled at this point
this->datalinkLayer->from_task_2();
}
// more stuff following - not relevant to the problem
...
</code>```

So as I understand correctly I access the shared pointer from two different threads (tasks) and it is not allowed.
Frankly I thought that I will be able to access the object nevertheless however the results might be unexpected.

It seems that something goes terribly wrong at the point when dll_task_2 tries to call the function using pointer to the DataLinkLayer. dll_task_2 has lower priority hence it is started afterwards. I don't understand why i still cannot at least access the object...
I can use the mutex to lock the variable but I thought that the primary reason for this is to protect the variable/object.

I am using Microsoft Visual C++ 2010 Express.
I don't know much about multithreading so maybe you can suggest a better solution to this problem as well as explain the reason of the problem.

答:
I wanted to comment on the creation of the DataLinkLayer.

When I call the DataLinkLayer constructor from main:

```<code>int main () {
DataLinkLayer* dataLinkLayer = new DataLinkLayer();
while(true); // to keep the main thread running
}
</code>```

I, of coruse, do not destruct the object, this is first. Now, inside the DataLinkLayer cosntructor I initialize many (not only these two tasks) other objects isntances and pass to most of them dataLinkLayer pointer (using this). This is legal, as far as I am concerned. Put it further - it compiles and runs as expected.

What I became curious about is the overall design idea that I am following (if any :) ).

The DataLinkLayer is a parent class that is accessed by several tasks which try to modify it parameters or perform some other processing. Since I want that everything remain as decoupled as possible I provide only interfaces for the accessors and encapsulate the data so that I don't have any global variables, friend functions etc.

It would have been a pretty easy task to do if only multithreading would not be there. I beleive I will encounter many other pitfalls on my way.

Feel free to discuss it please and merci for your generous comments!

UPD:

Speaking of passing the iDataLinkLayer interface pointer to the tasks - is this a good way to do it? In Java it would be pretty usual thing to realize a containment or so called strategy pattern to make things decoupled and stuff. However I am not 100% sure whether it is a good solution in c++... Any suggestions/commnets on it?

Body:
I am not very good in multithreading programming so I would like to ask for some help/advice.

In my application I have two threads trying to access a shared object.
One can think about two tasks trying to call functions from within another object. For clarity I will show some parts of the program which may not be very relevant but hopefully can help to get my problem better.

Please take a look at the sample code below:

//DataLinkLayer.h
class DataLinkLayer: public iDataLinkLayer {

public:
DataLinkLayer(void);
~DataLinkLayer(void);
};

Where iDataLinkLayer is an interface (abstract class without any implementation) containing pure virtual functions and a reference (pointer) declaration to the isntance of DataLinkLayer object (dataLinkLayer).

// DataLinkLayer.cpp
#include "DataLinkLayer.h"

DataLinkLayer::DataLinkLayer(void) {

/* In reality task constructors takes bunch of other parameters
 but they are not relevant (I believe) at this stage. */
dll_task_1* task1 = new dll_task_1(this);
dll_task_2* task2 = new dll_task_2(this);

/* Start multithreading */
task1->start(); // task1 extends thread class
task2->start(); // task2 also extends thread class
}

/* sample stub functions for testing */
void DataLinkLayer::from_task_1() {
printf("Test data Task 1");
}

void DataLinkLayer::from_task_2() {
printf("Test data Task 2");
}

Implementation of task 1 is below. The dataLinLayer interface (iDataLinkLayer) pointer is passed to the class cosntructor in order to be able to access necessary functions from within the dataLinkLayer isntance.

//data_task_1.cpp
#include "iDataLinkLayer.h"  // interface to DataLinkLayer
#include "data_task_1.h"

dll_task_1::dll_task_1(iDataLinkLayer* pDataLinkLayer) {
this->dataLinkLayer = pDataLinkLayer; // dataLinkLayer declared in dll_task_1.h
}

// Run method - executes the thread
void dll_task_1::run() {
// program reaches this point and prints the stuff
this->datalinkLayer->from_task_1();
}
// more stuff following - not relevant to the problem
...

And task 2 looks simialrly:

//data_task_2.cpp
#include "iDataLinkLayer.h"  // interface to DataLinkLayer
#include "data_task_2.h"

dll_task_2::dll_task_2(iDataLinkLayer* pDataLinkLayer){
this->dataLinkLayer = pDataLinkLayer; // dataLinkLayer declared in dll_task_2.h
}

// // Run method - executes the thread
void dll_task_2::run() {
// ERROR: 'Access violation reading location 0xcdcdcdd9' is signalled at this point
this->datalinkLayer->from_task_2();
}
// more stuff following - not relevant to the problem
...

So as I understand correctly I access the shared pointer from two different threads (tasks) and it is not allowed.
Frankly I thought that I will be able to access the object nevertheless however the results might be unexpected.

It seems that something goes terribly wrong at the point when dll_task_2 tries to call the function using pointer to the DataLinkLayer. dll_task_2 has lower priority hence it is started afterwards. I don't understand why i still cannot at least access the object...
I can use the mutex to lock the variable but I thought that the primary reason for this is to protect the variable/object.

I am using Microsoft Visual C++ 2010 Express.
I don't know much about multithreading so maybe you can suggest a better solution to this problem as well as explain the reason of the problem.

Body:
I wanted to comment on the creation of the DataLinkLayer.

When I call the DataLinkLayer constructor from main:

int main () {
DataLinkLayer* dataLinkLayer = new DataLinkLayer();
while(true); // to keep the main thread running
}

I, of coruse, do not destruct the object, this is first. Now, inside the DataLinkLayer cosntructor I initialize many (not only these two tasks) other objects isntances and pass to most of them dataLinkLayer pointer (using this). This is legal, as far as I am concerned. Put it further - it compiles and runs as expected.

What I became curious about is the overall design idea that I am following (if any :) ).

The DataLinkLayer is a parent class that is accessed by several tasks which try to modify it parameters or perform some other processing. Since I want that everything remain as decoupled as possible I provide only interfaces for the accessors and encapsulate the data so that I don't have any global variables, friend functions etc.

It would have been a pretty easy task to do if only multithreading would not be there. I beleive I will encounter many other pitfalls on my way.

Feel free to discuss it please and merci for your generous comments!

UPD:

Speaking of passing the iDataLinkLayer interface pointer to the tasks - is this a good way to do it? In Java it would be pretty usual thing to realize a containment or so called strategy pattern to make things decoupled and stuff. However I am not 100% sure whether it is a good solution in c++... Any suggestions/commnets on it?


问:
how to save 2 images on top of each other (swift3)
My code right now just saves 1 image. I would like to save a smaller image in the top left corner above the first image. The big thing is just to make it save together in the photo gallery. 2 images on top of each other.

```<code>import UIKit

class ViewController: UIViewController {

let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 300, height: 300))
let imageView2 = UIImageView(frame: CGRect(x:200, y: 50, width: 100, height: 100))

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let image =  UIImage(named: "wall")!
    imageView.image = image

    let image2 = UIImage(named: "pic")!
    imageView2.image = image2

    imageView.addSubview(imageView2)

    imageView2.image = image2

    imageView.addSubview(imageView2)

    let topImage = UIImage(named: "wall")
    let bottomImage = UIImage(named: "pic")

    let size = CGSize(width: topImage!.size.width, height: topImage!.size.height + bottomImage!.size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    topImage!.draw(in: CGRect(x: 0, y: topImage!.size.height, width: size.width, height: bottomImage!.size.height))
    bottomImage!.draw(in: CGRect(x: 0, y: topImage!.size.height, width: size.width, height: bottomImage!.size.height))

    //your new Image
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
                   UIGraphicsEndImageContext()

}

@IBAction func press(_ sender: Any) {
     UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }}}
</code>```

pic

答:
```<code>    let imageView2 = UIImageView(frame: CGRect(x:200, y: 50, width: 100, height:100))
    let image2 =  UIImage(named: "wallsmallImage")!
    imageView2.image = image2
    imageView.addSub(imageView2)

#Now merge both images
         let image =  UIImage(named: "wall")!
         imageView.image = image
        let image2 = UIImage(named: "pic")!
        imageView2.image = image2

       imageView.addSubview(imageView2)

        let topImage = UIImage(named: "wall")
        let bottomImage = UIImage(named: "pic")

        let size = CGSize(width: topImage!.size.width, height: topImage!.size.height + bottomImage!.size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        topImage!.draw(in: CGRect(x: 0, y: topImage!.size.height, width: size.width, height: bottomImage!.size.height))
         bottomImage!.draw(in: CGRect(x: 0, y: topImage!.size.height, width: size.width, height: bottomImage!.size.height))

        //your new Image
        let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
</code>```

Body:
My code right now just saves 1 image. I would like to save a smaller image in the top left corner above the first image. The big thing is just to make it save together in the photo gallery. 2 images on top of each other.

import UIKit

class ViewController: UIViewController {

let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 300, height: 300))
let imageView2 = UIImageView(frame: CGRect(x:200, y: 50, width: 100, height: 100))

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let image =  UIImage(named: "wall")!
    imageView.image = image

    let image2 = UIImage(named: "pic")!
    imageView2.image = image2

    imageView.addSubview(imageView2)

    imageView2.image = image2

    imageView.addSubview(imageView2)

    let topImage = UIImage(named: "wall")
    let bottomImage = UIImage(named: "pic")

    let size = CGSize(width: topImage!.size.width, height: topImage!.size.height + bottomImage!.size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    topImage!.draw(in: CGRect(x: 0, y: topImage!.size.height, width: size.width, height: bottomImage!.size.height))
    bottomImage!.draw(in: CGRect(x: 0, y: topImage!.size.height, width: size.width, height: bottomImage!.size.height))

    //your new Image
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
                   UIGraphicsEndImageContext()

}

@IBAction func press(_ sender: Any) {
     UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }}}

pic


问:
How do you get a position:absolute; element above a position:relative; one
You can see the issue in this fiddle.

I've got an absolutely positioned element with a z-index of 2 and a relatively positioned element with a z-index of 1.  The relatively positioned element contains the absolutely positioned one.  I thought that the z-index:2 element would show above the z-index:1 items, but it does not.  Is there a way to fix this so that the z-index:2 items are above all z-index:1 items?

div {
  background: green;
  position: relative;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  Row 1
  <span>I thought this would show above 'Row 2'</span>
</div>
<div>
  Row 2
</div></code>```

答:
The problem was because the div with absolute position was not relative to the second row. I added a wrapper around the two divs and added position: relative; to it.

.wrapper div {
  background: green;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

.wrapper {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div>
    Row 1
    <span>I thought this would show above 'Row 2'</span>
  </div>
  <div>
    Row 2
  </div>
</div></code>```

Body:
You can see the issue in this fiddle.

I've got an absolutely positioned element with a z-index of 2 and a relatively positioned element with a z-index of 1.  The relatively positioned element contains the absolutely positioned one.  I thought that the z-index:2 element would show above the z-index:1 items, but it does not.  Is there a way to fix this so that the z-index:2 items are above all z-index:1 items?

div {
  background: green;
  position: relative;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

  Row 1
  I thought this would show above 'Row 2'

  Row 2

Body:
The problem was because the div with absolute position was not relative to the second row. I added a wrapper around the two divs and added position: relative; to it.

.wrapper div {
  background: green;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

.wrapper {
  position: relative;
}

<div class="wrapper">
  <div>
    Row 1
    <span>I thought this would show above 'Row 2'</span>
  </div>
  <div>
    Row 2
  </div>
</div>


问:
how to compare the text field values with database values which is entered in the text field
Actually, I don't want to accept the same name which is already entered in the text field (i.e; unique values) stored in database.

For example, I entered a name "health" in text field and saved it. If again enter the same name then it won't accept.

I tried below but it's not working. Please help me.

```<code>boolean ifExisting(String cat)
     {
      Cursor c = db.rawQuery("SELECT * FROM " + "restaurants" + "WHERE" + "category" + "=" + cat, null);
         if(c.getCount() == 0)
         {
          return;
         }
          else
          {
           return;
          }
     }
       insert();
</code>```

答:
There are no spaces around your "WHERE" word. You're writing this :

```<code>"SELECT * FROM restaurantsWHEREcategory=" + cat
</code>```

Just add spaces and it should be better.

By the way, using rawQuery is very slow because of the time used to parse your string. You should take a look at the NotePad app in the android SDK samples/ directory.

Body:
Actually, I don't want to accept the same name which is already entered in the text field (i.e; unique values) stored in database.

For example, I entered a name "health" in text field and saved it. If again enter the same name then it won't accept.

I tried below but it's not working. Please help me.

boolean ifExisting(String cat)
     {
      Cursor c = db.rawQuery("SELECT * FROM " + "restaurants" + "WHERE" + "category" + "=" + cat, null);
         if(c.getCount() == 0)
         {
          return;
         }
          else
          {
           return;
          }
     }
       insert();

Body:
There are no spaces around your "WHERE" word. You're writing this :

"SELECT * FROM restaurantsWHEREcategory=" + cat

Just add spaces and it should be better.

By the way, using rawQuery is very slow because of the time used to parse your string. You should take a look at the NotePad app in the android SDK samples/ directory.

ContentLicense: CC BY-SA 2.5


问:
Update data in firebase using nodejs
I have the following problem, I am sending data every minute to a firebase
 database in a cron tab that is running in nodejs, I only send the information when there are changes, but when there are no changes the database continues to receive information, This is my code

```<code>let admin = require('firebase-admin');
let prev_res = {};

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'mydburl'
});

cron.schedule('* * * * *', function(){
    let connection = mysql.createConnection({
      host     : 'myhost',
      user     : 'myuser',
      password : 'mypass',
      database : 'mydb'
    });

    connection.query("MY QUERY", function(err, rows, fields){
        if (!err){
            if(JSON.stringify(rows) != JSON.stringify(prev_res)){
                let db = admin.database();
                let ref = db.ref('path');
                ref.set(rows);

                console.log("Updated data");
            } else {
                console.log("without changes");
            }

            prev_res = rows;

        }
    });

});
</code>```

Does the firebase admin have some kind of cache or something like that?

答:
This is actually a strange problem with Firebase Authentication.
The issue resides in the permissions for the user you are including in your credentials.
Besides creating a Service Account with the correct permissions, you need to add this user to your IAM Accounts with the editor role.

Restart your App after doing this and you should stop seeing:

"FIREBASE WARNING: Provided authentication credentials are invalid.
  This usually indicates your FirebaseApp instance was not initialized
  correctly."

Title: Update data in firebase using nodejs

Body:
I have the following problem, I am sending data every minute to a firebase
 database in a cron tab that is running in nodejs, I only send the information when there are changes, but when there are no changes the database continues to receive information, This is my code

let admin = require('firebase-admin');
let prev_res = {};

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'mydburl'
});

cron.schedule('* * * * *', function(){
    let connection = mysql.createConnection({
      host     : 'myhost',
      user     : 'myuser',
      password : 'mypass',
      database : 'mydb'
    });

    connection.query("MY QUERY", function(err, rows, fields){
        if (!err){
            if(JSON.stringify(rows) != JSON.stringify(prev_res)){
                let db = admin.database();
                let ref = db.ref('path');
                ref.set(rows);

                console.log("Updated data");
            } else {
                console.log("without changes");
            }

            prev_res = rows;

        }
    });

});

Does the firebase admin have some kind of cache or something like that?


问:
GWT - RPC SerializationException with class object
I am currently trying to use the SyncProxy library to test services of my app, in order to do load testing with JMeter. The app works fine, I am running it on localhost.

I already managed to make some calls, but only when the parameters where

this is the error :

Type 'net.gicm.ector.shared.beans.Utilisateur' was not included in the
  set of types which can be serialized by this SerializationPolicy or
  its Class object could not be loaded. For security purposes, this type
  will not be serialized.

Here is the piece of code where I make the call :

```<code> final Utilisateur user = new Utilisateur();
 user.setUser("C2984");

 TableauDeBordServiceAsync tableauDeBordServiceAsync = (TableauDeBordServiceAsync) SyncProxy
          .newProxyInstance(TableauDeBordServiceAsync.class, MODULE_BASE_URL, GET_SERVICE_NAME_2);
 tableauDeBordServiceAsync.ongletRealisationListeControle(plan, user, codeSI, numStructure, synthese, colonneAtrier, ordre, numeroPagination, filtre, new AsyncCallback<List<List<String>>>() {

    @Override
    public void onFailure(Throwable caught) {
        // TODO Auto-generated method stub
        System.out.println(caught);

    }

    @Override
    public void onSuccess(List<List<String>> result) {
        // TODO Auto-generated method stub
        System.out.println(result);

    }

 });
</code>```

I looked at this thread, and tried to find where could I do something wrong : https://stackoverflow.com/a/9534704/4628136

My class implements the Serializable interface, has a default empty constructor, and is in the client package.

```<code>public class Utilisateur implements Serializable {
   ...
   public Utilisateur() {
   }
   ...
}
</code>```

But actually, I don't see anything about that Utilisateur class in the gwt.rpc files.

答: Make sure all the attributes of this class are also serialized.</p>

Body:
I am currently trying to use the SyncProxy library to test services of my app, in order to do load testing with JMeter. The app works fine, I am running it on localhost.

I already managed to make some calls, but only when the parameters where

this is the error :

Type 'net.gicm.ector.shared.beans.Utilisateur' was not included in the
  set of types which can be serialized by this SerializationPolicy or
  its Class object could not be loaded. For security purposes, this type
  will not be serialized.

Here is the piece of code where I make the call :

 final Utilisateur user = new Utilisateur();
 user.setUser("C2984");

 TableauDeBordServiceAsync tableauDeBordServiceAsync = (TableauDeBordServiceAsync) SyncProxy
          .newProxyInstance(TableauDeBordServiceAsync.class, MODULE_BASE_URL, GET_SERVICE_NAME_2);
 tableauDeBordServiceAsync.ongletRealisationListeControle(plan, user, codeSI, numStructure, synthese, colonneAtrier, ordre, numeroPagination, filtre, new AsyncCallback<List<List<String>>>() {

    @Override
    public void onFailure(Throwable caught) {
        // TODO Auto-generated method stub
        System.out.println(caught);

    }

    @Override
    public void onSuccess(List<List<String>> result) {
        // TODO Auto-generated method stub
        System.out.println(result);

    }

 });

I looked at this thread, and tried to find where could I do something wrong : https://stackoverflow.com/a/9534704/4628136

My class implements the Serializable interface, has a default empty constructor, and is in the client package.

public class Utilisateur implements Serializable {
   ...
   public Utilisateur() {
   }
   ...
}

But actually, I don't see anything about that Utilisateur class in the gwt.rpc files.


答:
When you add a z-index to a child that is in a positioned parent element that also has a z-index, the parent z-index starts a new stacking order, and the child z-index is relative to the parent's z-index. So in this case, z-index: 2 is only compared to other elements inside of the parent with z-index: 1. To get around this, you could just apply the z-index to the span, or don't give the last div a z-index

You can read more about it here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

body {
  font-family: arial;
}

* {
  padding: 10px;
}

div {
  background: green;
  position: relative;
  width: 100%;

}

div:first-child {
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  Row 1
  <span>
  I thought this would show above 'Row 2'
</span>
</div>
<div>
  Row 2
</div></code>```

Title: How do you get a position:absolute; element above a position:relative; one

Body:
When you add a z-index to a child that is in a positioned parent element that also has a z-index, the parent z-index starts a new stacking order, and the child z-index is relative to the parent's z-index. So in this case, z-index: 2 is only compared to other elements inside of the parent with z-index: 1. To get around this, you could just apply the z-index to the span, or don't give the last div a z-index

You can read more about it here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

body {
  font-family: arial;
}

* {
  padding: 10px;
}

div {
  background: green;
  position: relative;
  width: 100%;

}

div:first-child {
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
  display: inline-block;
}

<div>
  Row 1
  <span>
  I thought this would show above 'Row 2'
</span>
</div>
<div>
  Row 2
</div>


问:
Creating an Image Icon from a local file for eclipse
So I am trying to add an image to a JLabel object which is added to a JPanel called "topPanel" which is part of a JFrame called
"primaryWindow". I have already declared the "topPanel" and "primaryWindow". I found on other forms that you have to create a separate source folder and add the image file in that folder in order to access it and I did so.

However, when I execute the following, the image does not appear to be on the Label. I know that it has nothing to do with adding the JLabel to the panel properly because when I enter a String into the JLabel constructor, the String appears on the panel. An image however does not appear. Am I properly adding the image? I am using a mac if this helps.

```<code>private JLabel image = new JLabel();
image.setIcon(new ImageIcon("Check.png"));
topPanel.add(image);
primaryWindow.add(topPanel, BorderLayout.NORTH);
</code>```

答:
The ImageIcon that you passed into the setIcon method of the JLabel could be null.  Have you tried to check if it is null before calling setIcon?  If you create a "res" resource folder in the root directory of your project, you could try the following:

```<code>image.setIcon(new ImageIcon(ImageIO.read(new File("res/Check.png"))));
</code>```

Additionally, if you are using Eclipse, you should try and refresh the project directory by right clicking and pressing refresh; sometimes Eclipse doesn't register files added.

Lastly, try setting the background of the JPanel to a certain color to see if it is displaying it and make sure its width and height are not 0 (it is possible that the layout you are using changed its size).

Body:
So I am trying to add an image to a JLabel object which is added to a JPanel called "topPanel" which is part of a JFrame called
"primaryWindow". I have already declared the "topPanel" and "primaryWindow". I found on other forms that you have to create a separate source folder and add the image file in that folder in order to access it and I did so.

However, when I execute the following, the image does not appear to be on the Label. I know that it has nothing to do with adding the JLabel to the panel properly because when I enter a String into the JLabel constructor, the String appears on the panel. An image however does not appear. Am I properly adding the image? I am using a mac if this helps.

private JLabel image = new JLabel();
image.setIcon(new ImageIcon("Check.png"));
topPanel.add(image);
primaryWindow.add(topPanel, BorderLayout.NORTH);

Body:
The ImageIcon that you passed into the setIcon method of the JLabel could be null.  Have you tried to check if it is null before calling setIcon?  If you create a "res" resource folder in the root directory of your project, you could try the following:

image.setIcon(new ImageIcon(ImageIO.read(new File("res/Check.png"))));

Additionally, if you are using Eclipse, you should try and refresh the project directory by right clicking and pressing refresh; sometimes Eclipse doesn't register files added.

Lastly, try setting the background of the JPanel to a certain color to see if it is displaying it and make sure its width and height are not 0 (it is possible that the layout you are using changed its size).


问:
Single / multiple JVM on Single Machine with single / multiple core
I have few questions and I have searched for below questions over the net but got more confused.

I have java application running on single machine with single JVM , 20 core machine with 20 GB ram with 20 java thread. ( single machine, single JVM, 20 core, 20 GB ram, 20 java threads )

I have java application running on single machine with 20 JVM, 20 core mahcine with 1 GB ram to each JVM with 1 JAVA thread to each process. ( single machine, 20 JVM, 20 core, 20 GB ram, 20 java threads )

From above points 1 and 2 which one is better and why in terms of

Performance of application

CPU utilization of machine

If CPU is not consumed fully even increasing the number of threads, then what to do in application or machine in order to utilize more CPU.

In which case context switching will be more.

In above 1 and 2 point, lets say each thread takes 10ms to complete the task then, in how much time all the tasks will be completeed in case 1 and 2. Please explain.

I have search and heard about CPU intensive and I/O intensive application in regard of CPU utilization. Can you please explain a bit as over net I got confused alot.

Generally it is recommened to have number of threads equal to number of cores. If i have more number of thread then cores then what will be the impact. Please explain.

答:
You have a lot of different variables in play there and there isn't going to be a simple answer.  I'll add some details below, but the tl;dr version is going to be "run some tests for your scenario and see what works the best".

Whether or not you should have one thread per cpu depends on your workload.  As you've already apparently found, if your thread is cpu intensive (meaning, most of the time it is actively using the cpu), then one thread will come close to fully utilizing one cpu.  In many real-world situations, though, it's likely that your thread may have to do other things (like wait for I/O), in which case it will not fully utilize a cpu (meaning you could run more than one thread per cpu).

also, in your two scenarios, you need to account for all the jvm overhead.  Each jvm will have many of its own threads (most notably, the GC threads).  These will add additional overhead to your cpu usage.  If your code makes heavy use of the garbage collector (creating/discarding a large amount of garbage while working), it may be beneficial to have separate jvms per thread, but you'll need to account for the additional gc thread cpu usage.  if your code does not make a lot of garbage, then using separate jvms (and many extra gc threads) may just be wasting resources.

Given all these variables, as well as the actual workload profile of your threads, you are unlikely to find the right answer with theory alone.  Testing a variety of scenarios with real world data is the only way you will find the right mix for your application (it might end up being something in the middle like 4 jvms with 5 threads each).


问:
Bootstrap Modal close button not working on smaller screens
For some modals, I'm using an 'x' button on the top right of the screen to close the modal. While the button works on larger devices (when the width is > 768 pixels), I've found that the button doesn't work on smaller devices (such as on mobile).

This is the HTML I use for the close button, which I got directly off the Bootstrap documentation:

```<code><button type="button" class="close" data-dismiss="modal" aria-label="Close">
    <span class="close-btn" aria-hidden="true">
        ×
    </span>
</button>
</code>```

I also added the class close-btn to change to font size to 2.5 em to make it larger.

Edit: Here's the full modal:

```<code><div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-content">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span class="close-btn" aria-hidden="true">×</span></button>
        <div class="row">
            <div class="col-lg-12">
                <div class="modal-body">
                    <h2 class="text-center">Title here.</h2>
                    <hr class="star-primary">

                    <h3 class="text-center">
                        Text here.
                    </h3>

                    <br />
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
Add the button tag inside the modal body

```<code><div class="modal-body">
                 <button type="button" class="close close-btn" data-dismiss="modal" aria-label="Close"><span class="" aria-hidden="true">×</span></button>

                    <h2 class="text-center">Title here.</h2>
                    <hr class="star-primary">

                    <h3 class="text-center">
                        Text here.
                    </h3>

                    <br />
                </div>
</code>```

Here is the codepen link for reference

https://codepen.io/chandrashekhar/pen/weBOvy?editors=1100

Hope this Works..

Body:
For some modals, I'm using an 'x' button on the top right of the screen to close the modal. While the button works on larger devices (when the width is > 768 pixels), I've found that the button doesn't work on smaller devices (such as on mobile).

This is the HTML I use for the close button, which I got directly off the Bootstrap documentation:

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

        ×

</button>

I also added the class close-btn to change to font size to 2.5 em to make it larger.

Edit: Here's the full modal:

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

Title here.

                        Text here.

Body:
Add the button tag inside the modal body

<div class="modal-body">
                 <button type="button" class="close close-btn" data-dismiss="modal" aria-label="Close"><span class="" aria-hidden="true">&times;</span></button>

                    <h2 class="text-center">Title here.</h2>
                    <hr class="star-primary">

                    <h3 class="text-center">
                        Text here.
                    </h3>

                    <br />
                </div>

Here is the codepen link for reference

https://codepen.io/chandrashekhar/pen/weBOvy?editors=1100

Hope this Works..


答:
Just remove z-index:1.

div {
  background: green;
  position: relative;
  width: 100%;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  Row 1
  <span>I thought this would show above 'Row 2'</span>
</div>
<div>
  Row 2
</div></code>```

Body:
Just remove z-index:1.

div {
  background: green;
  position: relative;
  width: 100%;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

<div>
  Row 1
  <span>I thought this would show above 'Row 2'</span>
</div>
<div>
  Row 2
</div>


问:
The use of Swift 3 @objc inference in Swift 4 mode is deprecated?
Briefly, while using Xcode 9 Beta, I have run into the following warning:

The use of Swift 3 @objc inference in Swift 4 mode is deprecated. Please address deprecated @objc inference warnings, test your code with “Use of deprecated Swift 3 @objc inference” logging enabled, and disable Swift 3 @objc inference.**

After some research, I still have no idea how to fix the issue.
I would greatly appreciate any tips on how to fix this issue as well as an explanation of what is going on.

My goal is to grasp a better understanding of what is happening with my code.

答:
I got rid of this warning by changing the "Swift 3 @objc Inference" build setting of my targets to "Default".

From this article:

Before Swift 4, the compiler made some Swift declarations automatically available to Objective-C. For example, if one subclassed from NSObject, the compiler created Objective-C entry points for all methods in such classes. The mechanism is called @objc inference.

In Swift 4, such automatic @objc inference is deprecated because it is costly to generate all those Objective-C entry points. When "Swift 3 @objc Inference" setting is set to "On", it allows the old code to work. However, it will show deprecation warnings that need to be addressed. It is recommended to "fix" these warnings and switch the setting to "Default", which is the default for new Swift projects.

Please also refer to this Swift proposal for more information.


问:
How can i write SQL update query with where clause in Entity Framework in C#
I know that for update a model in EF i must get model then change it then dbContext.SaveChanges()
but sometimes in my Asp.net mvc project , i want update a field in my table and i don't know it 's id  and must be get it with where clause.
but i don't want connect twice to database , because in ADO.net i can write:

```<code>UPDATE MyTable SET Field3 = "NewValue" WHERE Active = 1
</code>```

and now i want write a linq to sql for EF that work like that.
Is exist any way for that?
thanks

答:
You can use the raw query function in EF.</p>

```<code>var query = "UPDATE MyTable SET Field3 = 'NewValue' WHERE Active = 1";
using (var context = new YourContext())
{
    context.Database.ExecuteSqlCommand(query);
}
</code>```

Body:
I know that for update a model in EF i must get model then change it then dbContext.SaveChanges()
but sometimes in my Asp.net mvc project , i want update a field in my table and i don't know it 's id  and must be get it with where clause.
but i don't want connect twice to database , because in ADO.net i can write:

UPDATE MyTable SET Field3 = "NewValue" WHERE Active = 1

and now i want write a linq to sql for EF that work like that.
Is exist any way for that?
thanks

Body:
You can use the raw query function in EF.

var query = "UPDATE MyTable SET Field3 = 'NewValue' WHERE Active = 1";
using (var context = new YourContext())
{
    context.Database.ExecuteSqlCommand(query);
}


问:
Magento Block Caching tips
Ok, so I have recently been looking at block caching in magento.  Looks like a really great way to speed up rendering of pages, but it also looks like a bit of a pain in the arse.

For example, caching category blocks seems to require a lot of messing around to get done properly.  Also, there a lot of core blocks which do not utilize block caching that probably could. In these cases, does a developer have to create a single module and then rewrite all of these core blocks, just so as to enable block caching on them?

Are there any other tips with regards to block caching for those new to this subject?

答:
Block caching can be done in PHP if you prefer. The cache management has to be written in the constructor of the Block

https://magento2.atlassian.net/wiki/display/m1wiki/How+to+use+HTML+output+cache+in+Magento+1.x

```<code>protected function _construct() {
 $this->addData(array(
  'cache_lifetime' => 3600,
  'cache_tags'     => array(Mage_Catalog_Model_Product::CACHE_TAG),
  'cache_key'      => $this->getProduct()->getId(),
 ));
}
</code>```

Title: Magento Block Caching tips

Body:
Block caching can be done in PHP if you prefer. The cache management has to be written in the constructor of the Block

https://magento2.atlassian.net/wiki/display/m1wiki/How+to+use+HTML+output+cache+in+Magento+1.x

protected function _construct() {
 $this->addData(array(
  'cache_lifetime' => 3600,
  'cache_tags'     => array(Mage_Catalog_Model_Product::CACHE_TAG),
  'cache_key'      => $this->getProduct()->getId(),
 ));
}


问:
React don't rendered the Data that from serve without use reload event
Here is an example:
When user logined I send a request to server to get the user information. Then use 'react route history' goto home page, and render the Data from server. But it didn't work, there is no user info rendered in the view. When I reload the page, user info has added to the view. How to deal with it ?  Thank you very much.</p>

答:
axios.post('/user/login', qs.stringify({
                 uname: uname,
                 pwd: pwd,
                 captcha: captcha,
                 codeid: this.state.codeUUID
             })
         ).then(function (res) {
             let data = res.data.attachment;
             if (res.data.status == 200) {
                 localStorage.setItem('token', data.token);
                 localStorage.setItem('uid', data.uid);
                    this.context.router.push('/home')
             } else if(res.data.status === 412) {
                    message.error("captcha error")
                    this.getCaptcha();
                    this.refs.captcha.value = ''
             } else {
                    message.error(res.data.message);
                }
         }.bind(this))```


问:
Selenium can not click on GWT tree item
I can't give access to the webapp but here is the code and HTML of the button

```<code> we = driver.findElement(By.xpath("//div/div/div[2]/div/div/div/div/div/div/div/div/div/div/div"));
 int width = we.getSize().getWidth();
 action.moveToElement(we, width/2, 9).click().build().perform();
</code>```

.

```<code><div style="display: inline; background-color: rgb(255, 179, 0);" class="gwt-TreeItem gwt-TreeItem-selected" role="treeitem" id="gwt-uid-102" aria-level="9" aria-setsize="4" aria-posinset="1" aria-selected="true">
</code>```

答: When you run selenium TCs, make sure that the browser maximized. Sometimes, it may happen that elements overlap due to smaller resolution.</p>

Title: Selenium can not click on GWT tree item

Body:
I can't give access to the webapp but here is the code and HTML of the button

 we = driver.findElement(By.xpath("//div/div/div[2]/div/div/div/div/div/div/div/div/div/div/div"));
 int width = we.getSize().getWidth();
 action.moveToElement(we, width/2, 9).click().build().perform();

.


问:
Alternative for System.out.print in Android
Could someone tell me what is the alternative for System.out.print in Android?

答:
@polopok
Hm... Not that correct I think.

Check the code guidelines : http://source.android.com/source/code-style.html#logging

Log.d(), Log.i(), Log.w(), etc should be the way to go.


问:
How to create a Liferay 7 structure programmatically?
In Liferay 7, how to create a structure from a Java module?

Here is my attempt:

```<code>Map<Locale, String> nameMap = new HashMap<Locale, String>();
nameMap.put(Locale.JAPAN, "The name");
Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
descriptionMap.put(Locale.JAPAN, "The description");

DDMForm ddmForm = DDMUtil.getDDMForm("<here goes my real JSON form>");
DDMFormLayout ddmFormLayout = DDMUtil.getDefaultDDMFormLayout(ddmForm);

DDMStructureLocalServiceUtil.addStructure(
    20156, // userId
    33421, // groupId
    DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID, // parentStructureId
    PortalUtil.getPortal().getClassNameId(DDLRecordSet.class), // classNameId
    new Long(CounterLocalServiceUtil.increment()).toString(), // structureKey
    nameMap,
    descriptionMap,
    ddmForm,
    ddmFormLayout,
    StorageType.JSON.toString(),
    0, // type
    new ServiceContext()
);
</code>```

The structure gets created in the database's DDMStructure table:

Unfortunately, it does not appear in that site's Liferay UI:

How to make it show up?

No error appear in Liferay's log during creation nor when loading the UI.

When I create a structure manually, it shows up correctly.

The solution to this question for Liferay 6, which I tried too, leads to the same problem.

I noticed that when creating a structure manually, 3 rows get added to the ResourcePermission table... when creating a structure in Java should I also create these 3 objects?

答:
It is a classNameId problem. Replacing DDLRecordSet with JournalArticle solves the problem, making the structure show up correctly in Liferay's Structures UI.

Code that works:

```<code>ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(group.getGroupId());
serviceContext.setAddGroupPermissions(true);
serviceContext.setAddGuestPermissions(true);
serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

Map<Locale, String> nameMap = new HashMap<Locale, String>();
nameMap.put(Locale.JAPAN, "The name");
Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
descriptionMap.put(Locale.JAPAN, "The description");

DDMForm ddmForm = null;
try {
    ddmForm = DDMUtil.getDDMForm(json);
} catch (PortalException e) {
    log.error("Exception when parsing structure JSON", e);
}

DDMFormLayout ddmFormLayout = DDMUtil.getDefaultDDMFormLayout(ddmForm);
long scopeClassNameId = PortalUtil.getPortal().getClassNameId(JournalArticle.class);
long parentStructureId = DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID;
String storageType = StorageType.JSON.toString();
String structureKey = "my structure";

try {
    DDMStructure ddmStructure = DDMStructureLocalServiceUtil.addStructure(
        user.getUserId(), group.getGroupId(), parentStructureId,
        scopeClassNameId, structureKey,
        nameMap, descriptionMap, ddmForm, ddmFormLayout, storageType,
        DDMStructureConstants.TYPE_DEFAULT, serviceContext);
} catch (StructureDuplicateStructureKeyException e) {
    log.info("Skipping creation of structure that already exists");
} catch (PortalException e) {
    log.error("Exception when creating structure: " + structureDefinitionFilePath, e);
}
</code>```

Body:
In Liferay 7, how to create a structure from a Java module?

Here is my attempt:

Map<Locale, String> nameMap = new HashMap<Locale, String>();
nameMap.put(Locale.JAPAN, "The name");
Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
descriptionMap.put(Locale.JAPAN, "The description");

DDMForm ddmForm = DDMUtil.getDDMForm("<here goes my real JSON form>");
DDMFormLayout ddmFormLayout = DDMUtil.getDefaultDDMFormLayout(ddmForm);

DDMStructureLocalServiceUtil.addStructure(
    20156, // userId
    33421, // groupId
    DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID, // parentStructureId
    PortalUtil.getPortal().getClassNameId(DDLRecordSet.class), // classNameId
    new Long(CounterLocalServiceUtil.increment()).toString(), // structureKey
    nameMap,
    descriptionMap,
    ddmForm,
    ddmFormLayout,
    StorageType.JSON.toString(),
    0, // type
    new ServiceContext()
);

The structure gets created in the database's DDMStructure table:

Unfortunately, it does not appear in that site's Liferay UI:

How to make it show up?

No error appear in Liferay's log during creation nor when loading the UI.

When I create a structure manually, it shows up correctly.

The solution to this question for Liferay 6, which I tried too, leads to the same problem.

I noticed that when creating a structure manually, 3 rows get added to the ResourcePermission table... when creating a structure in Java should I also create these 3 objects?

Body:
It is a classNameId problem. Replacing DDLRecordSet with JournalArticle solves the problem, making the structure show up correctly in Liferay's Structures UI.

Code that works:

ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(group.getGroupId());
serviceContext.setAddGroupPermissions(true);
serviceContext.setAddGuestPermissions(true);
serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

Map<Locale, String> nameMap = new HashMap<Locale, String>();
nameMap.put(Locale.JAPAN, "The name");
Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
descriptionMap.put(Locale.JAPAN, "The description");

DDMForm ddmForm = null;
try {
    ddmForm = DDMUtil.getDDMForm(json);
} catch (PortalException e) {
    log.error("Exception when parsing structure JSON", e);
}

DDMFormLayout ddmFormLayout = DDMUtil.getDefaultDDMFormLayout(ddmForm);
long scopeClassNameId = PortalUtil.getPortal().getClassNameId(JournalArticle.class);
long parentStructureId = DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID;
String storageType = StorageType.JSON.toString();
String structureKey = "my structure";

try {
    DDMStructure ddmStructure = DDMStructureLocalServiceUtil.addStructure(
        user.getUserId(), group.getGroupId(), parentStructureId,
        scopeClassNameId, structureKey,
        nameMap, descriptionMap, ddmForm, ddmFormLayout, storageType,
        DDMStructureConstants.TYPE_DEFAULT, serviceContext);
} catch (StructureDuplicateStructureKeyException e) {
    log.info("Skipping creation of structure that already exists");
} catch (PortalException e) {
    log.error("Exception when creating structure: " + structureDefinitionFilePath, e);
}


问:
How can I use Hashicorp Vault to manage my application secrets?
I'm very excited by the offerings of Hashicorp Vault but I'm having trouble wrapping my head around how it fits into our present architecture. The need to manually unseal the vault with every deployment is a great benefit to security, no doubt, but how are applications meant to react when the Vault is initially sealed?

For instance, if application A depends on a database credential generated by Vault in order to initialize, how is this application meant to react when it is deployed while Vault is sealed? Spin-wait while checking for the sealed status?

Additionally, how are other people pre-populating Vault with certain secrets in production? For instance, we have an authentication server that depends on a single consistent system secret that it must fetch from Vault at startup. How can I securely ensure that this secret is available after deploying Vault?

For the record, we are deploying Vault with some other services using docker-compose and ecs compose for deployment.

答:
It is not necessary to seal your vault between deployments. Vault requires an unsealed vault to renew leases, read secrets, create credentials etc. The vault is secured with authentication and authorization during normal use.

You should seal your vault when a significant intrusion has been detected. Sealing the vault helps minimize damages by throwing away the reconstructed master key. This prevents Vault from operating until the risk has been mitigated. Sealing does not revoke credentials that were issued by Vault.

You also asked about importing pre-existing secrets and how to "securely ensure that this secret is available after deploying Vault?":

You should issue write commands for your pre-existing secrets to import them after the vault has been unsealed. You can securely ensure that the secret exists by reading it. Read and write operations are generally secure when using the CLI or API.

```<code>$ vault write secret/single-consistent-system-secret value=secret-stuff
Success! Data written to: secret/single-consistent-system-secret

$ vault read secret/single-consistent-system-secret
Key             Value
lease_duration  2592000
value           secret-stuff
</code>```

Body:
It is not necessary to seal your vault between deployments. Vault requires an unsealed vault to renew leases, read secrets, create credentials etc. The vault is secured with authentication and authorization during normal use.

You should seal your vault when a significant intrusion has been detected. Sealing the vault helps minimize damages by throwing away the reconstructed master key. This prevents Vault from operating until the risk has been mitigated. Sealing does not revoke credentials that were issued by Vault.

You also asked about importing pre-existing secrets and how to "securely ensure that this secret is available after deploying Vault?":

You should issue write commands for your pre-existing secrets to import them after the vault has been unsealed. You can securely ensure that the secret exists by reading it. Read and write operations are generally secure when using the CLI or API.

$ vault write secret/single-consistent-system-secret value=secret-stuff
Success! Data written to: secret/single-consistent-system-secret

$ vault read secret/single-consistent-system-secret
Key             Value
lease_duration  2592000
value           secret-stuff


问:
Ruby on Rails: Why the confirmation message does not appear in "link_to('delete', ...)"?
I have the following link next to one of my products:

```<code><%= link_to("Delete", {:action => 'destroy', :id => product.id}, :class => 'action', :confirm => 'Are you sure?') %>
</code>```

but when I click it, the confirmation box does not appear.

The generated HTML is:

```<code><a data-confirm="Are you sure ?" class="action" href="/products/destroy/48">Delete</a>
</code>```

Please advise.

答:
```<code><%= link_to("Delete", product, :method => :delete, :class => 'action', :confirm => 'Are you sure?') %>
</code>```

check your javascript_include_tag
and it should work fine :)

Body:
I have the following link next to one of my products:

<%= link_to("Delete", {:action => 'destroy', :id => product.id}, :class => 'action', :confirm => 'Are you sure?') %>

but when I click it, the confirmation box does not appear.

The generated HTML is:

Delete

Please advise.

Body:
<%= link_to("Delete", product, :method => :delete, :class => 'action', :confirm => 'Are you sure?') %>

check your javascript_include_tag
and it should work fine :)


问:
Python - PyQT4 how to detect the mouse click position anywhere in the window?
I have 1024x768 resolution window, when there is a click or mouse over, i want to find the x, y values. How can i do that?</p>

```<code>import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        qbtn = QtGui.QPushButton('Quit', self)
        #qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        qbtn.clicked.connect(self.test)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)

        self.setGeometry(0, 0, 1024, 768)
        self.setWindowTitle('Quit button')
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
        self.show()

    def test(self):
      print "show the position of mouse cursor in screen resolution: x is ?? , y is ??"

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

答:
The other way to get (x,y) coordinates:</p>

```<code>def mouseReleaseEvent(self, QMouseEvent):
    print('(', QMouseEvent.x(), ', ', QMouseEvent.y(), ')')
</code>```

Body:
I have 1024x768 resolution window, when there is a click or mouse over, i want to find the x, y values. How can i do that?

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        qbtn = QtGui.QPushButton('Quit', self)
        #qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        qbtn.clicked.connect(self.test)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)

        self.setGeometry(0, 0, 1024, 768)
        self.setWindowTitle('Quit button')
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
        self.show()

    def test(self):
      print "show the position of mouse cursor in screen resolution: x is ?? , y is ??"

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Body:
The other way to get (x,y) coordinates:

def mouseReleaseEvent(self, QMouseEvent):
    print('(', QMouseEvent.x(), ', ', QMouseEvent.y(), ')')


问:
Iterate over Json object with nested fields
I am having some difficulties to iterate over a json object. There are some nested fields, and it is getting me confused...

This is my JSON data

```<code>{
"_embedded": {
    "request_fields": [{
        "reference": null,
        "name": "Qual será o serviço?",
        "label": "Qual será o serviço?",
        "placeholder": "Qual será o serviço?",
        "values": {
            "Coloração": "Coloração",
            "Corte": "Corte",
            "Escova ": "Escova ",
            "Escova progressiva/definitiva": "Escova progressiva/definitiva",
            "Luzes": "Luzes"
        }
    }, {
        "reference": null,
        "name": "Para quem será o serviço?",
        "label": "Para quem será o serviço?",
        "placeholder": "Para quem será o serviço?",
        "values": {
            "Criança": "Criança",
            "Homem": "Homem",
            "Mulher": "Mulher"
        }
    }]
}
}
</code>```

And this is what i`ve tried so far --  update

```<code>  for (key in response) {
                    for (i in response[key].request_fields) {
                        // console.log(response[key].request_fields[i].values);
                        document.getElementById("form").innerHTML +=    "<div class='section'>" +
                                                                            "<label>" + response[key].request_fields[i].label + "</label>" +
                                                                            "<label>" for (e in response[key].request_fields[i].values) { response[key].request_fields[i].values[e] } "</label>" +
                                                                            "<label>" + response[key].request_fields[i].values{0} + "</label>" +
                                                                        "</div>" ;
                    }
                }
</code>```

Now I am getting

Uncaught SyntaxError: Unexpected token for

In my 3rd "for" to print "values"

答:
Thats because the index i is not in values, you need either another iterater, or a specific value, or just json it, or join it to a string.

```<code>for (key in response) {
    for (i in response[key].request_fields) {
        console.log(response[key].request_fields[i].values);
        var values=(()=>{
            var out="";
            for(var ii in response[key].request_fields[i].values){
                out+=ii+": "+response[key].request_fields[i].values[ii]+"\n";
            }
            return out;
        })();
        document.getElementById("form").innerHTML += "<div class='section'>" + "<label>" + response[key].request_fields[i].label + "</label>" + "<label>" +
        values + "</label>" + "</div>";
    }
}
</code>```

Body:
I am having some difficulties to iterate over a json object. There are some nested fields, and it is getting me confused...

This is my JSON data

{
"_embedded": {
    "request_fields": [{
        "reference": null,
        "name": "Qual será o serviço?",
        "label": "Qual será o serviço?",
        "placeholder": "Qual será o serviço?",
        "values": {
            "Coloração": "Coloração",
            "Corte": "Corte",
            "Escova ": "Escova ",
            "Escova progressiva/definitiva": "Escova progressiva/definitiva",
            "Luzes": "Luzes"
        }
    }, {
        "reference": null,
        "name": "Para quem será o serviço?",
        "label": "Para quem será o serviço?",
        "placeholder": "Para quem será o serviço?",
        "values": {
            "Criança": "Criança",
            "Homem": "Homem",
            "Mulher": "Mulher"
        }
    }]
}
}

And this is what i`ve tried so far --  update

  for (key in response) {
                    for (i in response[key].request_fields) {
                        // console.log(response[key].request_fields[i].values);
                        document.getElementById("form").innerHTML +=    "
" +
                                                                            "" + response[key].request_fields[i].label + "" +
                                                                            "" for (e in response[key].request_fields[i].values) { response[key].request_fields[i].values[e] } "" +
                                                                            "" + response[key].request_fields[i].values{0} + "" +
                                                                        "
" ;
                    }
                }

Now I am getting

Uncaught SyntaxError: Unexpected token for

In my 3rd "for" to print "values"

Body:
Thats because the index i is not in values, you need either another iterater, or a specific value, or just json it, or join it to a string.

for (key in response) {
    for (i in response[key].request_fields) {
        console.log(response[key].request_fields[i].values);
        var values=(()=>{
            var out="";
            for(var ii in response[key].request_fields[i].values){
                out+=ii+": "+response[key].request_fields[i].values[ii]+"\n";
            }
            return out;
        })();
        document.getElementById("form").innerHTML += "<div class='section'>" + "<label>" + response[key].request_fields[i].label + "</label>" + "<label>" +
        values + "</label>" + "</div>";
    }
}


问:
C# MVC - Passing object with list of another object inside
I want to post an object that has list of another object inside, MVC is receiving the object as null.

MVC Post

```<code>[HttpPost]
public ActionResult Create(ObjectWithList objectWithList) {
  // While debugging objectWithList has its properties null
}
</code>```

ObjectWithList

```<code>public class ObjectWithList
{
    public List<Foo> Foo { get; set; }
    public AnotherFoo AnotherFoo { get; set; }
}
</code>```

Foo and AntoherFoo are classes with normal properties, like string, etc.

Using Postman I POST:
Headers: Content-Type as application/json
Body (raw):

```<code>{
    "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "asd@asd.com"
   }
}
</code>```

If I just pass "Foo" empty:

```<code>{
    "Foo": [
            {}
    ]
    ...
</code>```

it works, (fills AnotherFoo). But as soon as i try to pass something inside Foo, MVC gets everything as null.

I'm correctly naming the properties of Foo and AnotherFoo on the JSON

答:
Try something like:</p>

```<code>var foos = {
 "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "asd@asd.com"
   }
};

$.ajax({
    url: "YourUrl",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ objectWithList: foos })
}).done(function(result){
//do something
});
</code>```

Body:
I want to post an object that has list of another object inside, MVC is receiving the object as null.

MVC Post

[HttpPost]
public ActionResult Create(ObjectWithList objectWithList) {
  // While debugging objectWithList has its properties null
}

ObjectWithList

public class ObjectWithList
{
    public List<Foo> Foo { get; set; }
    public AnotherFoo AnotherFoo { get; set; }
}

Foo and AntoherFoo are classes with normal properties, like string, etc.

Using Postman I POST:
Headers: Content-Type as application/json
Body (raw):

{
    "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "asd@asd.com"
   }
}

If I just pass "Foo" empty:

{
    "Foo": [
            {}
    ]
    ...

it works, (fills AnotherFoo). But as soon as i try to pass something inside Foo, MVC gets everything as null.

I'm correctly naming the properties of Foo and AnotherFoo on the JSON

Body:
Try something like:

var foos = {
 "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "asd@asd.com"
   }
};

$.ajax({
    url: "YourUrl",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ objectWithList: foos })
}).done(function(result){
//do something
});


问:
Android emulator and virtualbox cannot run at same time
Whenever I have Virtualbox running, I cannot start an Android emulator image (and vice versa). The error message in the AVD manager is

```<code>ioctl(KVM_CREATE_VM) failed: Device or resource busy
ko:failed to initialize KVM
</code>```

How can I make both run at the same time?

That is a Ubuntu 64 bit, all involved software is of the latest released version.

答:
I resolved it by installing HAXM 6.1.2.

Please refer to the following link for details :- https://forums.docker.com/t/cant-using-docker-for-mac-with-android-emulator-haxm/8939/11

Body:
Whenever I have Virtualbox running, I cannot start an Android emulator image (and vice versa). The error message in the AVD manager is

ioctl(KVM_CREATE_VM) failed: Device or resource busy
ko:failed to initialize KVM

How can I make both run at the same time?

That is a Ubuntu 64 bit, all involved software is of the latest released version.


问:
AngularJS converting the '/' to '%2F in url
I have a routeprovider:

 $routeProvider.when("/editor/:tripName*", {
              controller: "tripEditorController",
              controllerAs: "vm",
              templateUrl: "/views/tripEditorView.html"
          });```
</div>
</div>
</p>

<p>and in html something like :</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><td>Manage</td></code>```

But when I click on the button, my url is getting converted to something strange

/App/trips#!/#%2Feditor%2FIndia%2520Trip

Appreciate any pointer to get this fixed.

Body:
I have a routeprovider:

 $routeProvider.when("/editor/:tripName*", {
              controller: "tripEditorController",
              controllerAs: "vm",
              templateUrl: "/views/tripEditorView.html"
          });

and in html something like :

Manage

But when I click on the button, my url is getting converted to something strange

/App/trips#!/#%2Feditor%2FIndia%2520Trip

Appreciate any pointer to get this fixed.

Body: <p>only add an ! sign after hash as some cases work like that


问:
Spring data elasticsearch scan and scroll paged result is not working?
I have problems using scan and scroll as the pages from scan return strange result. I am not using them exactly as stated in the documentation.
In the method getAllExampleItems() I have a while loop on the "page.hasNext()" method, which always return false. The reason for that is the Pageable from the search query is not set on the result page, and the number of pages therefore is always 1. Another thing that is weird is that I set 100 as the result size and get 500 back! Isn't that a bug or what do I do wrong?
This is an example service:

```<code>package service;

import config.ElasticSearchConfig;
import items.ExampleItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.index.query.FilterBuilders.typeFilter;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;

@Service
public class ExampleService {

@Autowired
private ElasticsearchTemplate searchTemplate;

public List<ExampleItem> getAllExampleItems() {
    List<ExampleItem> allItems = new ArrayList<>();
    String scrollId = searchTemplate.scan(exampleItemSearchQuery(), 1000, false);
    Page<ExampleItem> page = searchTemplate.scroll(scrollId, 5000L, ExampleItem.class);
    if (page != null && page.hasContent()) {
        allItems.addAll(page.getContent());
        while (page != null && page.hasNext()) {
            page = searchTemplate.scroll(scrollId, 5000L, ExampleItem.class);
            if (page != null && page.hasContent()) {
                allItems.addAll(page.getContent());
            }
        }
    }
    return allItems;
}

private SearchQuery exampleItemSearchQuery() {
    return new NativeSearchQueryBuilder()
            .withQuery(matchAllQuery())
            .withFilter(typeFilter("exampleitem"))
            .withPageable(new PageRequest(0, 100))
            .build();
}

public void saveAllExampleItems(List<ExampleItem> items) {
         List<IndexQuery> indexQueries = new ArrayList<>();
         for (ExampleItem item : items) {
             IndexQuery qry = new IndexQuery();
             qry.setId(item.getId());
             qry.setObject(item);
             qry.setIndexName(ElasticSearchConfig.ITEMS);
             indexQueries.add(qry);
         }
         searchTemplate.bulkIndex(indexQueries);
         searchTemplate.refresh(ExampleItem.class, true);
     }
}
</code>```

Could somebody explain to me why this does not work, or what I am doing wrong?

答: I faced the same problem. Page must be not null and hasNext() is always true. hasContent() can assert the page. Replace hasNext() with hasContent() and try again....

Body:
I have problems using scan and scroll as the pages from scan return strange result. I am not using them exactly as stated in the documentation.
In the method getAllExampleItems() I have a while loop on the "page.hasNext()" method, which always return false. The reason for that is the Pageable from the search query is not set on the result page, and the number of pages therefore is always 1. Another thing that is weird is that I set 100 as the result size and get 500 back! Isn't that a bug or what do I do wrong?
This is an example service:

package service;

import config.ElasticSearchConfig;
import items.ExampleItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.index.query.FilterBuilders.typeFilter;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;

@Service
public class ExampleService {

@Autowired
private ElasticsearchTemplate searchTemplate;

public List<ExampleItem> getAllExampleItems() {
    List<ExampleItem> allItems = new ArrayList<>();
    String scrollId = searchTemplate.scan(exampleItemSearchQuery(), 1000, false);
    Page<ExampleItem> page = searchTemplate.scroll(scrollId, 5000L, ExampleItem.class);
    if (page != null && page.hasContent()) {
        allItems.addAll(page.getContent());
        while (page != null && page.hasNext()) {
            page = searchTemplate.scroll(scrollId, 5000L, ExampleItem.class);
            if (page != null && page.hasContent()) {
                allItems.addAll(page.getContent());
            }
        }
    }
    return allItems;
}

private SearchQuery exampleItemSearchQuery() {
    return new NativeSearchQueryBuilder()
            .withQuery(matchAllQuery())
            .withFilter(typeFilter("exampleitem"))
            .withPageable(new PageRequest(0, 100))
            .build();
}

public void saveAllExampleItems(List<ExampleItem> items) {
         List<IndexQuery> indexQueries = new ArrayList<>();
         for (ExampleItem item : items) {
             IndexQuery qry = new IndexQuery();
             qry.setId(item.getId());
             qry.setObject(item);
             qry.setIndexName(ElasticSearchConfig.ITEMS);
             indexQueries.add(qry);
         }
         searchTemplate.bulkIndex(indexQueries);
         searchTemplate.refresh(ExampleItem.class, true);
     }
}

Could somebody explain to me why this does not work, or what I am doing wrong?


问:
WPF Dynamic Icon Wierdness
I have an WPF application that has a dynamic icon.  Three emoji icons depending on apps state (Happy, Sad, Thinking).
I have a Binding on the Icon, with a ValueConvertor doing the work and it works great.

Or so I thought.

If I run the .exe directly from the directory, it works exactly as planned.

If I run the app via a shortcut (on the desktop), it does not show
any of the emoji, and just the default icon. (Yes the shortcut has
Start in Field set correctly)

It is almost like the it cant find the resource; example: icon = @"pack://application:,,,/Media/emojiSad.ico" because it is being run from the desktop.

答:
How are you trying to reference the icons?  I have always had no issue by setting them as embedded resources and referencing them as demonstrated at the following link.

Images in WPF as embedded resources

Your converter could return a specific image as follows:

```<code> return new Bitmap(@"images\emojiSad.ico");
</code>```

Title: WPF Dynamic Icon Wierdness

Body:
How are you trying to reference the icons?  I have always had no issue by setting them as embedded resources and referencing them as demonstrated at the following link.

Images in WPF as embedded resources

Your converter could return a specific image as follows:

 return new Bitmap(@"images\emojiSad.ico");


问:
Sort XML via attribute value PHP
So I have an XML file that I am trying to loop through in order, according to the attribute, "order".

Here is an example:

```<code><page>
<talentTrees>
<tree name="Football" order="2">
<tree name="Baseball" order="0">
<tree name="Frisbee" order="1">
</talentTrees>
</page>
</code>```

My goal is to loop through each "tree" using foreach, but I want to read them in order of the order attribute: Baseball, Frisbee, Football. (0,1,2).

Sorry for poor English, not my first language.

答:
If you have many  elements like this

```<code>$string = <<<EOS
<page>
<talentTrees>
<tree name="Football" order="2" />
<tree name="Baseball" order="0" />
<tree name="Frisbee" order="1" />
</talentTrees>
<talentTrees>
<tree name="Football2" order="1" />
<tree name="Baseball2" order="2" />
<tree name="Frisbee2" order="0" />
</talentTrees>
</page>
EOS;
</code>```

You can use foreach:

```<code>$xml = simplexml_load_string($string);

function sort_trees($t1, $t2) {
    return $t1['order'] - $t2['order'];
}

foreach($xml->talentTrees as $talentTrees){
    foreach($talentTrees->tree as $tree){
    $trees[]= $tree;
    }
    usort($trees, 'sort_trees');
    print_r($trees);
    unset($trees);
}
</code>```

output:

```<code>Array
(
    [0] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Baseball
                            [order] => 0
                        )

                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Frisbee
                            [order] => 1
                        )

                )

            [2] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Football
                            [order] => 2
                        )

                )

        )

    [1] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Frisbee2
                            [order] => 0
                        )

                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Football2
                            [order] => 1
                        )

                )

            [2] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Baseball2
                            [order] => 2
                        )

                )

        )

)
</code>```

For another example: https://stackoverflow.com/a/44379495/3506219

OwnerDisplayName: Mike

Title: Sort XML via attribute value PHP

Body:
So I have an XML file that I am trying to loop through in order, according to the attribute, "order".

Here is an example:

<page>
<talentTrees>
<tree name="Football" order="2">
<tree name="Baseball" order="0">
<tree name="Frisbee" order="1">
</talentTrees>
</page>

My goal is to loop through each "tree" using foreach, but I want to read them in order of the order attribute: Baseball, Frisbee, Football. (0,1,2).

Sorry for poor English, not my first language.

Body:
If you have many  elements like this

$string = <<<EOS
<page>
<talentTrees>
<tree name="Football" order="2" />
<tree name="Baseball" order="0" />
<tree name="Frisbee" order="1" />
</talentTrees>
<talentTrees>
<tree name="Football2" order="1" />
<tree name="Baseball2" order="2" />
<tree name="Frisbee2" order="0" />
</talentTrees>
</page>
EOS;

You can use foreach:

$xml = simplexml_load_string($string);

function sort_trees($t1, $t2) {
    return $t1['order'] - $t2['order'];
}

foreach($xml->talentTrees as $talentTrees){
    foreach($talentTrees->tree as $tree){
    $trees[]= $tree;
    }
    usort($trees, 'sort_trees');
    print_r($trees);
    unset($trees);
}

output:

Array
(
    [0] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Baseball
                            [order] => 0
                        )

                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Frisbee
                            [order] => 1
                        )

                )

            [2] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Football
                            [order] => 2
                        )

                )

        )

    [1] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Frisbee2
                            [order] => 0
                        )

                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Football2
                            [order] => 1
                        )

                )

            [2] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => Baseball2
                            [order] => 2
                        )

                )

        )

)

For another example: https://stackoverflow.com/a/44379495/3506219


问:
Select Join Table A and Table B while displaying Table B items based on Table A's foreign key
I'm in the midst of writing an SQL statement and I have a problem joining both tables (let's call it Table Enrollment & Product) based on a foreign key column from table Enrollment's column StudentID. The StudentID is read from a variable $StudentID.

Enrollment table

```<code>+--------------+-----------+-----------+

| EnrollmentID | StudentID | ProductID |

+--------------+-----------+-----------+

| 1            | 5         | 1         |

| 2            | 5         | 2         |

|3             | 7         | 2         |

|4             | 7         | 3         |

|5             | 9         | 5         |

+--------------+-----------+-----------+
</code>```

Product Table

```<code>+-----------+-------------+------------+

| ProductID | ProductName | ProductDate|

+-----------+-------------+------------+

|1          | ProductA    | 1/1/2017   |

|2          | ProductB    | 1/2/2017   |

|3          | ProductC    | 1/3/2017   |

|4          | ProductD    | 1/4/2017   |

+-----------+-------------+------------+
</code>```

This is the SQL statement so far i've come up and having trouble with:

```<code>"SELECT product.ProductName, product.ProductDate
                                FROM enrollment WHERE StudentID = '$StudentID'
                                RIGHT JOIN product ON enrollment.productid = product.productid";
</code>```

If $StudentID is 5. I want it to display all items from ProductID that is associated with StudentID 5. Which in this case, Product A and Product B will be the output.

答:
DECLARE @StudentID INT = 5; </p>

<p>SELECT p.productname,
       p.productdate
FROM   Enrollment e
       RIGHT JOIN producttable p
               ON e.productid = p.productid
WHERE  e.studentid = @StudentID </p>

Body:
I'm in the midst of writing an SQL statement and I have a problem joining both tables (let's call it Table Enrollment & Product) based on a foreign key column from table Enrollment's column StudentID. The StudentID is read from a variable $StudentID.

Enrollment table

+--------------+-----------+-----------+

| EnrollmentID | StudentID | ProductID |

+--------------+-----------+-----------+

| 1            | 5         | 1         |

| 2            | 5         | 2         |

|3             | 7         | 2         |

|4             | 7         | 3         |

|5             | 9         | 5         |

+--------------+-----------+-----------+

Product Table

+-----------+-------------+------------+

| ProductID | ProductName | ProductDate|

+-----------+-------------+------------+

|1          | ProductA    | 1/1/2017   |

|2          | ProductB    | 1/2/2017   |

|3          | ProductC    | 1/3/2017   |

|4          | ProductD    | 1/4/2017   |

+-----------+-------------+------------+

This is the SQL statement so far i've come up and having trouble with:

"SELECT product.ProductName, product.ProductDate
                                FROM enrollment WHERE StudentID = '$StudentID'
                                RIGHT JOIN product ON enrollment.productid = product.productid";

If $StudentID is 5. I want it to display all items from ProductID that is associated with StudentID 5. Which in this case, Product A and Product B will be the output.

Body:
DECLARE @StudentID INT = 5;

SELECT p.productname,
       p.productdate
FROM   Enrollment e
       RIGHT JOIN producttable p
               ON e.productid = p.productid
WHERE  e.studentid = @StudentID