问:
Button ng drop down- how to choose the item using webdriver with java
I have a button with drop down item,
if i click the button it's open the list and choose the item
below is the html

```<code><button id="btn-append-to-body" class="btn btn-primary mobile-quick-button dropdown-toggle" type="button" uib-dropdown-toggle="" aria-haspopup="true" aria-expanded="false">
<div class="clearfix">
<span class="pull-left text-left ng-binding" tabindex="0">   Select one </span>
<span class="pull-right text-right ng-binding">
</div>
</button>
<ul class="uib-dropdown-menu dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
<!-- ngRepeat: option in dropOptions -->
<li id="quickOption" class="ng-scope" role="presentation" name="quickOption" ng-repeat="option in dropOptions" ng-click="selectOption(option)" required="" tabindex="0" style="">
<a href="">
<div class="clearfix">
<span class="pull-left ng-binding">frame number</span>
</div>
</a>
</li>
<!-- end ngRepeat: option in dropOptions -->
<li id="quickOption" class="ng-scope" role="presentation" name="quickOption" ng-repeat="option in dropOptions" ng-click="selectOption(option)" required="" tabindex="0">
<a href="">
<div class="clearfix">
<span class="pull-left ng-binding">serial number</span>
</div>
</a>
</li>
</ul>
</code>```

I want to choose any one of the item from this list,

```<code>public void lookupSearch (String item){
driver.findElement(By.xpath("//*[@id='btn-append-to-body']")).click();
//then i choose/click the parameter item (i.e frame number or serial number)
}
</code>```

passing the item as parameter

please guide me how should i choose the item

答:
To click on the button with drop down item and choose any one of the item from this list you can use the following code block :</p>

```<code>public void lookupSearch (String item)
{
    driver.findElement(By.xpath("//button[@id='btn-append-to-body']/div/span[contains(.,'Select one')]")).click();
    WebDriverWait wait4elements = new WebDriverWait(driver, 10);
    List<WebElement> myElements = wait4elements.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//ul[@class='uib-dropdown-menu dropdown-menu']/li/a/div/span"), 2));
    for(WebElement elem:myElements)
        if(elem.getAttribute("innerHTML").contains(item))
        {
            elem.click();
            break;
        }
    System.out.println("Element with text as "+ item +" is selected");
}
</code>```

Body:
I have a button with drop down item,
if i click the button it's open the list and choose the item
below is the html

<button id="btn-append-to-body" class="btn btn-primary mobile-quick-button dropdown-toggle" type="button" uib-dropdown-toggle="" aria-haspopup="true" aria-expanded="false">

   Select one

</button>

frame number

serial number

I want to choose any one of the item from this list,

public void lookupSearch (String item){
driver.findElement(By.xpath("//*[@id='btn-append-to-body']")).click();
//then i choose/click the parameter item (i.e frame number or serial number)
}

passing the item as parameter

please guide me how should i choose the item

Body:
To click on the button with drop down item and choose any one of the item from this list you can use the following code block :

public void lookupSearch (String item)
{
    driver.findElement(By.xpath("//button[@id='btn-append-to-body']/div/span[contains(.,'Select one')]")).click();
    WebDriverWait wait4elements = new WebDriverWait(driver, 10);
    List<WebElement> myElements = wait4elements.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//ul[@class='uib-dropdown-menu dropdown-menu']/li/a/div/span"), 2));
    for(WebElement elem:myElements)
        if(elem.getAttribute("innerHTML").contains(item))
        {
            elem.click();
            break;
        }
    System.out.println("Element with text as "+ item +" is selected");
}


来源: stackexchange

问:
MS Access Autonumber Field Set Start Index
Is there a way to set the start index of autonumber field in ms access?

It's start on 1 and i want it start at 1000

答:
You can manually add an ID column with a specific seed. This also can be used in CREATE TABLE statements. Note that, for existing records, the ID doesn't start at 1000 but at 1.

```<code>ALTER TABLE A Add Column ID AutoIncrement(1000,1) PRIMARY KEY
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can manually add an ID column with a specific seed. This also can be used in CREATE TABLE statements. Note that, for existing records, the ID doesn't start at 1000 but at 1.

ALTER TABLE A Add Column ID AutoIncrement(1000,1) PRIMARY KEY


问:
Execute a shell command with python variables
I had script on bash where I generated username, password, ssh-key for user.
Part for creating of ssh-key:

```<code>su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N ''"
</code>```

How can I do the same in Python with os.system? I tried this:

```<code>os.system('su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"', user)
TypeError: system() takes at most 1 argument (2 given)
</code>```

Also I tried:

```<code>os.system('su user -c "ssh-keygen -f /home/user/.ssh/id_rsa -t rsa -b 4096 -N ''"')
</code>```

Of course, it doesn't work either.

答:
os.system is very close to a bash command line because it uses an underlying shell (like its cousins subprocess.call... using shell=True)

In your case, there's little interest using subprocess since your command runs a command, so you cannot really use argument protection by subprocess fully.

Pass the exact command, but the only change would be to protect the simple quotes, else python sees that as string end+string start (your string is protected by simple quotes already) and they're eliminated.

Check this simpler example:

```<code>>>> 'hello '' world'
'hello  world'
>>> 'hello \'\' world'
"hello '' world"
</code>```

that's a kind of worst-case when you cannot use either double or simple quotes to protect the string because you're using the other flavour within. In that case, escape the quotes using \:

```<code>os.system('su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N \'\'"')
</code>```

Body:
I had script on bash where I generated username, password, ssh-key for user.
Part for creating of ssh-key:

su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N ''"

How can I do the same in Python with os.system? I tried this:

os.system('su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"', user)
TypeError: system() takes at most 1 argument (2 given)

Also I tried:

os.system('su user -c "ssh-keygen -f /home/user/.ssh/id_rsa -t rsa -b 4096 -N ''"')

Of course, it doesn't work either.

Body:
os.system is very close to a bash command line because it uses an underlying shell (like its cousins subprocess.call... using shell=True)

In your case, there's little interest using subprocess since your command runs a command, so you cannot really use argument protection by subprocess fully.

Pass the exact command, but the only change would be to protect the simple quotes, else python sees that as string end+string start (your string is protected by simple quotes already) and they're eliminated.

Check this simpler example:

>>> 'hello '' world'
'hello  world'
>>> 'hello \'\' world'
"hello '' world"

that's a kind of worst-case when you cannot use either double or simple quotes to protect the string because you're using the other flavour within. In that case, escape the quotes using \:

os.system('su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N \'\'"')


问:
error: Invalid argument; while sending msgsnd() message; not matching queue ID
I was just learning IPC on linux and come up with three simple programs. One is made to create (and administrate in the feature) the message queue. The second should just send the message to the queue created by the first one. The third program is receiving data from the queue.

All programs are inheriting from the same root directory and spiting in to separate directories per source and binaries.

So lets just focus on creating and sending part, and that shall help me fix the third program as well.

add queue main.c:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define FAILED -1

int main(int argc, char *argv[]) {
  // message data
  key_t key;
  int msgqid;

  if ((key = ftok("../src/main.c", 'Z')) == FAILED) {
    perror("ftok");
    exit(1);
  }

  if ((msgqid = msgget(key, 0666 | IPC_CREAT)) == FAILED) { /* create an message queue with owner & group & others permission set to rw- */
    perror("msgget");
    exit(1);
  }

  printf("Message Queue %i with key %i, been created [press return to delete]", msgqid, key);
  getchar();

  if (msgctl(msgqid, IPC_RMID, NULL) == FAILED) {
    perror("msgctl");
    exit(1);
  }
  printf("I'm outta here! \n");

  return 0;
}
</code>```

send main.c:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/msg.h>
#include <stddef.h>
#include <string.h>

#include "../../lib/shared_msgbuf.h" /* mbuf, MSGSZ */

#define FAILED -1

int main(void) {
  char s[MSGSZ];

  printf("Enter a message: ");

  if (fgets(s, sizeof s, stdin) == NULL)
    perror("fgets");
  else
    strcpy(mbuf.mtext, s);

  printf("Connecting to the queue... \n", s);

  // Setup
  key_t key;
  int msgqid;

  if ((key = ftok("../../adqueue/src/main.c", 'Z')) == FAILED) {
    perror("ftok");
    exit(1);
  }

  if (msgqid = msgget(key, 0666) == FAILED) {
    perror("msget");
    exit(1);
  }

  printf("\n*CONNECTION ESTABLISHED* \n");
  printf("queue id: %i \n", msgqid);
  printf("queue key: %d \n", key);
  printf("message: %s \n", s);

  printf("Sending the message... \n");
  if (msgsnd(msgqid, &mbuf, MSGSZ, 0) == FAILED) {
    perror("msgsnd");
    exit(0);
  }

  return 0;
}
</code>```

So the problem is that I'm getting Invalid argument error number when trying to send the message. Looking at the data, I can't get why the id is not matching since connection to the queue seems to work...

Exemplar data:

```<code>./cadqueue
Message Queue 327680 with key 1510081535, been created [press return to delete]

./send
Enter a message: test
Connecting to the queue...

*CONNECTION ESTABLISHED*
queue id: 0
queue key: 1510081535
message: test

Sending the message...
msgsnd: Invalid argument
</code>```

答:
Your error comes from this line:

```<code>if (msgqid = msgget(key, 0666) == FAILED) {
</code>```

It should be

```<code>if ((msgqid = msgget(key, 0666)) == FAILED) {
</code>```

In first case, because of operator priority, comparison (==) is done before assignation (=).

In second case, paranthesis tells compiler what must be done first.

Body:
I was just learning IPC on linux and come up with three simple programs. One is made to create (and administrate in the feature) the message queue. The second should just send the message to the queue created by the first one. The third program is receiving data from the queue.

All programs are inheriting from the same root directory and spiting in to separate directories per source and binaries.

So lets just focus on creating and sending part, and that shall help me fix the third program as well.

add queue main.c:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define FAILED -1

int main(int argc, char *argv[]) {
  // message data
  key_t key;
  int msgqid;

  if ((key = ftok("../src/main.c", 'Z')) == FAILED) {
    perror("ftok");
    exit(1);
  }

  if ((msgqid = msgget(key, 0666 | IPC_CREAT)) == FAILED) { /* create an message queue with owner & group & others permission set to rw- */
    perror("msgget");
    exit(1);
  }

  printf("Message Queue %i with key %i, been created [press return to delete]", msgqid, key);
  getchar();

  if (msgctl(msgqid, IPC_RMID, NULL) == FAILED) {
    perror("msgctl");
    exit(1);
  }
  printf("I'm outta here! \n");

  return 0;
}

send main.c:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/msg.h>
#include <stddef.h>
#include <string.h>

#include "../../lib/shared_msgbuf.h" /* mbuf, MSGSZ */

#define FAILED -1

int main(void) {
  char s[MSGSZ];

  printf("Enter a message: ");

  if (fgets(s, sizeof s, stdin) == NULL)
    perror("fgets");
  else
    strcpy(mbuf.mtext, s);

  printf("Connecting to the queue... \n", s);

  // Setup
  key_t key;
  int msgqid;

  if ((key = ftok("../../adqueue/src/main.c", 'Z')) == FAILED) {
    perror("ftok");
    exit(1);
  }

  if (msgqid = msgget(key, 0666) == FAILED) {
    perror("msget");
    exit(1);
  }

  printf("\n*CONNECTION ESTABLISHED* \n");
  printf("queue id: %i \n", msgqid);
  printf("queue key: %d \n", key);
  printf("message: %s \n", s);

  printf("Sending the message... \n");
  if (msgsnd(msgqid, &mbuf, MSGSZ, 0) == FAILED) {
    perror("msgsnd");
    exit(0);
  }

  return 0;
}

So the problem is that I'm getting Invalid argument error number when trying to send the message. Looking at the data, I can't get why the id is not matching since connection to the queue seems to work...

Exemplar data:

./cadqueue
Message Queue 327680 with key 1510081535, been created [press return to delete]

./send
Enter a message: test
Connecting to the queue...

*CONNECTION ESTABLISHED*
queue id: 0
queue key: 1510081535
message: test

Sending the message...
msgsnd: Invalid argument

Body:
Your error comes from this line:

if (msgqid = msgget(key, 0666) == FAILED) {

It should be

if ((msgqid = msgget(key, 0666)) == FAILED) {

In first case, because of operator priority, comparison (==) is done before assignation (=).

In second case, paranthesis tells compiler what must be done first.


问:
Is it possible to automate the testing of a dynamically generated PDF file from a web application?
I see that it is possible to extract the text and images from a PDF file and test them. What I really want is to automate the testing of some tables with indefinite data in the PDF file which will be generated by the application. The generated PDF file can also be a report with data extracted from many tables. </p>

答: I think PDFUtil is your solution to solve the problem</p>


问:
Building Tensorflow 1.4.0 from sources for C/C++ in Ubuntu 17.10
I am trying to build Tensorflow 1.4.0 from sources for C/C++ in 64-bit Ubuntu 17.10. I tried to follow the instructions in Tensorflow website and other website for C++ using Bazel and summarize them as follows:

```<code>cd tensorflow
./configure
(select N for all the options)
bazel build --config=opt --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=0" --local_resources 2048,.5,1.0 //tensorflow:libtensorflow_cc.so //tensorflow:libtensorflow_framework.so //tensorflow/tools/pip_package:build_pip_package
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
sudo -H pip3 install /tmp/tensorflow_pkg/tensorflow-1.4.0rc1-cp36-cp36m-linux_x86_64.whl
</code>```

When I tried to build a simple test program and include tensorflow/core/public/session.h in Eclipse (with the include path set to the tensorflow root folder downloaded from git), it complained several things:

Missing Google's protobuf common.h in device_attributes.pb.h (I cannot use apt-get to install protobuf as it will complain version too old - lower than 3.0.0.4 check in device_attributes.pb.h). I downloaded the latest protobuf and follow the instructions to install it

Missing Eigen3's Tensor file in tensor.h, where tensor.h includes Tensor file in [tensorflow directory]/third_party/eigen3/unsupported/Eigen/CXX11/Tensor, and [tensorflow directory]/third_party/eigen3/unsupported/Eigen/CXX11/Tensor includes the missing [/usr/include/eigen3/]unsupported/Eigen/CXX11/Tensor file provided by libeigen3-dev. I apt-get to install libeigen3-dev.

After I installed libeigen3-dev, I added /usr/include/eigen3 to the Eclipse's include path as the Tensor file in tensorflow directory is unable to find the Tensor file in /usr/include (with extra eigen3 directory).

Missing nsync_cv.h file in mutex.h. I added nsync folder in tensorflow directory to the include path.

In summary, I have added the following paths to the include path in Eclipse:

[tensorflow directory]/

[tensorflow directory]/bazel-genfiles

[tensorflow directory]/bazel-tensorflow/external/nsync/public

/usr/include/eigen3

I added the library path [tensorflow directory]/bazel-bin/tensorflow with the following libraries:

tensorflow

tensorflow_cc

tensorflow_framework

I have also added -std=c++11 to the GCC C++ compiler and GCC C++ Linker in the Eclipse's project settings. In the end it encountered a linker error:

```<code>[tensorflow directory]/tensorflow/core/platform/default/logging.h:187: undefined reference to `tensorflow::internal::CheckOpMessageBuilder::NewString[abi::cxx11]()'
</code>```

I have seen a thread discussing similar issue but I did set -D_GLIBCXX_USE_CXX11_ABI=0 and Ubuntu 17.10 is using gcc5 or above.

Please kindly suggest how to fix the linker error. Many thanks!

答:
Officially, you have to create your C++ project in tensorflow sourcetree, write BUILD file and compile it using bazel. Look at this.

I wrote a blog post: https://tuanphuc.github.io/standalone-tensorflow-cpp/ giving detailed instructions to make a standalone C++ Tensorflow with configuration:

  -  Ubuntu 17.10
  -  gcc 7.2.0
  -  tensorflow 1.4.0
  -  Python 2 or 3
  -  cmake 3.9.6
  -  Eigen 3.3.4
  -  Protobuf (master branch)
  -  Googletest (master branch)
  -  bazel

Hope it helps

References:

Packaged TensorFlow C++ library for bazel-independent use

graph.pb.h missing

Body:
I am trying to build Tensorflow 1.4.0 from sources for C/C++ in 64-bit Ubuntu 17.10. I tried to follow the instructions in Tensorflow website and other website for C++ using Bazel and summarize them as follows:

cd tensorflow
./configure
(select N for all the options)
bazel build --config=opt --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=0" --local_resources 2048,.5,1.0 //tensorflow:libtensorflow_cc.so //tensorflow:libtensorflow_framework.so //tensorflow/tools/pip_package:build_pip_package
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
sudo -H pip3 install /tmp/tensorflow_pkg/tensorflow-1.4.0rc1-cp36-cp36m-linux_x86_64.whl

When I tried to build a simple test program and include tensorflow/core/public/session.h in Eclipse (with the include path set to the tensorflow root folder downloaded from git), it complained several things:

Missing Google's protobuf common.h in device_attributes.pb.h (I cannot use apt-get to install protobuf as it will complain version too old - lower than 3.0.0.4 check in device_attributes.pb.h). I downloaded the latest protobuf and follow the instructions to install it

Missing Eigen3's Tensor file in tensor.h, where tensor.h includes Tensor file in [tensorflow directory]/third_party/eigen3/unsupported/Eigen/CXX11/Tensor, and [tensorflow directory]/third_party/eigen3/unsupported/Eigen/CXX11/Tensor includes the missing [/usr/include/eigen3/]unsupported/Eigen/CXX11/Tensor file provided by libeigen3-dev. I apt-get to install libeigen3-dev.

After I installed libeigen3-dev, I added /usr/include/eigen3 to the Eclipse's include path as the Tensor file in tensorflow directory is unable to find the Tensor file in /usr/include (with extra eigen3 directory).

Missing nsync_cv.h file in mutex.h. I added nsync folder in tensorflow directory to the include path.

In summary, I have added the following paths to the include path in Eclipse:

[tensorflow directory]/

[tensorflow directory]/bazel-genfiles

[tensorflow directory]/bazel-tensorflow/external/nsync/public

/usr/include/eigen3

I added the library path [tensorflow directory]/bazel-bin/tensorflow with the following libraries:

tensorflow

tensorflow_cc

tensorflow_framework

I have also added -std=c++11 to the GCC C++ compiler and GCC C++ Linker in the Eclipse's project settings. In the end it encountered a linker error:

[tensorflow directory]/tensorflow/core/platform/default/logging.h:187: undefined reference to `tensorflow::internal::CheckOpMessageBuilder::NewString[abi::cxx11]()'

I have seen a thread discussing similar issue but I did set -D_GLIBCXX_USE_CXX11_ABI=0 and Ubuntu 17.10 is using gcc5 or above.

Please kindly suggest how to fix the linker error. Many thanks!


问:
Get results from Spring call of Mongo MapReduce
I try to get the results of my mapReduce function on MongoDB directly after the call of my function in my Java Spring code :

```<code>MongoOperations mongoOperations = new MongoTemplate(new SimpleMongoDbFactory(new Mongo("xxx.xxx.xxx.xxx"), "xxx"));
    MapReduceResults<Object> results = mongoOperations.mapReduce(
            "counters",
            mapFunctionCounters,
            reduceFunctionCounters,
            new MapReduceOptions().scopeVariables(scopeVariables).outputTypeInline(),
            Object.class);

    String jsonString = "";
    ObjectMapper mapper = new ObjectMapper();
    try {
        jsonString = mapper.writeValueAsString(results);
        System.out.println("jsonString = " + jsonString);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

Console result :

```<code>jsonString = {"rawResults":null,"outputCollection":null,"timing":{"mapTime":-1,"emitLoopTime":-1,"totalTime":576},"counts":{"inputCount":100287,"emitCount":7102,"outputCount":104}}
</code>```

The mapReduce works well when I specify a collection output, but I don't understand how to get the results directly like with the out: {inline: 1} property used in the mongodb command.

Someone to help me please?

答:
I just had to add the following class :

```<code>@AllArgsConstructor
@Setter
@Getter
public class ValueObject {
    private int id;
    private float value;

    @Override
    public String toString() {
        return "ValueObject [id=" + id + ", value=" + value + "]";
    }
}
</code>```

Then change the way to display the result :

```<code>MapReduceResults<ValueObject> results = mongoOperations.mapReduce(
            "counters",
            mapFunctionCounters,
            reduceFunctionCounters,
            new MapReduceOptions().scopeVariables(scopeVariables).outputTypeInline(),
            ValueObject.class
            );

    for (ValueObject valueObject : results) {
        System.out.println(valueObject.getId());
    }
</code>```

Body:
I try to get the results of my mapReduce function on MongoDB directly after the call of my function in my Java Spring code :

MongoOperations mongoOperations = new MongoTemplate(new SimpleMongoDbFactory(new Mongo("xxx.xxx.xxx.xxx"), "xxx"));
    MapReduceResults<Object> results = mongoOperations.mapReduce(
            "counters",
            mapFunctionCounters,
            reduceFunctionCounters,
            new MapReduceOptions().scopeVariables(scopeVariables).outputTypeInline(),
            Object.class);

    String jsonString = "";
    ObjectMapper mapper = new ObjectMapper();
    try {
        jsonString = mapper.writeValueAsString(results);
        System.out.println("jsonString = " + jsonString);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Console result :

jsonString = {"rawResults":null,"outputCollection":null,"timing":{"mapTime":-1,"emitLoopTime":-1,"totalTime":576},"counts":{"inputCount":100287,"emitCount":7102,"outputCount":104}}

The mapReduce works well when I specify a collection output, but I don't understand how to get the results directly like with the out: {inline: 1} property used in the mongodb command.

Someone to help me please?

Body:
I just had to add the following class :

@AllArgsConstructor
@Setter
@Getter
public class ValueObject {
    private int id;
    private float value;

    @Override
    public String toString() {
        return "ValueObject [id=" + id + ", value=" + value + "]";
    }
}

Then change the way to display the result :

MapReduceResults<ValueObject> results = mongoOperations.mapReduce(
            "counters",
            mapFunctionCounters,
            reduceFunctionCounters,
            new MapReduceOptions().scopeVariables(scopeVariables).outputTypeInline(),
            ValueObject.class
            );

    for (ValueObject valueObject : results) {
        System.out.println(valueObject.getId());
    }


问:
UIImageView with sticker and adding Gesture on Sticker
I have one ImageView and sticker on it now I want to add Gesture on that sticker, Everything is working properly but ,my sticker is going out from UIImageView's layer as shown in Image. I want sticker's gesture within ImageView's Boundaries only.

Following is my Code:

```<code>func addStickers(image: UIImage) {

    gesture = "Stickers"

    imgSticker  = UIImageView(frame: CGRect.init(x: 0.0, y: 0.0, width: 80, height: 80))
    imgSticker.center = view.center
    imgSticker.image = image
    imgSticker.contentMode = UIViewContentMode.scaleAspectFill
    imgSticker.isUserInteractionEnabled = true

    self.view.addSubview(imgSticker)
    //imgImage.addSubview(imgSticker)

    panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(handlePanGesture(_:)))
    panGesture.delegate = self

    pinchGesture = UIPinchGestureRecognizer.init(target: self, action: #selector(handlePinchGesture(_:)))
    pinchGesture.delegate = self

    rotateGesture = UIRotationGestureRecognizer.init(target: self, action: #selector(handleRotateGesture(_:)))
    rotateGesture.delegate = self

    imgSticker.addGestureRecognizer(panGesture)
    imgSticker.addGestureRecognizer(pinchGesture)
    imgSticker.addGestureRecognizer(rotateGesture)
}
</code>```

I am calling this function and my handle methods as below:

```<code>                addStickers(image: #imageLiteral(resourceName: "Sticker1.png"))
</code>```

func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {

```<code>    if gesture == "Stickers" {
        let recognizerCenter = recognizer.location(in: self .view)
        imgSticker.center = recognizerCenter

    } else {
        let recognizerCenter = recognizer.location(in: self.view)
        txtLabel.center = recognizerCenter
    }

}

func handlePinchGesture(_ recognizer: UIPinchGestureRecognizer) {
    if gesture == "Stickers" {
         imgSticker.transform = imgSticker.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
         recognizer.scale = 1.0

    } else {
        txtLabel.transform = txtLabel.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
        recognizer.scale = 1.0
    }

}

func handleRotateGesture(_ recognizer: UIRotationGestureRecognizer) {

    if gesture == "Stickers" {
         imgSticker.transform = imgSticker.transform.rotated(by: recognizer.rotation)
         recognizer.rotation = 0.0

    } else {
        txtLabel.transform = txtLabel.transform.rotated(by: recognizer.rotation)
        recognizer.rotation = 0.0
    }

}
</code>```

答:
Try replacing self.view in self.view.addSubview(imgSticker) to the ImageView of your image that is being edited, the one you put stickers onto it. Hope it helps.

So, it should be like this - imageView.addSubview(stickerOnImg). I had same issue before and this worked for me.

Body:
I have one ImageView and sticker on it now I want to add Gesture on that sticker, Everything is working properly but ,my sticker is going out from UIImageView's layer as shown in Image. I want sticker's gesture within ImageView's Boundaries only.

Following is my Code:

func addStickers(image: UIImage) {

    gesture = "Stickers"

    imgSticker  = UIImageView(frame: CGRect.init(x: 0.0, y: 0.0, width: 80, height: 80))
    imgSticker.center = view.center
    imgSticker.image = image
    imgSticker.contentMode = UIViewContentMode.scaleAspectFill
    imgSticker.isUserInteractionEnabled = true

    self.view.addSubview(imgSticker)
    //imgImage.addSubview(imgSticker)

    panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(handlePanGesture(_:)))
    panGesture.delegate = self

    pinchGesture = UIPinchGestureRecognizer.init(target: self, action: #selector(handlePinchGesture(_:)))
    pinchGesture.delegate = self

    rotateGesture = UIRotationGestureRecognizer.init(target: self, action: #selector(handleRotateGesture(_:)))
    rotateGesture.delegate = self

    imgSticker.addGestureRecognizer(panGesture)
    imgSticker.addGestureRecognizer(pinchGesture)
    imgSticker.addGestureRecognizer(rotateGesture)
}

I am calling this function and my handle methods as below:

                addStickers(image: #imageLiteral(resourceName: "Sticker1.png"))

func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {

    if gesture == "Stickers" {
        let recognizerCenter = recognizer.location(in: self .view)
        imgSticker.center = recognizerCenter

    } else {
        let recognizerCenter = recognizer.location(in: self.view)
        txtLabel.center = recognizerCenter
    }

}

func handlePinchGesture(_ recognizer: UIPinchGestureRecognizer) {
    if gesture == "Stickers" {
         imgSticker.transform = imgSticker.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
         recognizer.scale = 1.0

    } else {
        txtLabel.transform = txtLabel.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
        recognizer.scale = 1.0
    }

}

func handleRotateGesture(_ recognizer: UIRotationGestureRecognizer) {

    if gesture == "Stickers" {
         imgSticker.transform = imgSticker.transform.rotated(by: recognizer.rotation)
         recognizer.rotation = 0.0

    } else {
        txtLabel.transform = txtLabel.transform.rotated(by: recognizer.rotation)
        recognizer.rotation = 0.0
    }

}


问:
How bright is part of UIImage?
Have a label over part of an UIImageView. If image is too bright white text can not read. Any easy way to detect how bright portion of the image?

答:
There is no "easy" way of doing it at least for processor. For developer it is easiest to get access to raw RGBA buffer of image data and find out what is the average color. Then convert that color to HSV and check saturation to determine the brightness. You can even use GPU to make things a bit quicker; openGL should be perfect for that.

But before you get too far: The result will most likely not be what you are looking for. There are always cases that will make your text unreadable no matter what color they are. Consider you have a white text and will convert it to black once image is too bright. But then the image consists purely of black and white stripes so that every odd letter is over white stripe and the rest are on black. The text is simply unreadable.

I suggest you try with stroke, dropping shadows or adding a background. You can for instance have white text on a label and use semitransparent black background color with some layer corner radius. The background will barely be visible on all but the brightest images and text will always be readable.

Title: How bright is part of UIImage?


问:
How to get device make and model on iOS?
I was wondering if it's possible to determine what kind of iPhone (for example) the currentdevice is? I know it's possible to get the model through

    NSString *deviceType = [[UIDevice currentDevice] model];

which will just return whether I have an "iPhone" or an "iPod", BUT I was wondering if it's possible to detect/know if I have an iPhone 3GS vs. and iPhone 4 vs. an iPhone 4S (in actuality, all I really want to do is determine if I have a 3G or not, because I'm doing fairly graphics intensive stuff).

So yeah, let me know, thank you!

答:
If you have a plist of devices (eg maintained by @Tib above in https://stackoverflow.com/a/17655825/849616) to handle it if Swift 3 you'd use:

```<code>extension UIDevice {
    /// Fetches the information about the name of the device.
    ///
    /// - Returns: Should return meaningful device name, if not found will return device system code.
    public static func modelName() -> String {
        let physicalName = deviceSystemCode()
        if let deviceTypes = deviceTypes(), let modelName = deviceTypes[physicalName] as? String {
            return modelName
        }
        return physicalName
    }
}

private extension UIDevice {
    /// Fetches from system the code of the device
    static func deviceSystemCode() -> String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        return identifier
    }

    /// Fetches the plist entries from plist maintained in https://stackoverflow.com/a/17655825/849616
    ///
    /// - Returns: A dictionary with pairs of deviceSystemCode <-> meaningfulDeviceName.
    static func deviceTypes() -> NSDictionary? {
        if let fileUrl = Bundle.main.url(forResource: "your plist name", withExtension: "plist"),
            let configurationDictionary = NSDictionary(contentsOf: fileUrl) {
            return configurationDictionary
        }
        return nil
    }
}
</code>```

Later you can call it using UIDevice.modelName().

Additional credits go to @Tib (for plist), @Aniruddh Joshi (for deviceSystemCode() function).

Body:
If you have a plist of devices (eg maintained by @Tib above in https://stackoverflow.com/a/17655825/849616) to handle it if Swift 3 you'd use:

extension UIDevice {
    /// Fetches the information about the name of the device.
    ///
    /// - Returns: Should return meaningful device name, if not found will return device system code.
    public static func modelName() -> String {
        let physicalName = deviceSystemCode()
        if let deviceTypes = deviceTypes(), let modelName = deviceTypes[physicalName] as? String {
            return modelName
        }
        return physicalName
    }
}

private extension UIDevice {
    /// Fetches from system the code of the device
    static func deviceSystemCode() -> String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        return identifier
    }

    /// Fetches the plist entries from plist maintained in https://stackoverflow.com/a/17655825/849616
    ///
    /// - Returns: A dictionary with pairs of deviceSystemCode <-> meaningfulDeviceName.
    static func deviceTypes() -> NSDictionary? {
        if let fileUrl = Bundle.main.url(forResource: "your plist name", withExtension: "plist"),
            let configurationDictionary = NSDictionary(contentsOf: fileUrl) {
            return configurationDictionary
        }
        return nil
    }
}

Later you can call it using UIDevice.modelName().

Additional credits go to @Tib (for plist), @Aniruddh Joshi (for deviceSystemCode() function).


问:
WinForms: Is there a concept of associating a label with a textbox?
I'm using Visual Studio 2010 with C#.  Is there a concept in Windows Forms development of somehow linking a label with is text box?  Something so that they move together as a unit?  In the ASP.NET world, there is the AssociatedControlId property of the label control.  I also think I remember MS Access form designer having some way of associating (or linking) labels with controls.  Does this feature even exist in Visual Studio world?

If not, how do you group labels with controls such that if you move a text box you don't have to manually move the label also?

答:
If you want to group labels with other controls (or group controls in general), then use the System.Windows.Forms.Panel control. The specific purpose of the Panel control is to group collections of controls.

More information Panel Class (System.Windows.Forms)

If you want a higher degree of control (rather than using a Panel), then you could create a UserControl, that encapsulates a Label and a Control.

ContentLicense: CC BY-SA 2.5


问:
How can I skip before action for token validations controller in Devise?
I use before action to require params in every route except auth from Devise.
So, I want to skip the before action on token validation.
I already skip in session controller and registration controller by overriding them but I don't know how to override the token validation controller.</p>

答:
You can prevent filters from running before particular actions with the skip_before_action callback, like:

```<code>skip_before_action :verify_authenticity_token, only: :action
</code>```

Where action is the method where you want to disable verify_authenticity_token.

Body:
You can prevent filters from running before particular actions with the skip_before_action callback, like:

skip_before_action :verify_authenticity_token, only: :action

Where action is the method where you want to disable verify_authenticity_token.


问:
Loading font native-base error
I'm getting the error: You started loading 'Roboto_medium', but used it before it finished loading when using native base.

I've followed the instructions in the official page.

To create react native app I'm using create-react-native-app.

App.js

```<code>export default class App extends React.Component {

async componentWillMount() {
  await Expo.Font.loadAsync({
  'Roboto': require('native-base/Fonts/Roboto.ttf'),
  'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf'),
  'Ionicons': require('@expo/vector-icons/fonts/Ionicons.ttf'),
 });
}

 render() {
   return (
    <Container>
      <StatusBar hidden={true} />

    <Button>
      <Text>
        Button
      </Text>
    </Button>

    <ListaItens />
    </Container>
  );
}
}
</code>```

答:
you need to wait till the fonts get loaded. You can do something like this</p>

```<code>import React from "react";
import { StatusBar } from "react-native";
import { Container, Button, text, ListItem, Text } from "native-base";
import Expo from "expo";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { loading: true };
  }

  async componentWillMount() {
    await Expo.Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      Ionicons: require("@expo/vector-icons/fonts/Ionicons.ttf"),
    });
    this.setState({ loading: false });
  }

  render() {
    if (this.state.loading) {
      return <Expo.AppLoading />;
    }
    return (
      <Container>
        <StatusBar hidden={true} />

        <Button>
          <Text>Button</Text>
        </Button>

        <ListItem />
      </Container>
    );
  }
}
</code>```

Title: Loading font native-base error

Body:
I'm getting the error: You started loading 'Roboto_medium', but used it before it finished loading when using native base.

I've followed the instructions in the official page.

To create react native app I'm using create-react-native-app.

App.js

export default class App extends React.Component {

async componentWillMount() {
  await Expo.Font.loadAsync({
  'Roboto': require('native-base/Fonts/Roboto.ttf'),
  'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf'),
  'Ionicons': require('@expo/vector-icons/fonts/Ionicons.ttf'),
 });
}

 render() {
   return (
    <Container>
      <StatusBar hidden={true} />

    <Button>
      <Text>
        Button
      </Text>
    </Button>

    <ListaItens />
    </Container>
  );
}
}

Body:
you need to wait till the fonts get loaded. You can do something like this

import React from "react";
import { StatusBar } from "react-native";
import { Container, Button, text, ListItem, Text } from "native-base";
import Expo from "expo";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { loading: true };
  }

  async componentWillMount() {
    await Expo.Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      Ionicons: require("@expo/vector-icons/fonts/Ionicons.ttf"),
    });
    this.setState({ loading: false });
  }

  render() {
    if (this.state.loading) {
      return <Expo.AppLoading />;
    }
    return (
      <Container>
        <StatusBar hidden={true} />

        <Button>
          <Text>Button</Text>
        </Button>

        <ListItem />
      </Container>
    );
  }
}


问:
Efficient Prime Number Computing Program Java
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.

One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.

However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.

For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.

So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.

Here's my code, I can't figure out why it's not working

```<code>    Scanner sc = new Scanner (System.in);
    System.out.print ("Enter the upper limit: ");
    int high = sc.nextInt();

    boolean isPrime = true;
    int[] primearray = new int[0];

    for (int num = 1; num <= high; num++)
    {
        for (int x: primearray)
        {
            if (num%x==0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            int size = primearray.length;
            primearray = new int[size+1];
            primearray [size] = num;

            System.out.println (num);
        }
    }
</code>```

答:
You should use a Sieve of Eratosthenes to find primes, rather than testing each number for divisibility; that method is far slower than sieving. Here is an implementation of sieving from my blog:</p>

```<code>public static LinkedList sieve(int n)
{
    BitSet b = new BitSet(n);
    LinkedList ps = new LinkedList();

    b.set(0,n);

    for (int p=2; p<n; p++)
    {
        if (b.get(p))
        {
            ps.add(p);
            for (int i=p+p; i<n; i+=p)
            {
                b.clear(i);
            }
        }
    }

    return ps;
}
</code>```

Body:
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.

One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.

However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.

For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.

So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.

Here's my code, I can't figure out why it's not working

    Scanner sc = new Scanner (System.in);
    System.out.print ("Enter the upper limit: ");
    int high = sc.nextInt();

    boolean isPrime = true;
    int[] primearray = new int[0];

    for (int num = 1; num <= high; num++)
    {
        for (int x: primearray)
        {
            if (num%x==0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            int size = primearray.length;
            primearray = new int[size+1];
            primearray [size] = num;

            System.out.println (num);
        }
    }

Body:
You should use a Sieve of Eratosthenes to find primes, rather than testing each number for divisibility; that method is far slower than sieving. Here is an implementation of sieving from my blog:

public static LinkedList sieve(int n)
{
    BitSet b = new BitSet(n);
    LinkedList ps = new LinkedList();

    b.set(0,n);

    for (int p=2; p<n; p++)
    {
        if (b.get(p))
        {
            ps.add(p);
            for (int i=p+p; i<n; i+=p)
            {
                b.clear(i);
            }
        }
    }

    return ps;
}


问:
How to call helper function in laravel 5.5
I am using laravel 5.5. I have created a helper.php in app\Http. I am calling this helper in my blade file by using

```<code>{!! Helper::functionName() !!}
</code>```

this is working fine. but i want to hold this helper result in a variable like

```<code>{!! $Result=Helper::functionName() !!}
</code>```

But currently this is printing this result. How to solve this. please help.
So that i can make any if condition on this $Result.

In my helpers.php

```<code>namespace App\Http\Helpers;

class Helper
{
    public static function functionName()
    {
       return "mydata";
    }
}
</code>```

答: There is no point to use helper like this. You should run the helper in controller and pass calculated data into view. In most cases you shouldn't set any variables in views or make any calculations - those should be passed from controller to view and view should only use them.</p>

Body:
I am using laravel 5.5. I have created a helper.php in app\Http. I am calling this helper in my blade file by using

{!! Helper::functionName() !!}

this is working fine. but i want to hold this helper result in a variable like

{!! $Result=Helper::functionName() !!}

But currently this is printing this result. How to solve this. please help.
So that i can make any if condition on this $Result.

In my helpers.php

namespace App\Http\Helpers;

class Helper
{
    public static function functionName()
    {
       return "mydata";
    }
}


问:
Mouse hover on image parts show hints
I have an html page with simple, static image like this : Image

I need a way that putting mouse (hover) on any object, for example - "BED" to get a tooltip that - "There is bed".

I know how hover works at pure html, with blocks or any  teg, but I need a way of doing/tracking the user cursor, and when it enters in specific zone, to show the hint. Probably some JS required. How can I setup this unknown geometric forms with their coordinates to achieve my goal?

答:
No JS script needed :)

You can use image maps .. they are old but should work as you expected.. you can run it and see title when you hover over kitchen and bad

I used this webpage to 'generate' rectangles and area over the image or hotsports..

<map name="image-map">
    <area target="" alt="This is bad" title="This is bad" href="" coords="520,132,451,48" shape="rect">
    <area target="" alt="This is kitchen" title="This is kitchen" href="" coords="343,204,254,55" shape="rect">
</map>```

Title: Mouse hover on image parts show hints

Body:
No JS script needed :)

You can use image maps .. they are old but should work as you expected.. you can run it and see title when you hover over kitchen and bad

I used this webpage to 'generate' rectangles and area over the image or hotsports..

<img src="https://www.edrawsoft.com/symbols/simple-home-floorplan.png" usemap="#image-map">

<map name="image-map">
    <area target="" alt="This is bad" title="This is bad" href="" coords="520,132,451,48" shape="rect">
    <area target="" alt="This is kitchen" title="This is kitchen" href="" coords="343,204,254,55" shape="rect">
</map>


问:
How to make a nested ordered list from array data
I have data like this:

```<code>var array = ["a", "b", "c", "d", "e"];
</code>```

I want this data converted like this:

```<code><ol>
 <li>a</li>
   <ol>
    <li>b</li>
     <ol>
      <li>c</li>
       <ol>
        <li>d</li>
       </ol>
     </ol>
  </ol>
</code>```

I will try this:

```<code>var makeNestedList = () => {
  $.each(array, function(i, el) {
    nested += '<ol>';
    nested += '<li>' + el + '</li>';
    makeNestedList();
    nested += '</ol>';
  });
};
</code>```

But why is the result empty?

答:
You can use something like this:

Logic

loop over array in reverse order.

For every item, create a ordered list.

Append this list to next list.

function createOrderedList(items) {
  var ol = document.createElement('ol');
  items.forEach(function(item){
    ol.appendChild(createListItem(item))
  })
  return ol;
}

function createListItem(item) {
  var li = document.createElement('li');
  li.textContent = item;
  return li;
}

var array = ["a", "b", "c", "d", "e"];

var list = array.reduceRight(function(p, c){
  var el = createOrderedList([c]);
  if(p === null) {
    p = el;
  }
  else {
    el.appendChild(p);
  }
  return el;
}, null);

document.querySelector('.content').appendChild(list);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='content'/></code>```

Body:
I have data like this:

var array = ["a", "b", "c", "d", "e"];

I want this data converted like this:

a

b

c

d

I will try this:

var makeNestedList = () => {
  $.each(array, function(i, el) {
    nested += '
';
    nested += '
' + el + '
';
    makeNestedList();
    nested += '
';
  });
};

But why is the result empty?

Body:
You can use something like this:

Logic

loop over array in reverse order.

For every item, create a ordered list.

Append this list to next list.

function createOrderedList(items) {
  var ol = document.createElement('ol');
  items.forEach(function(item){
    ol.appendChild(createListItem(item))
  })
  return ol;
}

function createListItem(item) {
  var li = document.createElement('li');
  li.textContent = item;
  return li;
}

var array = ["a", "b", "c", "d", "e"];

var list = array.reduceRight(function(p, c){
  var el = createOrderedList([c]);
  if(p === null) {
    p = el;
  }
  else {
    el.appendChild(p);
  }
  return el;
}, null);

document.querySelector('.content').appendChild(list);

<div class='content'/>


问:
Font sizes on different pages
Ok so I'm not sure if questions like this are allowed on here so if not please tell me and I will remove it. My question is about whether font sizes should be the same on all pages.

Here's my situation. I have several headings spread across multiple pages on a website which I am creating. They all use the same styles but as they all have different character lengths when the screen gets smaller some of the headings start breaking at points which just make the website look rubbish. To make a couple of these heading look good I have had to use a font size of 16px, which isn't ideal as the the body text is 16px but still it looks better than what it did look like.

So what would you usually do in this situation? Would you keep all the headings the same size to keep in theme with the other pages? or is it ok to have some smaller than others? will the user even notice?

答:
You can use media queries to redefine your size like this :

    @media screen and (max-width: 640px) {
  .yourClass {
   font-size:14px;
  }
}```

Title: Font sizes on different pages


问:
Add PostgreSQL to vapor project
I added .package(url: "https://github.com/vapor-community/postgresql-provider.git", .upToNextMajor(from: "2.1.0")) to my Package.swift file, ran vapor update and let it regenerate the Xcode project.  When I then add the import of PostgreSQLProvider Xcode can't find it.  I already have postgresql and pkg-config installed via homebrew.

I'm using Xcode 9 and Swift 4

答: I had this problem too and wasn't sufficient with vapor xcode because it only regenerate the project and don't fetch the new dependencies like postgree you're adding, to solve this use vapor fetch and later vapor xcode, both commands with the project closed</p>

Title: Add PostgreSQL to vapor project


问:
c# mocking IFormFile CopyToAsync() method
I am working on a unit test for an async function that converts a list of IFormFile to a list of my own arbitrary database file classes.

The method that converts the file data to a byte array is:

```<code>internal async Task<List<File>> ConvertFormFilesToFiles(ICollection<IFormFile> formFiles)
{
    var file = new File
    {
        InsertDateTime = DateTime.Now,
        LastChangeDateTime = DateTime.Now
    };
    if (formFile.Length > 0)
    {
        using (var memoryStream = new MemoryStream())
        {
            await formFile.CopyToAsync(memoryStream, CancellationToken.None);
            file.FileData = memoryStream.ToArray();
        }
    }
    // ...
}
</code>```

The function receives an ICollection of IFormFiles so it is mockable.

For now I have test code like this:

```<code>//Arrange
var fileConverter = new FilesConverter();
using (var fileStream = new FileStream("Files/uploadme.txt", FileMode.Open, FileAccess.Read))
{
    using (var memoryStream = new MemoryStream())
    {
        var newMemoryStream = new MemoryStream();
        fileStream.CopyTo(memoryStream);
        FormFileMock.Setup(f => f.CopyToAsync(newMemoryStream, CancellationToken.None)).Returns(Task.CompletedTask);
        // some other setups

        //Act
        var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { FormFileMock.Object });
        //Assert
        Assert.IsTrue(result.Any());
    }
}
</code>```

The newMemoryStream variable is created because the function calls the CopyToAsync method with a new and empty memorystream (I'm not sure if this is necessary).

The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

答:
I know this might be unpopular because using a mock framework is totally "in" these days, but why not simply leave the framework be framework and go the simple, easy way? You can create a FormFile without any mocking. Just the real deal:

```<code>var fileConverter = new FilesConverter(FilesConverterLoggerMock.Object, FileDataMock.Object);

// access to a real file should really not be in a "unit" test, but anyway:
using (var stream = new MemoryStream(File.ReadAllBytes("Files/uploadme.txt"))
{
  // create a REAL form file
  var formFile = new FormFile(stream , 0, stream.Length, "name", "filename");

  //Act
  var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { formFile });

  //Assert
  Assert.IsTrue(result.Any());
}
</code>```

Body:
I am working on a unit test for an async function that converts a list of IFormFile to a list of my own arbitrary database file classes.

The method that converts the file data to a byte array is:

internal async Task<List<File>> ConvertFormFilesToFiles(ICollection<IFormFile> formFiles)
{
    var file = new File
    {
        InsertDateTime = DateTime.Now,
        LastChangeDateTime = DateTime.Now
    };
    if (formFile.Length > 0)
    {
        using (var memoryStream = new MemoryStream())
        {
            await formFile.CopyToAsync(memoryStream, CancellationToken.None);
            file.FileData = memoryStream.ToArray();
        }
    }
    // ...
}

The function receives an ICollection of IFormFiles so it is mockable.

For now I have test code like this:

//Arrange
var fileConverter = new FilesConverter();
using (var fileStream = new FileStream("Files/uploadme.txt", FileMode.Open, FileAccess.Read))
{
    using (var memoryStream = new MemoryStream())
    {
        var newMemoryStream = new MemoryStream();
        fileStream.CopyTo(memoryStream);
        FormFileMock.Setup(f => f.CopyToAsync(newMemoryStream, CancellationToken.None)).Returns(Task.CompletedTask);
        // some other setups

        //Act
        var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { FormFileMock.Object });
        //Assert
        Assert.IsTrue(result.Any());
    }
}

The newMemoryStream variable is created because the function calls the CopyToAsync method with a new and empty memorystream (I'm not sure if this is necessary).

The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

Body:
I know this might be unpopular because using a mock framework is totally "in" these days, but why not simply leave the framework be framework and go the simple, easy way? You can create a FormFile without any mocking. Just the real deal:

var fileConverter = new FilesConverter(FilesConverterLoggerMock.Object, FileDataMock.Object);

// access to a real file should really not be in a "unit" test, but anyway:
using (var stream = new MemoryStream(File.ReadAllBytes("Files/uploadme.txt"))
{
  // create a REAL form file
  var formFile = new FormFile(stream , 0, stream.Length, "name", "filename");

  //Act
  var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { formFile });

  //Assert
  Assert.IsTrue(result.Any());
}


问:
How can i create an toggle button using react mozilla forms
I'm trying to make a form using react-jsonschema-form

I need to create a toggle button. To do this I use the following Schema and UiSchema :

```<code>const Schema = {
  customCheckboxComponent: {
      type: 'string',
      title: 'toggle button'
  } };

const UISchema = {
  customCheckboxComponent: {
    "ui:widget": (props) => {
        return (
            <label className="switch">
                <input type="checkbox"
                className="col-xs-12 custom"
                title={props.title}
                value={props.value}
                onChange={(event) => props.onChange(event.target.value)}/>
                <span className="slider round"/>
            </label>
        );
           };
</code>```

And I'm using the css provide w3Schools :

I failed to get the state of this toggle button. It's as if the state of my toggle button doesn't change !

Can some one please help me on this.

答:
I have solved my problem on changing :

```<code>onChange={(event) => props.onChange(event.target.value)}
</code>```

by

```<code>onClick={() => props.onChange(!props.value)}
</code>```

Body:
I'm trying to make a form using react-jsonschema-form

I need to create a toggle button. To do this I use the following Schema and UiSchema :

const Schema = {
  customCheckboxComponent: {
      type: 'string',
      title: 'toggle button'
  } };

const UISchema = {
  customCheckboxComponent: {
    "ui:widget": (props) => {
        return (

                <input type="checkbox"
                className="col-xs-12 custom"
                title={props.title}
                value={props.value}
                onChange={(event) => props.onChange(event.target.value)}/>

        );
           };

And I'm using the css provide w3Schools :

I failed to get the state of this toggle button. It's as if the state of my toggle button doesn't change !

Can some one please help me on this.

Body:
I have solved my problem on changing :

onChange={(event) => props.onChange(event.target.value)}

by

onClick={() => props.onChange(!props.value)}


问:
Extract Seq using Kafka Streams
I'm trying to read a Kafka topic, do some processing based on that, and store the results in another topic.

My code looks like below:

```<code>builder
   .stream(settings.Streams.inputTopic)
   .mapValues[Seq[Product]]((e: EventRecord) ⇒ fx(e))
   // Something needs to be done here...
   .to(settings.Streams.outputTopic)
</code>```

The fx(e) function does some processing and returns a Seq[Product]. I'd like to store all products as a separate entry in the topic. Problem is that the messages read from the topic contain multiple products, hence the return value for fx(e).

Is it possible to embed this behaviour in the stream?

答:
Use flatMapValues instead of mapValues:

```<code>import scala.collection.JavaConverters.asJavaIterableConverter

builder
  .stream(settings.Streams.inputTopic)
  .flatMapValues(e => fx(e).toIterable.asJava)
  .to(settings.Streams.outputTopic)
</code>```

Title: Extract Seq using Kafka Streams

Body:
I'm trying to read a Kafka topic, do some processing based on that, and store the results in another topic.

My code looks like below:

builder
   .stream(settings.Streams.inputTopic)
   .mapValues[Seq[Product]]((e: EventRecord) ⇒ fx(e))
   // Something needs to be done here...
   .to(settings.Streams.outputTopic)

The fx(e) function does some processing and returns a Seq[Product]. I'd like to store all products as a separate entry in the topic. Problem is that the messages read from the topic contain multiple products, hence the return value for fx(e).

Is it possible to embed this behaviour in the stream?

Body:
Use flatMapValues instead of mapValues:

import scala.collection.JavaConverters.asJavaIterableConverter

builder
  .stream(settings.Streams.inputTopic)
  .flatMapValues(e => fx(e).toIterable.asJava)
  .to(settings.Streams.outputTopic)


问:
Read from command line
I have a problem with reading dates. Task:

The goal is to write a program capable of constructing and printing a Huffman tree for a specific file. The program will receive the name of the file in the form of a single command-line argument, read all data from the input file and build the Huffman tree for this file...

Example:

```<code>$>program.exe simple.in
</code>```

My solution:

```<code>string FileName = Console.ReadLine();
fileBytes = File.ReadAllBytes(FileName);
</code>```

But this solution writes:

RE:Runtime error 102: Dereferencing null value

Thanks

答:
I solved it.
Instead of:

```<code>Console.ReadLine();
</code>```

I used:

```<code>args[0];
</code>```

Title: Read from command line

Body:
I have a problem with reading dates. Task:

The goal is to write a program capable of constructing and printing a Huffman tree for a specific file. The program will receive the name of the file in the form of a single command-line argument, read all data from the input file and build the Huffman tree for this file...

Example:

$>program.exe simple.in

My solution:

string FileName = Console.ReadLine();
fileBytes = File.ReadAllBytes(FileName);

But this solution writes:

RE:Runtime error 102: Dereferencing null value

Thanks

Body:
I solved it.
Instead of:

Console.ReadLine();

I used:

args[0];


问:
Liquibase unable to pass changeLogParameters
I am using liquibase-gradle-plugin and Groovy DSL to apply the changesets in my database. I have made necessary configurations in the gradle scripts as per the documentation of the plugin. There is also a relevant issue which has been marked as Closed and seems to be working for other users. However, the properties are not resolving in my SQL file. I am not sure what I am doing wrong. Any pointers are greatly appreciated.

Contents of build.gradle

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.liquibase:liquibase-gradle-plugin:1.2.4"
        classpath group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
    }
}

apply plugin: 'org.liquibase.gradle'
liquibase {
    activities {
        main {
            changeLogFile "${project.projectDir}/src/main/db/changelogs.groovy"
            changeLogParameters([
                    name    : 'foo',
                    category: 'bar'
            ])
            url "jdbc:mysql://localhost/test?nullNamePatternMatchesAll=true"
            username 'test'
            password 'test'
            driver 'com.mysql.jdbc.Driver'
        }
    }
}
</code>```

Contents of changelogs.groovy

```<code>databaseChangeLog(logicalFilePath: '/db/changelogs.groovy') {

    changeSet(id: '1', author: 'abc', runAlways: true) {

        comment 'Init.'
        sqlFile(path: 'scripts/init.sql', relativeToChangelogFile: true)

    }
}
</code>```

Contents of init.sql

```<code>USE TEST;

DROP TABLE IF EXISTS MY_TABLE;

CREATE TABLE MY_TABLE(
    NAME VARCHAR(100),
    CATEGORY VARCHAR(100)
);

INSERT INTO MY_TABLE VALUES ('${name}', '${category}');

COMMIT;
</code>```

SQL Output:

```<code>mysql-sql> select * from  my_table;
+---------+-------------+
| NAME    | CATEGORY    |
+---------+-------------+
| ${name} | ${category} |
+---------+-------------+
1 row in set (0.00 sec)
</code>```

Here I would have expected the table to contain 'foo' and 'bar' for name and category respectively.

The code is available on GitHub.

答:
My best guess is that you need to replace this line:

```<code>INSERT INTO MY_TABLE VALUES ('${name}', '${category}');
</code>```

with this:

```<code>INSERT INTO MY_TABLE VALUES ("${name}", "${category}");
</code>```

The difference is that the first line uses single quotes which translate to literal strings. The second line use double quotes, which allows for String interpolation (a.k.a. String templates).

Here is a quote from http://groovy-lang.org/style-guide.html

Also note the difference between single quotes and double quotes in
  Groovy: single quotes always create Java Strings, without
  interpolation of variables, whereas double quotes either create Java
  Strings or GStrings when interpolated variables are present.

Read more about single quoted, double quoted and triple quoted Strings here: http://docs.groovy-lang.org/latest/html/documentation/index.html#all-strings

Body:
I am using liquibase-gradle-plugin and Groovy DSL to apply the changesets in my database. I have made necessary configurations in the gradle scripts as per the documentation of the plugin. There is also a relevant issue which has been marked as Closed and seems to be working for other users. However, the properties are not resolving in my SQL file. I am not sure what I am doing wrong. Any pointers are greatly appreciated.

Contents of build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.liquibase:liquibase-gradle-plugin:1.2.4"
        classpath group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
    }
}

apply plugin: 'org.liquibase.gradle'
liquibase {
    activities {
        main {
            changeLogFile "${project.projectDir}/src/main/db/changelogs.groovy"
            changeLogParameters([
                    name    : 'foo',
                    category: 'bar'
            ])
            url "jdbc:mysql://localhost/test?nullNamePatternMatchesAll=true"
            username 'test'
            password 'test'
            driver 'com.mysql.jdbc.Driver'
        }
    }
}

Contents of changelogs.groovy

databaseChangeLog(logicalFilePath: '/db/changelogs.groovy') {

    changeSet(id: '1', author: 'abc', runAlways: true) {

        comment 'Init.'
        sqlFile(path: 'scripts/init.sql', relativeToChangelogFile: true)

    }
}

Contents of init.sql

USE TEST;

DROP TABLE IF EXISTS MY_TABLE;

CREATE TABLE MY_TABLE(
    NAME VARCHAR(100),
    CATEGORY VARCHAR(100)
);

INSERT INTO MY_TABLE VALUES ('${name}', '${category}');

COMMIT;

SQL Output:

mysql-sql> select * from  my_table;
+---------+-------------+
| NAME    | CATEGORY    |
+---------+-------------+
| ${name} | ${category} |
+---------+-------------+
1 row in set (0.00 sec)

Here I would have expected the table to contain 'foo' and 'bar' for name and category respectively.

The code is available on GitHub.

Body:
My best guess is that you need to replace this line:

INSERT INTO MY_TABLE VALUES ('${name}', '${category}');

with this:

INSERT INTO MY_TABLE VALUES ("${name}", "${category}");

The difference is that the first line uses single quotes which translate to literal strings. The second line use double quotes, which allows for String interpolation (a.k.a. String templates).

Here is a quote from http://groovy-lang.org/style-guide.html

Also note the difference between single quotes and double quotes in
  Groovy: single quotes always create Java Strings, without
  interpolation of variables, whereas double quotes either create Java
  Strings or GStrings when interpolated variables are present.

Read more about single quoted, double quoted and triple quoted Strings here: http://docs.groovy-lang.org/latest/html/documentation/index.html#all-strings


问:
XML to GrapML using stylesheet
I am trying to convert an XML file to a GraphMl format using a xsl stylesheet (see below), the from and to attributes in the link are to be used as the source and target attributes in the GraphMl file. My code runs but the output file is empty, how can I fix the stylesheet?

Sample XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE network SYSTEM "http://www.matsim.org/files/dtd/network_v2.dtd">
<network>

    <!-- ====================================================================== -->

        <nodes>
            <node id="MyCiTi_1" x="-53196.450154726146" y="-3755010.0058102254" >
            </node>
            <node id="MyCiTi_10" x="-54879.37761845079" y="-3753903.660850382" >
            </node>
            <node id="MyCiTi_100" x="-46659.23389528884" y="-3749500.821686937" >
            </node>
        </nodes>

    <!-- ====================================================================== -->

        <links capperiod="01:00:00" effectivecellsize="7.5" effectivelanewidth="3.75">
            <link id="MyCiTi_0" from="MyCiTi_180" to="MyCiTi_180" length="50.0" freespeed="8.333333333333334" capacity="500.0" >
            </link>
            <link id="MyCiTi_1" from="MyCiTi_180" to="MyCiTi_58" length="608.4643035761809" freespeed="8.333333333333334" capacity="500.0"  >
            </link>
            <link id="MyCiTi_10" from="MyCiTi_176" to="MyCiTi_192" length="868.3169964115151" freespeed="8.333333333333334" capacity="500.0" >
            </link>
        </links>

</network>
</code>```

xsl sheet

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <graphml xmlns="http://graphml.graphdrawing.org/xmlns"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
        <key id="nodes" for="node" attr.name="id" attr.type="string"/>
        <key id="edges" for="edge" attr.name="id" attr.type="string"/>
        <graph id="g" edgedefault="undirected">
                <xsl:for-each select="node">
                    <node>
                        <data key="node">
                            <xsl:value-of select="@x"/>
                            <xsl:value-of select="@y"/>
                        </data>
                    </node>
                </xsl:for-each>
                <xsl:for-each select="link">
                    <edge source="@from" target="@to">
                        <data key="link">
                            <xsl:value-of select="@length"/>
                        </data>
                    </edge>
                </xsl:for-each>
        </graph>
    </graphml>
</xsl:template>

</xsl:stylesheet>
</code>```

答:
The paths do not work properly. If you want to do this with for-each, you need to start at network.

To transfer information directly into other attributes you just need to put these in {}.

I think you should insert one space character between your coordinates.

The nodes should also have IDs, right?

Try this:

```<code><graph id="g" edgedefault="undirected">
<xsl:for-each select="network/nodes/node">
    <node id="{@id}">
        <data key="node">
            <xsl:value-of select="@x"/>
            <xsl:text> </xsl:text>
            <xsl:value-of select="@y"/>
        </data>
    </node>
    </xsl:for-each>
    <xsl:for-each select="network/links/link">
        <edge source="{@from}" target="{@to}">
            <data key="link">
               <xsl:value-of select="@length"/>
            </data>
        </edge>
    </xsl:for-each>
</graph>
</code>```

Title: XML to GrapML using stylesheet

Body:
I am trying to convert an XML file to a GraphMl format using a xsl stylesheet (see below), the from and to attributes in the link are to be used as the source and target attributes in the GraphMl file. My code runs but the output file is empty, how can I fix the stylesheet?

Sample XML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE network SYSTEM "http://www.matsim.org/files/dtd/network_v2.dtd">
<network>

        <nodes>
            <node id="MyCiTi_1" x="-53196.450154726146" y="-3755010.0058102254" >
            </node>
            <node id="MyCiTi_10" x="-54879.37761845079" y="-3753903.660850382" >
            </node>
            <node id="MyCiTi_100" x="-46659.23389528884" y="-3749500.821686937" >
            </node>
        </nodes>

        <links capperiod="01:00:00" effectivecellsize="7.5" effectivelanewidth="3.75">
            <link id="MyCiTi_0" from="MyCiTi_180" to="MyCiTi_180" length="50.0" freespeed="8.333333333333334" capacity="500.0" >
            </link>
            <link id="MyCiTi_1" from="MyCiTi_180" to="MyCiTi_58" length="608.4643035761809" freespeed="8.333333333333334" capacity="500.0"  >
            </link>
            <link id="MyCiTi_10" from="MyCiTi_176" to="MyCiTi_192" length="868.3169964115151" freespeed="8.333333333333334" capacity="500.0" >
            </link>
        </links>

</network>

xsl sheet

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <graphml xmlns="http://graphml.graphdrawing.org/xmlns"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
        <key id="nodes" for="node" attr.name="id" attr.type="string"/>
        <key id="edges" for="edge" attr.name="id" attr.type="string"/>
        <graph id="g" edgedefault="undirected">
                <xsl:for-each select="node">
                    <node>
                        <data key="node">
                            <xsl:value-of select="@x"/>
                            <xsl:value-of select="@y"/>
                        </data>
                    </node>
                </xsl:for-each>
                <xsl:for-each select="link">
                    <edge source="@from" target="@to">
                        <data key="link">
                            <xsl:value-of select="@length"/>
                        </data>
                    </edge>
                </xsl:for-each>
        </graph>
    </graphml>
</xsl:template>

</xsl:stylesheet>

Body:
The paths do not work properly. If you want to do this with for-each, you need to start at network.

To transfer information directly into other attributes you just need to put these in {}.

I think you should insert one space character between your coordinates.

The nodes should also have IDs, right?

Try this:

<graph id="g" edgedefault="undirected">
<xsl:for-each select="network/nodes/node">
    <node id="{@id}">
        <data key="node">
            <xsl:value-of select="@x"/>
            <xsl:text> </xsl:text>
            <xsl:value-of select="@y"/>
        </data>
    </node>
    </xsl:for-each>
    <xsl:for-each select="network/links/link">
        <edge source="{@from}" target="{@to}">
            <data key="link">
               <xsl:value-of select="@length"/>
            </data>
        </edge>
    </xsl:for-each>
</graph>


问:
How do you know a soap client is using https/ssl? Using php nusoap library
I'm using a PHP soap toolkit called nusoap (http://sourceforge.net/projects/nusoap), and I have a newbie question.

I am calling a WSDL service, which is running over ssl (e.g. https://server.com/service/method.asmx?WSDL).

Using nusoap, I traced out the request.  It looks like this:

```<code>POST /service/method.asmx HTTP/1.0
Host: server.com
User-Agent: NuSOAP/0.9.5 (1.123)
Content-Type: text/xml; charset=ISO-8859-1
SOAPAction: "http://software.com/service/Method"
Content-Length: 713
</code>```

I'm wondering, though, is this being done over SSL, or no?

答: SOAPAction: "http://software.com/service/Method" indicates it's probably not using SSL. You'd expect it to have https in that URI.  I certainly wouldn't trust it.

OwnerDisplayName: Alex

Body:
I'm using a PHP soap toolkit called nusoap (http://sourceforge.net/projects/nusoap), and I have a newbie question.

I am calling a WSDL service, which is running over ssl (e.g. https://server.com/service/method.asmx?WSDL).

Using nusoap, I traced out the request.  It looks like this:

POST /service/method.asmx HTTP/1.0
Host: server.com
User-Agent: NuSOAP/0.9.5 (1.123)
Content-Type: text/xml; charset=ISO-8859-1
SOAPAction: "http://software.com/service/Method"
Content-Length: 713

I'm wondering, though, is this being done over SSL, or no?

OwnerDisplayName: Matthew Read


问:
How can I set node and link text manually in separated input?
I have simple python flask app where I send JSON data to my HTML and with goJS I display my graph which looks like this:

I want to change my selected node text inside input and when I click on "update node text" button I want to update node text with text from my input. I managed to get node text with help of this diagram listener:

```<code>myDiagram.addDiagramListener("ObjectSingleClicked", function(e) {
  console.log("clicked!");
  var part = e.subject.part;
  //part.data is the node object
  if (!(part instanceof go.Link)) {
    console.log("its not link!");
    console.log(part.data);
    document.getElementById("nodeText").value = part.data.text;

  } else {
    console.log("its link!");
  }
});
</code>```

I am stuck with updating node text and don't know how to do it. Also I want to make same thing with link text. I searched and googled but no solutions nor examples for this case. Any help will be appreciated.

答:
First I should say that the most common way to allow users to edit text in diagrams is to set TextBlock.editable to true and to add a TwoWay Binding of TextBlock.text to some data property.  This allows users to edit the text in-place rather than in separate HTML fields.

But it is common to have editing of properties in HTML fields.  Assuming there is at least a one way Binding from some data property to the TextBlock.text property in your node, your textarea's blur (or change?) event handler just needs to call Model.setDataProperty within a transaction.  Read more about modifying models and transactions.

Finally if you have a bunch of properties that you want to allow the user to edit, and especially if the number of properties might vary, you might want to use the GoJS DataInspector.  It is demonstrated by the Org Chart Editor sample and the Data Inspector sample.

ContentLicense: CC BY-SA 4.0

Body:
I have simple python flask app where I send JSON data to my HTML and with goJS I display my graph which looks like this:

I want to change my selected node text inside input and when I click on "update node text" button I want to update node text with text from my input. I managed to get node text with help of this diagram listener:

myDiagram.addDiagramListener("ObjectSingleClicked", function(e) {
  console.log("clicked!");
  var part = e.subject.part;
  //part.data is the node object
  if (!(part instanceof go.Link)) {
    console.log("its not link!");
    console.log(part.data);
    document.getElementById("nodeText").value = part.data.text;

  } else {
    console.log("its link!");
  }
});

I am stuck with updating node text and don't know how to do it. Also I want to make same thing with link text. I searched and googled but no solutions nor examples for this case. Any help will be appreciated.


问:
Avoid creating onMessage function per WS client
Following ws's instructions to create a WebSocket server:

```<code>const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});
</code>```

An onMessage callback named incoming is created for every client, am I right?

Imagine having two million clients. This code would create two million functions. Is there a way to avoid this? Something like this would be wonderful:

```<code>const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('message', function incoming(ws, message) {
  // Access to ws object
  console.log('received: %s', message);
});
</code>```

答:
How about:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

function handleMessage(message) {
  console.log('received: %s', message);
}

wss.on('message', handleMessage);```

Body:
Following ws's instructions to create a WebSocket server:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

An onMessage callback named incoming is created for every client, am I right?

Imagine having two million clients. This code would create two million functions. Is there a way to avoid this? Something like this would be wonderful:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('message', function incoming(ws, message) {
  // Access to ws object
  console.log('received: %s', message);
});


问:
Microservice Architecture design
I have few doubts on Microservice architecture.

Lets say there are microservices A, B and C.
A maintains the context of a job apart from other things it does and B,C work to fulfill that job by doing respective tasks for that job.

Here I have questions.

1. DB design

I am talking about SQL here.
Usage of foreign keys simplifies lot of things.
But as I understand microservice architecture, every microservice maintaines its own data and data has to be queried from that service if required.

Does it mean no foreign keys referring to tables in another microservices?

2. Data Flow

As I see here are two ways.

All the queries are done using jobId maintained uniquely in all microservices for a job.

Client requests go directly to individual service for a task.  To get summary of the job, client queries individual microservices collects the data and passes to user.

Do everything through coordinating microservice. Client requests go to service A and in tern service A will gather info from all other microservices for that jobId and passed that to user.

Which of the above two has to be followed and why?

答:
You're correct thinking that microservices should ideally have their own data structure so they can be deployed independently. However there are several design patterns that help you, and that doesn't necessarily translates in "No FK". Please refer to:

Database per service

Sagas

API Composition

CQRS

The patterns listed above answer both your questions.

Title: Microservice Architecture design


问:
Piping text log to Blue Ocean?
I'm using Blue Ocean to do a Unity3D build through command lines (https://docs.unity3d.com/Manual/CommandLineArguments.html).

I currently have a stage in blue ocean which runs the build command in a 'Windows Batch Script' outputting the log to a text file on the computer.

is there a way to also output that same logging text to the blue ocean build output? Right now all I see is the batch command.

答:
You have to make Unity to log to the standard out, then the logs will be picked up by Jenkins. The docs you linked has a -batchmode switch that says Note that in batch mode, Unity sends a minimal version of its log output to the console. However, the Log Files still contain the full log information.

I believe running with that flag you will see some output in Jenkins. You can test it locally too. When you run the unity command, if you see output in your command line, chances are high that you will have it in Jenkins too.

Title: Piping text log to Blue Ocean?


问:
smsgateway.me store message status in php variable
Using smsgateway.me to send a message I use the default code with my own variables which are working fine. However, sometimes the SMS does not send and I would like to store the SMS in the database if failed.
To do so I think I need a value from the $result array, but I dont know how to start.  I tried many different codes without any result.

Can anywone please tell me how to get an if sent ok -> do something / else do something else based on the code and variables below?
Thanks a lot!

Documentation here

Here is the default code (with default variables) that sends a message:

```<code><?php
include "smsGateway.php";
$smsGateway = new SmsGateway('demo@smsgateway.me', 'password');

$deviceID = 1;
$number = '+44771232343';
$message = 'Hello World!';

$options = [
'send_at' => strtotime('+10 minutes'), // Send the message in 10 minutes
'expires_at' => strtotime('+1 hour') // Cancel the message in 1 hour if the message is not yet sent
];

//Please note options is no required and can be left out
$result = $smsGateway->sendMessageToNumber($number, $message, $deviceID, $options);
?>
</code>```

Success content:

```<code>{
"success": true,
"result": {
"success": [
{
"id": "308",
"device_id": "4",
"message": "hello world!",
"status": "pending",
"send_at": "1414624856",
"queued_at": "0",
"sent_at": "0",
"delivered_at": "0",
"expires_at": "1414634856",
"canceled_at": "0",
"failed_at": "0",
"received_at": "0",
"error": "None",
"created_at": "1414624856",
"contact": {
"id": "14",
"name": "Phyllis Turner",
"number": "+447791064713"
}
}
],
"fails": [
]
}
}
</code>```

error content:

```<code>{
"success": true,
"result": {
"success": [
],
"fails": [
"number": "+44771232343"
"message": "hello world!",
"device": 1
"errors": {
"device": ["The selected device is invalid"],
}
]
}
}
</code>```

答:
This did the trick if failed:

```<code>if (isset($result['response']['result']['fails'][0]['number']) === TRUE) {
     echo 'failed';
else{
     echo 'success';
}
</code>```

this works on success:

```<code>if(isset($result['response']['result']['success'][0]['id']) === TRUE){
    echo 'success';
}else{
    echo 'failed';
}
</code>```

Thanks Michael, your reply helped me to change it a bit and figure it out!

Body:
Using smsgateway.me to send a message I use the default code with my own variables which are working fine. However, sometimes the SMS does not send and I would like to store the SMS in the database if failed.
To do so I think I need a value from the $result array, but I dont know how to start.  I tried many different codes without any result.

Can anywone please tell me how to get an if sent ok -> do something / else do something else based on the code and variables below?
Thanks a lot!

Documentation here

Here is the default code (with default variables) that sends a message:

<?php
include "smsGateway.php";
$smsGateway = new SmsGateway('demo@smsgateway.me', 'password');

$deviceID = 1;
$number = '+44771232343';
$message = 'Hello World!';

$options = [
'send_at' => strtotime('+10 minutes'), // Send the message in 10 minutes
'expires_at' => strtotime('+1 hour') // Cancel the message in 1 hour if the message is not yet sent
];

//Please note options is no required and can be left out
$result = $smsGateway->sendMessageToNumber($number, $message, $deviceID, $options);
?>

Success content:

{
"success": true,
"result": {
"success": [
{
"id": "308",
"device_id": "4",
"message": "hello world!",
"status": "pending",
"send_at": "1414624856",
"queued_at": "0",
"sent_at": "0",
"delivered_at": "0",
"expires_at": "1414634856",
"canceled_at": "0",
"failed_at": "0",
"received_at": "0",
"error": "None",
"created_at": "1414624856",
"contact": {
"id": "14",
"name": "Phyllis Turner",
"number": "+447791064713"
}
}
],
"fails": [
]
}
}

error content:

{
"success": true,
"result": {
"success": [
],
"fails": [
"number": "+44771232343"
"message": "hello world!",
"device": 1
"errors": {
"device": ["The selected device is invalid"],
}
]
}
}

Body:
This did the trick if failed:

if (isset($result['response']['result']['fails'][0]['number']) === TRUE) {
     echo 'failed';
else{
     echo 'success';
}

this works on success:

if(isset($result['response']['result']['success'][0]['id']) === TRUE){
    echo 'success';
}else{
    echo 'failed';
}

Thanks Michael, your reply helped me to change it a bit and figure it out!


问:
Pull data from view into viewmodel before command is executed WPF
I have textbox. Its updatesourcetrigger property is set to lostfocus. I dont want to set it to proportychanged.

Now lets say, my WPF form is already dirty and user is updating the textbox. Now user directly press CTRL + S key(i.e. it invokes SAVE command) when focus is in textbox only.

Now updated textbox value is not reflected in viewmodel when save command is invoked.(i.e. my view and viewmodel data is not synchronized.)

Can I somehow pull data from view to viewmodel before command invokes or can I call textbox lostfocus event before invoking command.

Thanks in advance....

答:
I answer for similar question in https://stackoverflow.com/a/47309346/4554937. I write command which update binding source for focused keyboard element and execute it before save data.

Piece of my CommitValueCommand

```<code>public void Execute(object parameter)
{
    if (Keyboard.FocusedElement is TextBox textBox)
    {
        BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty).UpdateSource();
    }
}
</code>```

Body:
I answer for similar question in https://stackoverflow.com/a/47309346/4554937. I write command which update binding source for focused keyboard element and execute it before save data.

Piece of my CommitValueCommand

public void Execute(object parameter)
{
    if (Keyboard.FocusedElement is TextBox textBox)
    {
        BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty).UpdateSource();
    }
}


问:
Why does my code not process correctly it keeps returning the wrong line?
It is supposed to return a certain line if the Computer randomly picks a certain letter, but it chooses only one instance to repeat over and over again, even when the condition for the other sentence to be printed is met.

```<code>import random
Player_Score = 0
Computer_Score = 0
while Player_Score < 5 or Computer_Score < 5:
    Player_object = input("Would you like to choose R, P, or S?")
    Computer_object = str(random.sample(set(["R", "P", "S"]), 1))
    if Player_object == "R" or Player_object == "r":
        if str(Computer_object) == "R":
             print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
        elif str(Computer_object) == "P":
            Computer_Score = Computer_Score + 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.")
        else:
            Player_Score = Player_Score + 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer scored a point.")
</code>```

This code returns these results:

```<code>    Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?
</code>```

答:
str(random.sample(set(["R", "P", "S"]), 1)) returns "['S']", not 'S', so your code always enters the else condition.

Instead, try random.sample("RPS", 1)[0], which will return the first (and only) element of the list or use random.choice('RPS').

Body:
It is supposed to return a certain line if the Computer randomly picks a certain letter, but it chooses only one instance to repeat over and over again, even when the condition for the other sentence to be printed is met.

import random
Player_Score = 0
Computer_Score = 0
while Player_Score < 5 or Computer_Score < 5:
    Player_object = input("Would you like to choose R, P, or S?")
    Computer_object = str(random.sample(set(["R", "P", "S"]), 1))
    if Player_object == "R" or Player_object == "r":
        if str(Computer_object) == "R":
             print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
        elif str(Computer_object) == "P":
            Computer_Score = Computer_Score + 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.")
        else:
            Player_Score = Player_Score + 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer scored a point.")

This code returns these results:

    Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['S'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['R'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?R
You have chosen R and the Computer chose ['P'].You have beaten the Computer scored a point.
Would you like to choose R, P, or S?