问:
Error in function imshow
I'm trying to make a custom object detector (chairs) using the HOG+SVM method. My plan of action is to:

Loop through the images in my folder

Read and resize them

Convert them to vectors using the hog.compute() function

And then store them into a data file

If all goes well, my SVM classifier will handle the rest.

Then ideally, it will be able to identify the chairs that are displayed through my webcam.

Here's the code I'm trying to use (only the initial bit):

```<code>import cv2
import os
import numpy as np

def loadimg():

    for i in range(0,19):
        image = cv2.imread(str(i))
        cv2.imshow("img",image)
        (winW, winH) = (500, 500)
        r = 128.0 / image.shape[1]
        dim = (128, int(image.shape[0] * r))
        img = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
    return img

def hoggify(img):
    imeg = hog.compute(img)
    return imeg

for fn in os.listdir('/Users/munirmalik/cvprojek/cod'):
loadimg()
hoggify(imeg)
np.savetxt('data.txt')
</code>```

This is the error I'm getting:

```<code>cv2.error: /Users/munirmalik/opencv/modules/highgui/src/window.cpp:304: error: (-215) size.width>0 && size.height>0 in function imshow
</code>```

I've googled the error and it says that imread() isn't reading my image, which I'm assuming has to do with my for loop in the loadimg() function.

Can someone please help me out? Also if you can think of a better way to go about doing this, please do let me know :)

答:
This is the bug in your code

```<code>   for i in range(0,19):
        image = cv2.imread(str(i))
</code>```

This translates to cv2.imread("0"). The cv2.imread() functon needs to be passed an image address like "path/to/image.jpg". I'm not sure how your images are arranged in the file structure, but the argument to cv2.imread() should end in a file extension like JPG, PNG, etc

As per OP's comment, the code should be changed to:

```<code>   for i in range(0,19):
        image = cv2.imread(r"/Users/munirmalik/cvprojek/cod/chairs/" + str(i)+ ".jpg")
</code>```

Title: Error in function imshow

Body:
I'm trying to make a custom object detector (chairs) using the HOG+SVM method. My plan of action is to:

Loop through the images in my folder

Read and resize them

Convert them to vectors using the hog.compute() function

And then store them into a data file

If all goes well, my SVM classifier will handle the rest.

Then ideally, it will be able to identify the chairs that are displayed through my webcam.

Here's the code I'm trying to use (only the initial bit):

import cv2
import os
import numpy as np

def loadimg():

    for i in range(0,19):
        image = cv2.imread(str(i))
        cv2.imshow("img",image)
        (winW, winH) = (500, 500)
        r = 128.0 / image.shape[1]
        dim = (128, int(image.shape[0] * r))
        img = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
    return img

def hoggify(img):
    imeg = hog.compute(img)
    return imeg

for fn in os.listdir('/Users/munirmalik/cvprojek/cod'):
loadimg()
hoggify(imeg)
np.savetxt('data.txt')

This is the error I'm getting:

cv2.error: /Users/munirmalik/opencv/modules/highgui/src/window.cpp:304: error: (-215) size.width>0 && size.height>0 in function imshow

I've googled the error and it says that imread() isn't reading my image, which I'm assuming has to do with my for loop in the loadimg() function.

Can someone please help me out? Also if you can think of a better way to go about doing this, please do let me know :)

Body:
This is the bug in your code

   for i in range(0,19):
        image = cv2.imread(str(i))

This translates to cv2.imread("0"). The cv2.imread() functon needs to be passed an image address like "path/to/image.jpg". I'm not sure how your images are arranged in the file structure, but the argument to cv2.imread() should end in a file extension like JPG, PNG, etc

As per OP's comment, the code should be changed to:

   for i in range(0,19):
        image = cv2.imread(r"/Users/munirmalik/cvprojek/cod/chairs/" + str(i)+ ".jpg")


来源: stackexchange

问:
jquery selector doesn't give all elements
In the next web page I want to select all
 elements with Jquery.
I want to select all the products that are inside

https://www.walmart.com/browse/home-improvement/air-quality/1072864_133032_1231459

I have tried:

```<code>$(".search-product-result ul li")
$("ul.search-result-gridview-items li")
</code>```

Also I have tried:

```<code>$("li")
$("ul li")
$("section li")
</code>```

to select all
 and none works.
All of them give one
 and not all.

Why this happens?

答:
Doing
$('.search-result-gridview-items').children seems to work for me

ContentLicense: CC BY-SA 3.0

Body:
In the next web page I want to select all
 elements with Jquery.
I want to select all the products that are inside

https://www.walmart.com/browse/home-improvement/air-quality/1072864_133032_1231459

I have tried:

$(".search-product-result ul li")
$("ul.search-result-gridview-items li")

Also I have tried:

$("li")
$("ul li")
$("section li")

to select all
 and none works.
All of them give one
 and not all.

Why this happens?


问:
OSGi bundle restart with cxf-extension-osgi
I have a simple CXF RS bundle deployed in Fuse 4.2 that works fine upon initial installation. But, when I update or re-install the bundle, the REST service in no longer accessible.

I tried a various configurations and found that using cxf-extension-osgi was the issue...

from this...

```<code><import resource="classpath:META-INF/cxf/osgi/cxf-extension-osgi.xml"/>
</code>```

to this...

```<code><import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml"/>
</code>```

Also, I updated the address to be non-relative...ending up with this configuration (that works after bundle restarts, etc)

```<code><import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml" />

<jaxrs:server id="testService" address="http://localhost:9000/">
    <jaxrs:serviceBeans>
        <ref bean="testBean" />
    </jaxrs:serviceBeans>
</jaxrs:server>
</code>```

Any idea what is causing this issue when using cxf-extension-osgi? Also, what is the trade-off when using cxf-extendsion-http-jetty instead (functional, performance, etc)?

thanks

答:
Sorry, it seems to be error in cxf/servicemix integration. The problem is, cxf tries to register service under the address that is already used (by older version of this service).

Both REST and SOAP services are unaccessible after bundle restart/update. Restart of whole servicemix. Hovewer, when business logic is in other bundle, and the bundle with SOAP/REST service contains only interface, restart is needed only when interface has changed.

We were fighting with this error long, but unfortunatelly without effort.

ContentLicense: CC BY-SA 2.5

Body:
I have a simple CXF RS bundle deployed in Fuse 4.2 that works fine upon initial installation. But, when I update or re-install the bundle, the REST service in no longer accessible.

I tried a various configurations and found that using cxf-extension-osgi was the issue...

from this...

<import resource="classpath:META-INF/cxf/osgi/cxf-extension-osgi.xml"/>

to this...

<import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml"/>

Also, I updated the address to be non-relative...ending up with this configuration (that works after bundle restarts, etc)

<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml" />

<jaxrs:server id="testService" address="http://localhost:9000/">
    <jaxrs:serviceBeans>
        <ref bean="testBean" />
    </jaxrs:serviceBeans>
</jaxrs:server>

Any idea what is causing this issue when using cxf-extension-osgi? Also, what is the trade-off when using cxf-extendsion-http-jetty instead (functional, performance, etc)?

thanks


问:
Link inside clickable div
I have a link inside a clickable div like this:

HTML:

```<code><div onClick="goToCat(2);" class="author-topics-block ">
    <a href="http://mywebsite/page/?cat=2">The woman in steel</a>
</div>
</code>```

CSS:

```<code>.author-topics-block {
    cursor: pointer;
    text-align: center;
    line-height:26px;
    padding: 0 10px 0 10px;
    font-size: 15px;
    font-family: Oswald;
    border-bottom: 4px solid transparent;
}
</code>```

JS:

```<code>function goToCat(catId) {
  window.location.href = "http://mywebsite/page/?cat=" + catId;
}
</code>```

How do I prevent a click from triggering both on the div and on the link?

I want to keep the tag of the link href for search engines and the referencing.

答:
Is there more content going into the div besides the anchor tag, or could you do something like this and avoid the click event altogether?

.author-topics-block {
    cursor: pointer;
    text-align: center;
    line-height:26px;
    padding: 0 10px 0 10px;
    font-size: 15px;
    font-family: Oswald;
    border-bottom: 4px solid transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <div class="author-topics-block ">
      The woman in steel
  </div>
</code>```

Title: Link inside clickable div

Body:
I have a link inside a clickable div like this:

HTML:

    The woman in steel

CSS:

.author-topics-block {
    cursor: pointer;
    text-align: center;
    line-height:26px;
    padding: 0 10px 0 10px;
    font-size: 15px;
    font-family: Oswald;
    border-bottom: 4px solid transparent;
}

JS:

function goToCat(catId) {
  window.location.href = "http://mywebsite/page/?cat=" + catId;
}

How do I prevent a click from triggering both on the div and on the link?

I want to keep the tag of the link <a href for search engines and the referencing.

Body:
Is there more content going into the div besides the anchor tag, or could you do something like this and avoid the click event altogether?

.author-topics-block {
    cursor: pointer;
    text-align: center;
    line-height:26px;
    padding: 0 10px 0 10px;
    font-size: 15px;
    font-family: Oswald;
    border-bottom: 4px solid transparent;
}

<a href="http://mywebsite/page/?cat=2">
  <div class="author-topics-block ">
      The woman in steel
  </div>
</a>


问:
Minikube Kubernetes kubectl MacOS Error
I just followed the instructions to install Minikube on my Mac using brew:

```<code>https://github.com/kubernetes/minikube

brew cask install minikube
</code>```

And then I just followed the instructions to test it:

```<code>minikube start
</code>```

Gave me the following:

```<code>MacBook-Pro:~ joe$ minikube start
Starting local Kubernetes v1.6.4 cluster...
Starting VM...
Moving files into cluster...
Setting up certs...
Starting cluster components...
Connecting to cluster...
Setting up kubeconfig...
Kubectl is now configured to use the cluster
</code>```

I then tried to ask for the kubectl version as:

```<code>MacBook-Pro:~ joe$ kubectl version
Client Version: version.Info{Major:"1", Minor:"4", GitVersion:"v1.4.5", GitCommit:"5a0a696437ad35c133c0c8493f7e9d22b0f9b81b", GitTreeState:"clean", BuildDate:"2016-10-29T01:38:40Z", GoVersion:"go1.7.1", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"dirty", BuildDate:"2017-06-22T04:31:09Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
</code>```

And I then tried the usual hello world example as below, which resulted in the error (also shown below):

```<code>MacBook-Pro:~ joe$ kubectl run hello-minikube --image=gcr.io/google_containers/echoserver:1.4 --port=8080
error: group map[extensions:0xc4204c6000 policy:0xc4204c6070 rbac.authorization.k8s.io:0xc4200ea070 storage.k8s.io:0xc4200ea150 federation:0xc4203ba0e0 apps:0xc4203ba620 authentication.k8s.io:0xc4203ba690 batch:0xc4203baa10 certificates.k8s.io:0xc4203baa80 componentconfig:0xc4203baaf0 :0xc4203ba5b0 authorization.k8s.io:0xc4203ba7e0 autoscaling:0xc4203ba850] is already registered
</code>```

I could not find any suitable answers. I guess my kubectl client should be updated. But how do I do this on my Mac? I guess it was all installed using brew. So any ideas how I could get this fixed?

EDIT: Tried what the post from Sebastien Goasguen

Hers is what I get:

```<code>MacBook-Pro:~ joe$ brew upgrade kubectl
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (caskroom/cask, homebrew/core).
==> Updated Formulae
bacula-fd           etcd                fio                 gx-go               kibana              metricbeat          packetbeat          subversion          webpack
certbot             exa                 gnumeric            heroku              libuv               mikutter            paket               tippecanoe          you-get
dos2unix            exploitdb           goffice             hugo                llnode              neovim              pyenv               vagrant-completion
elasticsearch       filebeat            gx                  irssi               logstash            numpy               remarshal           vim

Error: kubectl 1.7.0 already installed
MacBook-Pro:~ joe$ kubectl config use-context minikube
switched to context "minikube".
MacBook-Pro:~ joe$ kubectl run hello-minikube --image=gcr.io/google_containers/echoserver:1.4 --port=8080
Unable to connect to the server: dial tcp 192.168.99.101:8443: i/o timeout
MacBook-Pro:~ joe$ minikube delete
Deleting local Kubernetes cluster...
Machine deleted.
MacBook-Pro:~ joe$
</code>```

答:
So first update kubectl. If you installed it with brew:

brew upgrade kubectl

Otherwise, check the kubectl installation docs here: https://kubernetes.io/docs/tasks/tools/install-kubectl/

Then make sure you are targeting your minikube:

kubectl config use-context minikube

If that still fails, stop and delete minikube and re-install by downloading the release from the GitHub release page:

https://github.com/kubernetes/minikube/releases

Title: Minikube Kubernetes kubectl MacOS Error

Body:
I just followed the instructions to install Minikube on my Mac using brew:

https://github.com/kubernetes/minikube

brew cask install minikube

And then I just followed the instructions to test it:

minikube start

Gave me the following:

MacBook-Pro:~ joe$ minikube start
Starting local Kubernetes v1.6.4 cluster...
Starting VM...
Moving files into cluster...
Setting up certs...
Starting cluster components...
Connecting to cluster...
Setting up kubeconfig...
Kubectl is now configured to use the cluster

I then tried to ask for the kubectl version as:

MacBook-Pro:~ joe$ kubectl version
Client Version: version.Info{Major:"1", Minor:"4", GitVersion:"v1.4.5", GitCommit:"5a0a696437ad35c133c0c8493f7e9d22b0f9b81b", GitTreeState:"clean", BuildDate:"2016-10-29T01:38:40Z", GoVersion:"go1.7.1", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"dirty", BuildDate:"2017-06-22T04:31:09Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}

And I then tried the usual hello world example as below, which resulted in the error (also shown below):

MacBook-Pro:~ joe$ kubectl run hello-minikube --image=gcr.io/google_containers/echoserver:1.4 --port=8080
error: group map[extensions:0xc4204c6000 policy:0xc4204c6070 rbac.authorization.k8s.io:0xc4200ea070 storage.k8s.io:0xc4200ea150 federation:0xc4203ba0e0 apps:0xc4203ba620 authentication.k8s.io:0xc4203ba690 batch:0xc4203baa10 certificates.k8s.io:0xc4203baa80 componentconfig:0xc4203baaf0 :0xc4203ba5b0 authorization.k8s.io:0xc4203ba7e0 autoscaling:0xc4203ba850] is already registered

I could not find any suitable answers. I guess my kubectl client should be updated. But how do I do this on my Mac? I guess it was all installed using brew. So any ideas how I could get this fixed?

EDIT: Tried what the post from Sebastien Goasguen

Hers is what I get:

MacBook-Pro:~ joe$ brew upgrade kubectl
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (caskroom/cask, homebrew/core).
==> Updated Formulae
bacula-fd           etcd                fio                 gx-go               kibana              metricbeat          packetbeat          subversion          webpack
certbot             exa                 gnumeric            heroku              libuv               mikutter            paket               tippecanoe          you-get
dos2unix            exploitdb           goffice             hugo                llnode              neovim              pyenv               vagrant-completion
elasticsearch       filebeat            gx                  irssi               logstash            numpy               remarshal           vim

Error: kubectl 1.7.0 already installed
MacBook-Pro:~ joe$ kubectl config use-context minikube
switched to context "minikube".
MacBook-Pro:~ joe$ kubectl run hello-minikube --image=gcr.io/google_containers/echoserver:1.4 --port=8080
Unable to connect to the server: dial tcp 192.168.99.101:8443: i/o timeout
MacBook-Pro:~ joe$ minikube delete
Deleting local Kubernetes cluster...
Machine deleted.
MacBook-Pro:~ joe$


问:
Changing the Value of an Attribute using javascript
Getting my script down to the bare bones, I have followed the example of the w3schools.com ( https://www.w3schools.com/js/js_htmldom_html.asp ) for: document.getElementById(id).attribute = new value. Their example:

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

    <img id="myImage" src="smiley.gif">

<script>
    document.getElementById("myImage").src = "landscape.jpg";
</script>

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

Here is mine. I get no error messages on the Chrome console.

```<code><body>

    <img id = "indexPhoto" src =
        "newthaiimages/indexPhotos/indexPhoto_320.jpg"
         width="320" height="474" alt="hero sepia toned photo of Thai
         temple next to a river"/>

<script>

    document.getElementById("indexPhoto").scr =
        "newthaiimages/indexPhotos/indexPhoto_450.jpg";

</script>

</body>
</code>```

You can see the result at http://newthaimassage.com/index3.php . Here is the script not stripped down.

```<code><script>

    window.onload = function() {

       var w = window

   var x = w.innerWidth

switch(w.innerWidth){

    case x <= 320:

    break;

    case x <= 768:

        document.getElementById("indexPhoto").scr ="indexPhoto_450.jpg";

    break;

    case x <= 1024:

        document.getElementById("indexPhoto").scr ="indexPhoto_835.jpg";

    break;

    case x <= 1420:

        document.getElementById("indexPhoto").scr ="indexPhoto_1000.jpg";

    break;

    default:

        document.getElementById("indexPhoto").scr ="indexPhoto_1200.jpg";

}}

</script>
</code>```

Currently I am using CSS media queries to show images by window size, but using background images I can not use CSS animation, which is my ultimate goal here. Any help on this would be greatly appreciated.

答:
In JavaScript:</p>

```<code>var ele=document.getElementById("indexPhoto");
ele.setAttribute('src',"landscape.jpg");
</code>```

Body:
Getting my script down to the bare bones, I have followed the example of the w3schools.com ( https://www.w3schools.com/js/js_htmldom_html.asp ) for: document.getElementById(id).attribute = new value. Their example:

<!DOCTYPE html>

Here is mine. I get no error messages on the Chrome console.

You can see the result at http://newthaimassage.com/index3.php . Here is the script not stripped down.

Currently I am using CSS media queries to show images by window size, but using background images I can not use CSS animation, which is my ultimate goal here. Any help on this would be greatly appreciated.

Body:
In JavaScript:

var ele=document.getElementById("indexPhoto");
ele.setAttribute('src',"landscape.jpg");


答:
May not be best answer but if I were to do a similar task I would simply comment out the href inside the div, crawlers should still read it like its a link but it wouldn't be clickable technically.

It also seems that you may be over complicating it from my point of view. Why not just specify each link for the div instead of having a script make it? It would simplify the code and remove your problem.

Title: Link inside clickable div


问:
Can VIM autoindent SQL?
"SQL Statement indentation good practice" appears to be the accepted format for writing SQL blocks.

Is there a Vim indent/syntax file that would adhere to this standard, or at least be close?

Currently my Vim left alights pretty much everything and only indents certain keywords.

答:
You can use the vim-autoformat plugin:

Install vim-autoformat with your favourite plugin-manager (I prefer lightweight vim-plug)

Install sqlparse with pip

Add the following lines to your vim/nvim config

```<code>noremap <F3> :Autoformat<CR>
let g:formatdef_sql = '"sqlformat --reindent --keywords upper - identifiers lower -"'
let g:formatters_sql = ['sql']
</code>```

If you see this message: vim has no support for python, you should rebuild your vim with python support or install python-client for neovim

Title: Can VIM autoindent SQL?

Body:
You can use the vim-autoformat plugin:

Install vim-autoformat with your favourite plugin-manager (I prefer lightweight vim-plug)

Install sqlparse with pip

Add the following lines to your vim/nvim config

noremap <F3> :Autoformat<CR>
let g:formatdef_sql = '"sqlformat --reindent --keywords upper - identifiers lower -"'
let g:formatters_sql = ['sql']

If you see this message: vim has no support for python, you should rebuild your vim with python support or install python-client for neovim


问:
Difference between res.setHeader and res.header in node.js
What is the difference between res.setHeader and res.header. Which one should be used for enabling CORS? In some pages res.header is used and some pages res.setHeader is used for CORS.</p>

答:
Perhaps an example can clarify more:</p>
```<code>// only a single field is set
res.setHeader('content-type', 'application/json');

// multiple fields can be set at once
res.set({
     'content-type': 'application/json',
     'content-length': '100',
     'warning': "with content type charset encoding will be added by default"
});

</code>```

Body:
Perhaps an example can clarify more:

// only a single field is set
res.setHeader('content-type', 'application/json');

// multiple fields can be set at once
res.set({
     'content-type': 'application/json',
     'content-length': '100',
     'warning': "with content type charset encoding will be added by default"
});

ContentLicense: CC BY-SA 4.0


问:
Read .mat files from Unix shell
Is there a way to read .mat files from the UNIX command line shell?

Such as cat mymat.mat ?

I am aware of the possibilities to load it in MATLAB or python, but these are not available for me atm.

答:
GNU Octave may be an option as it can be freely installed without cost.

Say you ran a session something like this and created two arrays, A and B:

```<code>octave:1> A = [ 1:3; 4:6; 7:9 ];
octave:2> B = [ 11:13; 14:16; 17:19 ];
octave:3> save -7 myfile.mat A B
</code>```

Then, in the shell, outside of Octave, you could do this to see the names of the variables in the file:

```<code>$ octave-cli <<< "who -file myfile.mat"
</code>```

Sample Output

```<code>Variables in the file myfile.mat:

A  B
</code>```

And then this to dump the variables:

```<code> $ octave-cli <<< "load myfile.mat;A"
</code>```

Sample Output

```<code>A =

   1   2   3
   4   5   6
   7   8   9
</code>```

And:

```<code>$ octave-cli <<< "load myfile.mat;B"
</code>```

Sample Output

```<code>B =

   11   12   13
   14   15   16
   17   18   19
</code>```

Title: Read .mat files from Unix shell

Body:
GNU Octave may be an option as it can be freely installed without cost.

Say you ran a session something like this and created two arrays, A and B:

octave:1> A = [ 1:3; 4:6; 7:9 ];
octave:2> B = [ 11:13; 14:16; 17:19 ];
octave:3> save -7 myfile.mat A B

Then, in the shell, outside of Octave, you could do this to see the names of the variables in the file:

$ octave-cli <<< "who -file myfile.mat"

Sample Output

Variables in the file myfile.mat:

A  B

And then this to dump the variables:

 $ octave-cli <<< "load myfile.mat;A"

Sample Output

A =

   1   2   3
   4   5   6
   7   8   9

And:

$ octave-cli <<< "load myfile.mat;B"

Sample Output

B =

   11   12   13
   14   15   16
   17   18   19


问:
Create a asmx web service in C# using visual studio 2013
Hy,

how can I create a asmx web service in Visual Studio 2013?

I have found this short tutorial about that, but when I follow this in Visual Studio 2013 I get an error that says "the type 'Service1' could not be created".

Thanks for help :)

答: Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.</p>


问:
How to write this kind of documentation easily?
I love pure ascii text documentation, like this one:
http://www.catonmat.net/download/sed.stream.editor.cheat.sheet.txt

But I don't know how to write it easily. There are lots of tables in it. Anyone can explain it please?

Thanks.

答:
Take a look at https://www.multieditsoftware.com/ME2008.php
As far as I remember there're such feature.</p>


问:
JUnit @BeforeClass annotation compiles fine in IDE but fails Maven build
When I write a simple method as follows:

```<code> @BeforeClass
 public void setUp(){}
</code>```

it compiles properly both in IntellijIDEA and Eclipse (using built in IDE Build).
However the same fragment of code fails a Maven run:

```<code>Tests in error:
  initializationError(TestClass): Method setUp() should be static
</code>```

Should have not this error been caught during compilation?

答:
This is no different than a test failure, which is only ever detected at runtime.  Because you have a malformed method attached to your @BeforeClass annotation, JUnit is informing you that the tests cannot run due to that, thus failing the build.

Compilation has nothing to do with this.  You're going to want to, well, fix your tests to ensure that they comply with what JUnit is asking for.

Body:
When I write a simple method as follows:

 @BeforeClass
 public void setUp(){}

it compiles properly both in IntellijIDEA and Eclipse (using built in IDE Build).
However the same fragment of code fails a Maven run:

Tests in error:
  initializationError(TestClass): Method setUp() should be static

Should have not this error been caught during compilation?


问:
Change JFrame in WindowBuilder Eclipse
I'm working with swing and I'm not able to change the JFrame in COMPONENTS area in WindowBuilder.
I can only see the main frame.
When I press a button I create a new Frame but I cant edit it with WindowBuilder.

```<code>        frameMain.setVisible(false);
        frameLogin = new JFrame("Login Admin");
        frameLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameLogin.setSize(600, 400);
        frameLogin.setLocationRelativeTo(null);
        frameLogin.setVisible(true);
</code>```

I WANT TO EDIT frameLogin in WindowBuilder, any solution?
By creating a new JFrame in WindowBuilder it creates another class in other file.

答:
I did this :
In my view (frameMain) I declared this :

```<code>private loginFrameAdmin frameLoginA;
private loginFrameUser frameLoginU;
</code>```

where loginFrameAdmin is a JFrame like this :

```<code>import javax.swing.JFrame;

public class loginFrameAdmin {

    private JFrame frameLogin;
    public loginFrameAdmin() {
        frameLogin = new JFrame("Login Amministratore");
        frameLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameLogin.setSize(600, 400);
        frameLogin.setLocationRelativeTo(null);
        frameLogin.setVisible(true);
    }
}
</code>```

Then in the same view (frameMain) I added a class :

```<code>public void adminPage() {
        JOptionPane.showMessageDialog(null, "Login for admins");
        frameMain.setVisible(false);
        frameLoginA = new loginFrameAdmin();
    }
</code>```

And now I'm able to edit my JFrame, thanks to @kalsowerus

Title: Change JFrame in WindowBuilder Eclipse

Body:
I'm working with swing and I'm not able to change the JFrame in COMPONENTS area in WindowBuilder.
I can only see the main frame.
When I press a button I create a new Frame but I cant edit it with WindowBuilder.

        frameMain.setVisible(false);
        frameLogin = new JFrame("Login Admin");
        frameLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameLogin.setSize(600, 400);
        frameLogin.setLocationRelativeTo(null);
        frameLogin.setVisible(true);

I WANT TO EDIT frameLogin in WindowBuilder, any solution?
By creating a new JFrame in WindowBuilder it creates another class in other file.

Body:
I did this :
In my view (frameMain) I declared this :

private loginFrameAdmin frameLoginA;
private loginFrameUser frameLoginU;

where loginFrameAdmin is a JFrame like this :

import javax.swing.JFrame;

public class loginFrameAdmin {

    private JFrame frameLogin;
    public loginFrameAdmin() {
        frameLogin = new JFrame("Login Amministratore");
        frameLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameLogin.setSize(600, 400);
        frameLogin.setLocationRelativeTo(null);
        frameLogin.setVisible(true);
    }
}

Then in the same view (frameMain) I added a class :

public void adminPage() {
        JOptionPane.showMessageDialog(null, "Login for admins");
        frameMain.setVisible(false);
        frameLoginA = new loginFrameAdmin();
    }

And now I'm able to edit my JFrame, thanks to @kalsowerus


问:
Knockoutjs Button Click
Hi how can ı get my value with knockoutjs click event my button code

```<code> <button data-bind="click : LikeButtonClick , value : MessageId" class="btn btn-default like"><span data-bind="text:LikeCount"></span> <i class="fa fa-thumbs-o-up"></i></button>
</code>```

and my knockoutjs click code

```<code> var LikeButtonClick = function () {
    alert("");
 }
</code>```

And how can I refresh my likes after like button click event. I use template binding. My template binding code is

```<code>  var viewModel = {
            messages: ko.observableArray()
        };
        ko.options.useOnlyNativeEvents = true;
        ko.applyBindings(viewModel);
        $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
            viewModel.messages(data);
        });
</code>```

and my like button code

```<code>var LikeButtonClick = function (id) {
            $.ajax({
                url: '/Home/Like/' + id,
                type: 'POST',
                success: function (data) {
                        // refresh
                        });
                }
            });
        }
</code>```

答:
Another method is to build the click function into your data model. Here I've added the function to the item directly. Each click will only affect it's own object information.

function Post() {
  var self = this;
  self.Text = ko.observable("Lorem Ipsum");
  self.Liked = ko.observable(false);
  self.LikeCount = ko.computed(function() {
    return self.Liked() ? 1 : 0;
  });
  self.MessageId = ko.observable(1);

  self.LikeButtonClick = function() {
    self.Liked(!self.Liked());
  }

}

function viewModel() {
  var self = this;

  self.Posts = ko.observableArray();

  self.Load = function() {
    self.Posts.push(new Post());
    self.Posts.push(new Post());
    self.Posts.push(new Post());
  }
  self.Load();
}

ko.applyBindings(new viewModel());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div data-bind="foreach: Posts">

  <div data-bind="text:Text"></div>
  <button data-bind="click: LikeButtonClick, value: MessageId" class="btn btn-default like">
<span data-bind="text:LikeCount"></span>
<i class="fa fa-thumbs-o-up"></i></button>
</div></code>```

Title: Knockoutjs Button Click

Body:
Hi how can ı get my value with knockoutjs click event my button code

 <button data-bind="click : LikeButtonClick , value : MessageId" class="btn btn-default like"> </button>

and my knockoutjs click code

 var LikeButtonClick = function () {
    alert("");
 }

And how can I refresh my likes after like button click event. I use template binding. My template binding code is

  var viewModel = {
            messages: ko.observableArray()
        };
        ko.options.useOnlyNativeEvents = true;
        ko.applyBindings(viewModel);
        $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
            viewModel.messages(data);
        });

and my like button code

var LikeButtonClick = function (id) {
            $.ajax({
                url: '/Home/Like/' + id,
                type: 'POST',
                success: function (data) {
                        // refresh
                        });
                }
            });
        }

Body:
Another method is to build the click function into your data model. Here I've added the function to the item directly. Each click will only affect it's own object information.

function Post() {
  var self = this;
  self.Text = ko.observable("Lorem Ipsum");
  self.Liked = ko.observable(false);
  self.LikeCount = ko.computed(function() {
    return self.Liked() ? 1 : 0;
  });
  self.MessageId = ko.observable(1);

  self.LikeButtonClick = function() {
    self.Liked(!self.Liked());
  }

}

function viewModel() {
  var self = this;

  self.Posts = ko.observableArray();

  self.Load = function() {
    self.Posts.push(new Post());
    self.Posts.push(new Post());
    self.Posts.push(new Post());
  }
  self.Load();
}

ko.applyBindings(new viewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div data-bind="foreach: Posts">

  <div data-bind="text:Text"></div>
  <button data-bind="click: LikeButtonClick, value: MessageId" class="btn btn-default like">
<span data-bind="text:LikeCount"></span>
<i class="fa fa-thumbs-o-up"></i></button>
</div>


问:
SonarQube MsBuild scanner on linux build agent
We build or dotnet core 1.1 projects on our own linux build agents in docker. (https://github.com/Microsoft/vsts-agent-docker) We would like to use Sonar to analyze our C# code. But it seems that the SonarQube MsBuild Scanner can't run in linux environment. Does anybody know a workaround for this. We don't really want to use Windows agents just to do the code analyzing.

Is it possible to run the scanner with mono? If so, is it supported by the sonar steps in tfs 2017? (https://dev.nexogen.hu/tfs/_gallery/items?itemName=sonarsource.sonarqube&targetId=cf345037-b065-4a16-9091-c30d56bf0798)

Can we expect the dotnet core port of the SonarQube MsBuild Scanner in the near future?

答: At this moment we do not support analysis on other operating systems than Windows and there is no workaround. This is planned for the near future, but we have not started working on it, yet: MMF-484.</p>


问:
Tfidf Vectorizer not working
I have a corpus(Hotel Reviews) and I want to do some NLP process including Tfidf. My problem is when I Applied Tfidf and print 100 features it doesn't appear as a single word but the entire sentence.
Here is my code:

Note: clean_doc is a function return my corpus cleaning from stopwords, stemming, and etc

```<code>vectorizer = TfidfVectorizer(analyzer='word',tokenizer=clean_doc,
max_features=100, lowercase = False, ngram_range=(1,3), min_df = 1)
vz  = vectorizer.fit_transform(list(data['Review']))
feature_names = vectorizer.get_feature_names()
for feature in feature_names:
  print(feature)
</code>```

it returns something like this:

```<code>love view  good room
food amazing recommended
bad services location far
-----
</code>```

any idea why? Thanks in Advance

答: There is most likely an error in your clean_doc function. The 'tokenizer' argument should be a function that takes a string as input and returns a list of tokens.

Title: Tfidf Vectorizer not working

Body:
I have a corpus(Hotel Reviews) and I want to do some NLP process including Tfidf. My problem is when I Applied Tfidf and print 100 features it doesn't appear as a single word but the entire sentence.
Here is my code:

Note: clean_doc is a function return my corpus cleaning from stopwords, stemming, and etc

vectorizer = TfidfVectorizer(analyzer='word',tokenizer=clean_doc,
max_features=100, lowercase = False, ngram_range=(1,3), min_df = 1)
vz  = vectorizer.fit_transform(list(data['Review']))
feature_names = vectorizer.get_feature_names()
for feature in feature_names:
  print(feature)

it returns something like this:

love view  good room
food amazing recommended
bad services location far
-----

any idea why? Thanks in Advance


问:
Activiti BPM Platform - Select a specific schema for creating tables?
I've just started working with activity and integrated it in my project (postgres based) in an embedded way (sample spring configuration file snip)

```<code>    (...)
    <!-- Activiti components -->
    <bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
        <property name="dataSource" ref="dataSource" />
        <property name="transactionManager" ref="transactionManager" />
        <property name="databaseSchemaUpdate" value="true" />
        <property name="jobExecutorActivate" value="false" />
    </bean>

    <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
        <property name="processEngineConfiguration" ref="processEngineConfiguration" />
    </bean>

    <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService" />
    <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService" />
    <bean id="taskService" factory-bean="processEngine" factory-method="getTaskService" />
    <bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService" />
    <bean id="managementService" factory-bean="processEngine" factory-method="getManagementService" />

    (...)
</code>```

It works well and create a lot of tables on my application schema at startup.

My problem is : tables are created in the 'public' schema in my postgres database. I would have preferred to put those tables in a separate schema, say 'activity'.

Fact is that after browsing the documentation / the net for almost two hours, I didn't found any way to change the default schema target creation behavior.

Any help... greatly appreciated ! ;)

答:
Since Postgres 9.4 JDBC driver you can specify the default schema in the JDBC url like this:
jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema

With this URL, all Activiti tables are created in the myschema schema instead of the default one in the search path, usually public.

Sources: this response on Stack Overflow and the latest documentation.

Body:
I've just started working with activity and integrated it in my project (postgres based) in an embedded way (sample spring configuration file snip)

    (...)

    <bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
        <property name="dataSource" ref="dataSource" />
        <property name="transactionManager" ref="transactionManager" />
        <property name="databaseSchemaUpdate" value="true" />
        <property name="jobExecutorActivate" value="false" />
    </bean>

    <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
        <property name="processEngineConfiguration" ref="processEngineConfiguration" />
    </bean>

    <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService" />
    <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService" />
    <bean id="taskService" factory-bean="processEngine" factory-method="getTaskService" />
    <bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService" />
    <bean id="managementService" factory-bean="processEngine" factory-method="getManagementService" />

    (...)

It works well and create a lot of tables on my application schema at startup.

My problem is : tables are created in the 'public' schema in my postgres database. I would have preferred to put those tables in a separate schema, say 'activity'.

Fact is that after browsing the documentation / the net for almost two hours, I didn't found any way to change the default schema target creation behavior.

Any help... greatly appreciated ! ;)


问:
Are parameters Thread Safe?
I have read a number of posts on this subject, but I'm still just a little fuzzy how C# handles parameters in methods when called from multiple threads.

I have a series of utility methods that need to be called from about 60+ threads.  It's a process that downloads patient data for roughly 20,000-30,000 patients every day.  For the most part, the methods look like this.

```<code>
    Public Static SomeClass
    {
        public static string StringToSQLBool(string s)
        {
           if (s.Trim() == "")
           {
              return "Null";
           }
           else
           {
              if (s.ToLower() == "true")
              {
                 return "1";
              }
              {
                 return "0";
              }
           }
        }

        public static string DateToSQLAnsiStr(string ADate)
        {
            try
            {
               if (ADate.Trim() != "")
               {
                  DateTime d = Convert.ToDateTime(ADate);
                  return "{d '" + d.Year.ToString() + "-" +
                          d.Month.ToString().PadLeft(2, '0') + "-" +
                          d.Day.ToString().PadLeft(2, '0') + "'}";
               }
               else
               {
                  return "Null";
               }
            }
            catch
            {
               return "Null";
            }
        }
    }
</code>
```

As I understand it, as long as the parameters are used in the method that are singular to the calling thread, then it would be considered safe.

Are these thread-safe without locking?

答:
Threading is an issue when trying to manipulate (or manipulate in one and access in another) the same objects across threads. It does not matter by what 'name' the objects are accessed.

Using the term 'variable' to discuss class members is a less than ideal way, especially in context, to refer to fields. And that is the key difference here: local variables, including parameters, can never be accessed by two threads at once1.

To answer the question verbatim: "parameters are always thread-safe" although the objects that they evaluate to may not be.

However, in the example code, only immutable objects2 are used:

The String + operator returns a new string, being the concatenation of the two, and it is this new String result which is re-assigned to the local (parameter) variable. The same logic applies for the DateTime.

Thus, there is no threading issue with the posted code; because there is no shared manipulation (or manipulation and access) of the same objects, regardless of local variables or parameters.

1 Access to closure-bound variables, including parameters, must generally treated as field access in context of threading. This is because the C# compiler synthesizes/creates a hidden object behind the scenes which is then manipulated to store the closure state.

2 If an object cannot be manipulated after it is created, it is considered an immutable type and is inherently thread-safe. Strings fall into this category. (Thread-safety of immutable objects is only guaranteed after the object has been fully constructed.)

Title: Are parameters Thread Safe?

Body:
I have read a number of posts on this subject, but I'm still just a little fuzzy how C# handles parameters in methods when called from multiple threads.

I have a series of utility methods that need to be called from about 60+ threads.  It's a process that downloads patient data for roughly 20,000-30,000 patients every day.  For the most part, the methods look like this.

    Public Static SomeClass
    {
        public static string StringToSQLBool(string s)
        {
           if (s.Trim() == "")
           {
              return "Null";
           }
           else
           {
              if (s.ToLower() == "true")
              {
                 return "1";
              }
              {
                 return "0";
              }
           }
        }

        public static string DateToSQLAnsiStr(string ADate)
        {
            try
            {
               if (ADate.Trim() != "")
               {
                  DateTime d = Convert.ToDateTime(ADate);
                  return "{d '" + d.Year.ToString() + "-" +
                          d.Month.ToString().PadLeft(2, '0') + "-" +
                          d.Day.ToString().PadLeft(2, '0') + "'}";
               }
               else
               {
                  return "Null";
               }
            }
            catch
            {
               return "Null";
            }
        }
    }

As I understand it, as long as the parameters are used in the method that are singular to the calling thread, then it would be considered safe.

Are these thread-safe without locking?


问:
Upsert many documents in MongoDB and php
I try to import data from an external source into my mongodb with php. Every row from the external data is one mongodb document. Every row has an unique id called uid.

Now I am trying the following: I want to insert a new row, if no document with the same uid exists already (Upsert).

For a single document, I would do the following:

```<code>$collection->updateOne(
    ["uid" => "2"],
    ['$set' => [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "Test"
    ]],
    [
        "upsert" => true
    ]
);
</code>```

Step 1:

Is it possible to override the complete document, not just set specific fields? Something like this:

```<code>$collection->updateOne(
    ["uid" => "2"],
    [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "Test"
    ],
    [
        "upsert" => true
    ]
);
</code>```

This is not working, since i get a First key in $update argument is not an update operator error. How to do it?

Step 2

For performance reasons, I want to use insertMany or updateMany function to bulk upsert multiple documents.

But what filter do I need for updateMany:

```<code>$db->updateMany(
    [???????],
    [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "XXX"
    ],
    [
        "upsert" => true
    ]
);
</code>```

答:
The questions are totally independent.

The first:

Use update with multi: false (which is default) instead of updateOne. The former allows to replaces an existing document entirely.

The second:

updateMany doesn't work this way. It is more like update with multi: true - it applies update operations to all documents that match the filter. When used with upsert: true the filter fields should be uniquely indexed to avoid multiple upserts.

If you want to perform multiple upserts with individual filters in one go, you can use bulk update:

```<code>$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
$bulk->update(["uid" => "2"], [
    "newfield" => date("Y-m-d H:i:s"),
    "name" => "Test"
]]);
$bulk->update(["uid" => "3"], [
    "newfield" => date("Y-m-d H:i:s"),
    "name" => "Another Test"
]]);
$bulk->update(["uid" => "4"], [
    "newfield" => date("Y-m-d H:i:s"),
    "name" => "One more Test"
]]);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
</code>```

Please read the page behind the last link for limitations of bulk operations.

Body:
I try to import data from an external source into my mongodb with php. Every row from the external data is one mongodb document. Every row has an unique id called uid.

Now I am trying the following: I want to insert a new row, if no document with the same uid exists already (Upsert).

For a single document, I would do the following:

$collection->updateOne(
    ["uid" => "2"],
    ['$set' => [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "Test"
    ]],
    [
        "upsert" => true
    ]
);

Step 1:

Is it possible to override the complete document, not just set specific fields? Something like this:

$collection->updateOne(
    ["uid" => "2"],
    [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "Test"
    ],
    [
        "upsert" => true
    ]
);

This is not working, since i get a First key in $update argument is not an update operator error. How to do it?

Step 2

For performance reasons, I want to use insertMany or updateMany function to bulk upsert multiple documents.

But what filter do I need for updateMany:

$db->updateMany(
    [???????],
    [
        "newfield" => date("Y-m-d H:i:s"),
        "name" => "XXX"
    ],
    [
        "upsert" => true
    ]
);

Body:
The questions are totally independent.

The first:

Use update with multi: false (which is default) instead of updateOne. The former allows to replaces an existing document entirely.

The second:

updateMany doesn't work this way. It is more like update with multi: true - it applies update operations to all documents that match the filter. When used with upsert: true the filter fields should be uniquely indexed to avoid multiple upserts.

If you want to perform multiple upserts with individual filters in one go, you can use bulk update:

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
$bulk->update(["uid" => "2"], [
    "newfield" => date("Y-m-d H:i:s"),
    "name" => "Test"
]]);
$bulk->update(["uid" => "3"], [
    "newfield" => date("Y-m-d H:i:s"),
    "name" => "Another Test"
]]);
$bulk->update(["uid" => "4"], [
    "newfield" => date("Y-m-d H:i:s"),
    "name" => "One more Test"
]]);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);

Please read the page behind the last link for limitations of bulk operations.


问:
Error while trying to parse a website url using python . how to debug it?
```<code>#!/usr/bin/python
import json
import urllib
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits:
    print ' ', h['url']
    resp = urllib.urlopen(h['url'])
        res = resp.read()

    soup = BeautifulSoup(res)
        print soup.prettify()
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

showsome('sachin')
</code>```

What is the wrong in this code ?

Note all the 4 links that I am getting out of the search , I am feeding it back to extract the contents out of it , and then use BeautifulSoup to parse it . How should I go about it ?

答: You can debug python code in a proper environment that lets you examine what is going on with the variables, stacks and all using the eclipse ide with a module name pydev, try it to see what is going on inside.</p>

Body:
#!/usr/bin/python
import json
import urllib
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits:
    print ' ', h['url']
    resp = urllib.urlopen(h['url'])
        res = resp.read()

    soup = BeautifulSoup(res)
        print soup.prettify()
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

showsome('sachin')

What is the wrong in this code ?

Note all the 4 links that I am getting out of the search , I am feeding it back to extract the contents out of it , and then use BeautifulSoup to parse it . How should I go about it ?


问:
Elastic Search query analyzing
I want to see all the tokens is generated from 'match' text

I am wondering to know is there any specific file or capability to show details of query executing in elastic search or another way to see what is generated as a sequence of tokens when I am using 'match level' queries?

答:
I did not use the log file to see which tokens are generated in the time of 'match' operation. Instead, I used _analayze endpoint.

Better to say if you want to use analyser of the specific index (in the case of different indices that each of them using its own customised analyser) put the name of the index in the URL:

```<code>POST /index_name/_analyze
{
  "text" : "1174HHA8285M360"
}
</code>```

This will use the default analyser defined in that index. And if we have more than one analyser in one index we can specify it in the query just as follow:

```<code>POST /index_name/_analyze
{
  "text" : "1174HHA8285M360",
  "analyzer" : "analyser_name"
}
</code>```

Title: Elastic Search query analyzing

Body:
I did not use the log file to see which tokens are generated in the time of 'match' operation. Instead, I used _analayze endpoint.

Better to say if you want to use analyser of the specific index (in the case of different indices that each of them using its own customised analyser) put the name of the index in the URL:

POST /index_name/_analyze
{
  "text" : "1174HHA8285M360"
}

This will use the default analyser defined in that index. And if we have more than one analyser in one index we can specify it in the query just as follow:

POST /index_name/_analyze
{
  "text" : "1174HHA8285M360",
  "analyzer" : "analyser_name"
}


问:
RxAndroid call one network call after another
I am new to RxJava. I have a scenario where I want to call first login webservice (getLoginObservable) and on success, want to call another webservice (getFetchDataObservable) to get user information.

I have following code working if login is success. But I am unable to figure out how to code failure case.

```<code>private void doLogin() {
    emailAddress = editTextUsername.getText().toString();
    final String password = editTextPassword.getText().toString();
    showProgress(null, getString(R.string.loggingInPleaseWait));

    getLoginObservable(editTextUsername.getText().toString(), password)
            .map(response -> {
                if (response.result) {
                    getPresenter().saveUserDetails(getContext(), emailAddress, true, response.dataObject.questionId, response.dataObject.question);
                }
                return response;
            })
            .flatMap(response -> {
                return getFetchDataObservable();
            })
            .subscribe(res -> {
                dismissProgress();
                if (res.result) {
                    saveInformation(password, res);
                } else {
                    ConstantsMethods.showOkButtonDialog(getContext(), res.message, null);
                }
            }, e -> {
                dismissProgress();
                if (e instanceof NoInternetConnectionException) {
                    ConstantsMethods.showOkButtonDialog(getContext(), getString(R.string.noInternetConnection), null);
                }
                Log.e(LoginFragment.class.getSimpleName(), e.getMessage());
            });
}

    private Observable<WsResponse<SecurityQuestion>> getLoginObservable(String userName, String password) {
        return Observable.<WsResponse<SecurityQuestion>>create(subscriber -> {
            getPresenter().doLogin(getActivity(), userName, password, appType,
                    new Callback<Void, WsResponse<SecurityQuestion>>() {
                        @Override
                        public Void callback(final WsResponse<SecurityQuestion> param) {
                            subscriber.onNext(param);
                            return null;
                        }
                    });
        });
    }

    private Observable<WsResponse<PatientDataProfile>> getFetchDataObservable() {
        return Observable.create(subscriber -> {
            new AfPatientsPresenter().fetchPatientData(getContext(), emailAddress, "", new Callback<Void, WsResponse<PatientDataProfile>>() {
                @Override
                public Void callback(WsResponse<PatientDataProfile> param1) {
                    subscriber.onNext(param1);
                    subscriber.onComplete();
                    return null;
                }
            });
        });
    }
</code>```

As much i know RxJava, I can figure out that getLoginObservable(editTextUsername.getText().toString(), password) observable send response to map (map(response -> { ... }) and this map return response to flatmap (flatMap(response -> { ... }) and its response is sent to subscriber. Here i am just lost that how can i skip (second network call)flatmap flatMap(response -> { ... } to send response directly to subscriber in case of login failure.

答:
instead of:

```<code>.map(response -> {
                if (response.result) {
                    getPresenter().saveUserDetails(getContext(), emailAddress, true, response.dataObject.questionId, response.dataObject.question);
                }
                return response;
            })
</code>```

you can use:

```<code>flatMap(response-> {
    if (response.result) {
        getPresenter().saveUserDetails(getContext(), emailAddress, true, response.dataObject.questionId, response.dataObject.question);
        return Observable.just(response);
    } else {
        return Observable.error(new Exception("Login failed")); // or maybe some LoginFailedException() you can reuse
    }
})
</code>```

Body:
I am new to RxJava. I have a scenario where I want to call first login webservice (getLoginObservable) and on success, want to call another webservice (getFetchDataObservable) to get user information.

I have following code working if login is success. But I am unable to figure out how to code failure case.

private void doLogin() {
    emailAddress = editTextUsername.getText().toString();
    final String password = editTextPassword.getText().toString();
    showProgress(null, getString(R.string.loggingInPleaseWait));

    getLoginObservable(editTextUsername.getText().toString(), password)
            .map(response -> {
                if (response.result) {
                    getPresenter().saveUserDetails(getContext(), emailAddress, true, response.dataObject.questionId, response.dataObject.question);
                }
                return response;
            })
            .flatMap(response -> {
                return getFetchDataObservable();
            })
            .subscribe(res -> {
                dismissProgress();
                if (res.result) {
                    saveInformation(password, res);
                } else {
                    ConstantsMethods.showOkButtonDialog(getContext(), res.message, null);
                }
            }, e -> {
                dismissProgress();
                if (e instanceof NoInternetConnectionException) {
                    ConstantsMethods.showOkButtonDialog(getContext(), getString(R.string.noInternetConnection), null);
                }
                Log.e(LoginFragment.class.getSimpleName(), e.getMessage());
            });
}

    private Observable<WsResponse<SecurityQuestion>> getLoginObservable(String userName, String password) {
        return Observable.<WsResponse<SecurityQuestion>>create(subscriber -> {
            getPresenter().doLogin(getActivity(), userName, password, appType,
                    new Callback<Void, WsResponse<SecurityQuestion>>() {
                        @Override
                        public Void callback(final WsResponse<SecurityQuestion> param) {
                            subscriber.onNext(param);
                            return null;
                        }
                    });
        });
    }

    private Observable<WsResponse<PatientDataProfile>> getFetchDataObservable() {
        return Observable.create(subscriber -> {
            new AfPatientsPresenter().fetchPatientData(getContext(), emailAddress, "", new Callback<Void, WsResponse<PatientDataProfile>>() {
                @Override
                public Void callback(WsResponse<PatientDataProfile> param1) {
                    subscriber.onNext(param1);
                    subscriber.onComplete();
                    return null;
                }
            });
        });
    }

As much i know RxJava, I can figure out that getLoginObservable(editTextUsername.getText().toString(), password) observable send response to map (map(response -> { ... }) and this map return response to flatmap (flatMap(response -> { ... }) and its response is sent to subscriber. Here i am just lost that how can i skip (second network call)flatmap flatMap(response -> { ... } to send response directly to subscriber in case of login failure.

Body:
instead of:

.map(response -> {
                if (response.result) {
                    getPresenter().saveUserDetails(getContext(), emailAddress, true, response.dataObject.questionId, response.dataObject.question);
                }
                return response;
            })

you can use:

flatMap(response-> {
    if (response.result) {
        getPresenter().saveUserDetails(getContext(), emailAddress, true, response.dataObject.questionId, response.dataObject.question);
        return Observable.just(response);
    } else {
        return Observable.error(new Exception("Login failed")); // or maybe some LoginFailedException() you can reuse
    }
})


问:
I added successfully a column to previous table using MySQL database dynamically
I added successfully a column to previous table using MySQL database dynamically, But when I  fill up the form run and send it to the the database  in my local server it shows:

```<code>SQLSTATE[42S02]: Base table or view not found: 1146 Table 'forge. posts' doesn't exist (SQL: select count(*) as aggregate from ` posts` where ` slug ` = hihello)
</code>```

My code of migration table 'posts'

```<code><?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }
}
</code>```

for inserting a new column called 'slug' in the 'post' table

```<code> <?php

 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Database\Migrations\Migration;

class AddSlugToUsers extends Migration
{

    public function up(){

      Schema::table('posts',function(Blueprint $table){
        $table->string('slug')->unique()->after('title');

      });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(){

     Schema::table('posts',function(Blueprint $table){
     $table->dropColumn('slug');
        });

    }
   }
</code>```

Successfully inserted 'slug' column but problem is posting the form to the database.

```<code><?php

namespace App\Http\Controllers;
            use Illuminate\Http\Request;
             use App\Http\Requests;
           use App\Http\Controllers\Controller;
          use App\Post;
         use Session;

          class PostController extends Controller
          {
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
           public function index()
            {
            $posts = Post::orderBy('id', 'desc')->paginate(10);
            return view('posts.index')->withPosts($posts);
            }

        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
             public function create()
             {
            return view('posts.create');
             }

        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
             public function store(Request $request)
            {
            // validate the data
            $this->validate($request, array(
                    'title' => 'required|max:255',
                    'slug'
                   =>'required|min:5|alpha_dash|min:5|max:255|unique:
             posts, slug ',
                    'body'  => 'required'));

            // store in the database
            $post = new Post;

            $post->title = $request->title;
            $post->slug =  $request->title;
            $post->body = $request->body;

            $post->save();

            Session::flash('success', 'The blog post was successfully
            save!');

            return redirect()->route('posts.show', $post->id);
             }

        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function show($id)
             {
            $post = Post::find($id);
            return view('posts.show')->withPost($post);
             }

        /**
         * Show the form for editing the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function edit($id)
            {
            // find the post in the database and save as a var
            $post = Post::find($id);
            // return the view and pass in the var we previously created
            return view('posts.edit')->withPost($post);
            }

        /**
         * Update the specified resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function update(Request $request, $id)
             {
            // Validate the data
            $this->validate($request, array(
                    'title' => 'required|max:255',

             'slug'=>'required|alpha_dash|min:5|max:255|unique:posts,slug',
                    'body'  => 'required'
                ));
            // Save the data to the database
            $post = Post::find($id);

            $post->title = $request->input('title');
            $post->title=$request->input('slug');
            $post->body = $request->input('body');

            $post->save();

            // set flash data with success message
            Session::flash('success', 'This post was successfully saved.');

            // redirect with flash data to posts.show
            return redirect()->route('posts.show', $post->id);
           }

         /**
         * Remove the specified resource from storage.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function destroy($id)
            {
            $post = Post::find($id);

            $post->delete();
            //for sesssion
            Session::flash('success', 'The post was successfully deleted.');
            return redirect()->route('posts.index');
               }
            }
</code>```

答: 'forge. posts' this looks like there is a space before table name posts. Did you check your model if there is a s</p>

Body:
I added successfully a column to previous table using MySQL database dynamically, But when I  fill up the form run and send it to the the database  in my local server it shows:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'forge. posts' doesn't exist (SQL: select count(*) as aggregate from ` posts` where ` slug ` = hihello)

My code of migration table 'posts'

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }
}

for inserting a new column called 'slug' in the 'post' table

 <?php

 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Database\Migrations\Migration;

class AddSlugToUsers extends Migration
{

    public function up(){

      Schema::table('posts',function(Blueprint $table){
        $table->string('slug')->unique()->after('title');

      });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(){

     Schema::table('posts',function(Blueprint $table){
     $table->dropColumn('slug');
        });

    }
   }

Successfully inserted 'slug' column but problem is posting the form to the database.

<?php

namespace App\Http\Controllers;
            use Illuminate\Http\Request;
             use App\Http\Requests;
           use App\Http\Controllers\Controller;
          use App\Post;
         use Session;

          class PostController extends Controller
          {
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
           public function index()
            {
            $posts = Post::orderBy('id', 'desc')->paginate(10);
            return view('posts.index')->withPosts($posts);
            }

        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
             public function create()
             {
            return view('posts.create');
             }

        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
             public function store(Request $request)
            {
            // validate the data
            $this->validate($request, array(
                    'title' => 'required|max:255',
                    'slug'
                   =>'required|min:5|alpha_dash|min:5|max:255|unique:
             posts, slug ',
                    'body'  => 'required'));

            // store in the database
            $post = new Post;

            $post->title = $request->title;
            $post->slug =  $request->title;
            $post->body = $request->body;

            $post->save();

            Session::flash('success', 'The blog post was successfully
            save!');

            return redirect()->route('posts.show', $post->id);
             }

        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function show($id)
             {
            $post = Post::find($id);
            return view('posts.show')->withPost($post);
             }

        /**
         * Show the form for editing the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function edit($id)
            {
            // find the post in the database and save as a var
            $post = Post::find($id);
            // return the view and pass in the var we previously created
            return view('posts.edit')->withPost($post);
            }

        /**
         * Update the specified resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function update(Request $request, $id)
             {
            // Validate the data
            $this->validate($request, array(
                    'title' => 'required|max:255',

             'slug'=>'required|alpha_dash|min:5|max:255|unique:posts,slug',
                    'body'  => 'required'
                ));
            // Save the data to the database
            $post = Post::find($id);

            $post->title = $request->input('title');
            $post->title=$request->input('slug');
            $post->body = $request->input('body');

            $post->save();

            // set flash data with success message
            Session::flash('success', 'This post was successfully saved.');

            // redirect with flash data to posts.show
            return redirect()->route('posts.show', $post->id);
           }

         /**
         * Remove the specified resource from storage.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
            public function destroy($id)
            {
            $post = Post::find($id);

            $post->delete();
            //for sesssion
            Session::flash('success', 'The post was successfully deleted.');
            return redirect()->route('posts.index');
               }
            }


问:
How to catch application errors in java/jax-rs
I wonder if there is anything like Application_Error from Global.asax in asp.net but in java?

I am using jersey & angularJS. I already implemented the ServletContextListener that I tested and it works, but cannot find something like application_error

```<code>public class MyListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("Shutting down");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("Starting");
    }

}
</code>```

I also have a class which implements the method filter from ContainerRequestFilter where I validate my jwt token and accept or reject the authorization.

All my methods don't handle the exception within, it means that I want to catch the exception of the whole application even if it is produced in a resource, a method from service layer or data access layer, etc. and try to send an email to admin and redirect to error.html page.

Thanks in advance.

答:
I think there are some solutions independent of Jersey that you can implement for catching all exceptions in a java web application. I am assuming that your project has web.xml -

1) Using Filter - You can add one filter in your web application and catch all exceptions there. Filter is like an interceptor which can be called before processing any request.

You can define filter in web.xml -

```<code><filter>
    <filter-name>exceptionFilter</filter-name>
    <filter-class>com.MyExceptionFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>exceptionFilter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>
</code>```

Now define MyExceptionFilter class -

```<code>public final class MyExceptionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
        try {
            // forward request to subsequent filter/resource/servlet
            filterChain.doFilter(request, response);
        } catch ( Throwable ex ) {
            // do whatever you want in case any exception occurred and not caught in the request processing class
            // forward request to error page
            request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
        }
    }

    @Override
    public void destroy() {
    }

}
</code>```

Problem with this approach is that it is possible to define multiple filters in a web application. The sequence of how these filters will get called is not fixed.

2) Error Page - You can also define error page for the web application. In web.xml, add below lines -

```<code><error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/ExceptionHandler</location>
</error-page>
</code>```

and then define ExceptionHandler servlet -

```<code>@WebServlet("/ExceptionHandler")
public class ExceptionHandler extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processException(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processException(request, response);
    }
    private void processException(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        Throwable throwable = (Throwable) request
                .getAttribute("javax.servlet.error.exception");
        // do whatever you want to do with exception
        // forward request to error page
        request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
    }
}
</code>```

Body:
I wonder if there is anything like Application_Error from Global.asax in asp.net but in java?

I am using jersey & angularJS. I already implemented the ServletContextListener that I tested and it works, but cannot find something like application_error

public class MyListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("Shutting down");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("Starting");
    }

}

I also have a class which implements the method filter from ContainerRequestFilter where I validate my jwt token and accept or reject the authorization.

All my methods don't handle the exception within, it means that I want to catch the exception of the whole application even if it is produced in a resource, a method from service layer or data access layer, etc. and try to send an email to admin and redirect to error.html page.

Thanks in advance.

Body:
I think there are some solutions independent of Jersey that you can implement for catching all exceptions in a java web application. I am assuming that your project has web.xml -

1) Using Filter - You can add one filter in your web application and catch all exceptions there. Filter is like an interceptor which can be called before processing any request.

You can define filter in web.xml -

<filter>
    <filter-name>exceptionFilter</filter-name>
    <filter-class>com.MyExceptionFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>exceptionFilter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>

Now define MyExceptionFilter class -

public final class MyExceptionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
        try {
            // forward request to subsequent filter/resource/servlet
            filterChain.doFilter(request, response);
        } catch ( Throwable ex ) {
            // do whatever you want in case any exception occurred and not caught in the request processing class
            // forward request to error page
            request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
        }
    }

    @Override
    public void destroy() {
    }

}

Problem with this approach is that it is possible to define multiple filters in a web application. The sequence of how these filters will get called is not fixed.

2) Error Page - You can also define error page for the web application. In web.xml, add below lines -

<error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/ExceptionHandler</location>
</error-page>

and then define ExceptionHandler servlet -

@WebServlet("/ExceptionHandler")
public class ExceptionHandler extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processException(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processException(request, response);
    }
    private void processException(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        Throwable throwable = (Throwable) request
                .getAttribute("javax.servlet.error.exception");
        // do whatever you want to do with exception
        // forward request to error page
        request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
    }
}


问:
jquery selector doesn't give all elements
In the next web page I want to select all
 elements with Jquery.
I want to select all the products that are inside

https://www.walmart.com/browse/home-improvement/air-quality/1072864_133032_1231459

I have tried:

```<code>$(".search-product-result ul li")
$("ul.search-result-gridview-items li")
</code>```

Also I have tried:

```<code>$("li")
$("ul li")
$("section li")
</code>```

to select all
 and none works.
All of them give one
 and not all.

Why this happens?

答:
Did you try using Child Selector (“parent > child”)?

```<code>$( ".search-product-result > li" )
</code>```

Check more info here:
https://api.jquery.com/category/selectors/hierarchy-selectors/

Body:
In the next web page I want to select all
 elements with Jquery.
I want to select all the products that are inside

https://www.walmart.com/browse/home-improvement/air-quality/1072864_133032_1231459

I have tried:

$(".search-product-result ul li")
$("ul.search-result-gridview-items li")

Also I have tried:

$("li")
$("ul li")
$("section li")

to select all
 and none works.
All of them give one
 and not all.

Why this happens?

Body:
Did you try using Child Selector (“parent > child”)?

$( ".search-product-result > li" )

Check more info here:
https://api.jquery.com/category/selectors/hierarchy-selectors/


问:
Mysql query issues when passing string or date
I have a mysql query that works fine in phpmyadmin, but does not give the expected results on my php page.  I am sure that I have something wrong in the code.

Here is the php code that passes the variable

```<code>print "<td><a href='transactions_by_transaction_date.php?var=\''".urlencode(
$row['transaction_date'])."'\''>".$row['transaction_date']."</a></td></tr><tr>";
</code>```

And here is where I create my query

```<code>$var = $_GET['var'];
echo $var;
$stmt2 = $db->prepare("SELECT * FROM bo_transactions WHERE
transaction_date=:var ORDER BY transaction_id");
$stmt2->bindParam(':var',$var,PDO::PARAM_STR);
$stmt2->execute();
// set the resulting array to associative
$result = $stmt2->setFetchMode(PDO::FETCH_ASSOC);
</code>```

I have the echo $var line to verify that it is passing the correct date and it appears to be.  The field transaction_date is a date type.

What have I missed?

答: My apologies to everyone.  The problem was not in the code posted  it was a typing error in  my output.  Thank you to all that gave me input</p>

Body:
I have a mysql query that works fine in phpmyadmin, but does not give the expected results on my php page.  I am sure that I have something wrong in the code.

Here is the php code that passes the variable

print "".$row['transaction_date']."

";

And here is where I create my query

$var = $_GET['var'];
echo $var;
$stmt2 = $db->prepare("SELECT * FROM bo_transactions WHERE
transaction_date=:var ORDER BY transaction_id");
$stmt2->bindParam(':var',$var,PDO::PARAM_STR);
$stmt2->execute();
// set the resulting array to associative
$result = $stmt2->setFetchMode(PDO::FETCH_ASSOC);

I have the echo $var line to verify that it is passing the correct date and it appears to be.  The field transaction_date is a date type.

What have I missed?


问:
Python beautifulsoup to remove all tags/content with specific tag and text following
I am using beautifulsoup in python and want to remove everything from a string that are enclosed in a certain tag and have a specific non-closing tag with specific text following it. In this example, I want to remove all the documents that have type tag inside it with text of DOCA.

Let's say I have something like this:

```<code><body>
    <document>
        <type>DOCA
            <sequence>1
            <filename>DOCA.htm
            <description>FORM DOCA
            <text>
                <title>Form DOCA</title>
                <h5 align="left"><a href="#toc">Table of Contents</a></h5>
    </document>
    <document>
        <type>DOCB
        <sequence>1
        <filename>DOCB.htm
        <description>FORM DOCB
        <text>
            <title>Form DOCB</title>
            <h5 align="left"><a href="#toc">Table of Contents</a></h5>
    </document>
<body>
</code>```

What I want to do is remove all <document> that have a <type> of DOCA. I have tried the following but it doesn't work:

```<code>>>print(soup.find('document').find('type', text = re.compile('DOCA.*')))
None
</code>```

答:
You can query all documents and then, within each document, query all types, check to see if DOCA exists in any of them, and delete the entire enclosing document if it does.

```<code>from bs4 import BeautifulSoup

soup = BeautifulSoup(..., 'html.parser')

for doc in soup.find_all('document'):
    for type in doc.find_all('type'):
        if 'DOCA' in type.text:
            doc.extract()
            break

print(soup)
</code>```

Output:

```<code><body>

<document>
<type>DOCB
        <sequence>1
        <filename>DOCB.htm
        <description>FORM DOCB
        <text>
<title>Form DOCB</title>
<h5 align="left"><a href="#toc">Table of Contents</a></h5>
</text></description></filename></sequence></type></document>
</body>
</code>```

Body:
I am using beautifulsoup in python and want to remove everything from a string that are enclosed in a certain tag and have a specific non-closing tag with specific text following it. In this example, I want to remove all the documents that have type tag inside it with text of DOCA.

Let's say I have something like this:

    <document>
        <type>DOCA
            <sequence>1
            <filename>DOCA.htm
            <description>FORM DOCA
            <text>
                <title>Form DOCA</title>

Table of Contents

    </document>
    <document>
        <type>DOCB
        <sequence>1
        <filename>DOCB.htm
        <description>FORM DOCB
        <text>
            <title>Form DOCB</title>

Table of Contents

    </document>

What I want to do is remove all <document> that have a <type> of DOCA. I have tried the following but it doesn't work:

>>print(soup.find('document').find('type', text = re.compile('DOCA.*')))
None

Body:
You can query all documents and then, within each document, query all types, check to see if DOCA exists in any of them, and delete the entire enclosing document if it does.

from bs4 import BeautifulSoup

soup = BeautifulSoup(..., 'html.parser')

for doc in soup.find_all('document'):
    for type in doc.find_all('type'):
        if 'DOCA' in type.text:
            doc.extract()
            break

print(soup)

Output:

<body>

<document>
<type>DOCB
        <sequence>1
        <filename>DOCB.htm
        <description>FORM DOCB
        <text>
<title>Form DOCB</title>
<h5 align="left"><a href="#toc">Table of Contents</a></h5>
</text></description></filename></sequence></type></document>
</body>


问:
XSL changing spaces in a link to %20
I  need to change links that are automatically created by MOSS07 with spaces to include %20.

Example:

```<code>{$SafeLinkURL}
</code>```

which would output https://stackoverflow.com/example of spaces

https://stackoverflow.com/example%20of%20spaces

If anyone can shed some light on this please do.

Thanks in advance,

Nick

答:
The XSLT 2.0 function(s) Dimitrie mentioned are:

fn:encode-for-uri()

fn:iri-to-uri()

fn:escape-html-uri()

See the links for detailed specification and examples. In your case (if you could've used a XSLT 2.0 processor) the fn:iri-to-uri() would've solved your problem.

But none of these functions will not work in your current XSLT 1.0 environment. So please see this post as a future reference for other people.

Title: XSL changing spaces in a link to %20

Body:
I  need to change links that are automatically created by MOSS07 with spaces to include %20.

Example:

{$SafeLinkURL}

which would output https://stackoverflow.com/example of spaces

https://stackoverflow.com/example%20of%20spaces

If anyone can shed some light on this please do.

Thanks in advance,

Nick


问:
MSXML2.DOMDocument load function fails in VBA
I've been struggling with the below issue for a while now and couldn't find the solution yet.

There is an iShare page with an XML file that I want to download using VBA code, then later process the XML file and save into MS Access database.

I've been using the below code for about 4 years now, it worked perfectly without any issues. But suddenly it stopped working this week.
Any ideas why?

the code:

```<code>Private Function GetRequests() As Boolean
  On Error GoTo ErrHandler

  Dim oDoc As MSXML2.DOMDocument
  Dim Url As String
  Dim sFileName As String

  Set oDoc = New MSXML2.DOMDocument
  oDoc.async = False
  Url = cUrlDatabase & "/" & cApplicationName & "/In/" & cReqXmlFile

  UpdateStatus "Loading " & cReqXmlFile

  If Not oDoc.Load(Url) Then
    c_sLastError = "Could not load XML " & Url
    GoTo EndProc
  End If

  sFileName = sPath & "\Data\requests.xml"

  oDoc.Save sFileName

  GetRequests = True
End Function
</code>```

The code fails at the oDoc.Load(Url) part, it comes back false.

答:
Here's an example of how to gather error details:

```<code>      Dim xDoc As MSXML.DOMDocument
      Set xDoc = New MSXML.DOMDocument

      If xDoc.Load("C:\My Documents\cds.xml") Then
        ' The document loaded successfully.
        ' Now do something intersting.
      Else
        ' The document failed to load.
        Dim strErrText As String
        Dim xPE As MSXML.IXMLDOMParseError

        ' Obtain the ParseError object
        Set xPE = xDoc.parseError
        With xPE
            strErrText = "Your XML Document failed to load" & _
            "due the following error." & vbCrLf & _
            "Error #: " & .errorCode & ": " & xPE.reason & _
            "Line #: " & .Line & vbCrLf & _
            "Line Position: " & .linepos & vbCrLf & _
            "Position In File: " & .filepos & vbCrLf & _
            "Source Text: " & .srcText & vbCrLf & _
            "Document URL: " & .url
        End With

        MsgBox strErrText, vbExclamation End If

        Set xPE = Nothing
      End If
</code>```

Example taken from here.

Body:
I've been struggling with the below issue for a while now and couldn't find the solution yet.

There is an iShare page with an XML file that I want to download using VBA code, then later process the XML file and save into MS Access database.

I've been using the below code for about 4 years now, it worked perfectly without any issues. But suddenly it stopped working this week.
Any ideas why?

the code:

Private Function GetRequests() As Boolean
  On Error GoTo ErrHandler

  Dim oDoc As MSXML2.DOMDocument
  Dim Url As String
  Dim sFileName As String

  Set oDoc = New MSXML2.DOMDocument
  oDoc.async = False
  Url = cUrlDatabase & "/" & cApplicationName & "/In/" & cReqXmlFile

  UpdateStatus "Loading " & cReqXmlFile

  If Not oDoc.Load(Url) Then
    c_sLastError = "Could not load XML " & Url
    GoTo EndProc
  End If

  sFileName = sPath & "\Data\requests.xml"

  oDoc.Save sFileName

  GetRequests = True
End Function

The code fails at the oDoc.Load(Url) part, it comes back false.

Body:
Here's an example of how to gather error details:

      Dim xDoc As MSXML.DOMDocument
      Set xDoc = New MSXML.DOMDocument

      If xDoc.Load("C:\My Documents\cds.xml") Then
        ' The document loaded successfully.
        ' Now do something intersting.
      Else
        ' The document failed to load.
        Dim strErrText As String
        Dim xPE As MSXML.IXMLDOMParseError

        ' Obtain the ParseError object
        Set xPE = xDoc.parseError
        With xPE
            strErrText = "Your XML Document failed to load" & _
            "due the following error." & vbCrLf & _
            "Error #: " & .errorCode & ": " & xPE.reason & _
            "Line #: " & .Line & vbCrLf & _
            "Line Position: " & .linepos & vbCrLf & _
            "Position In File: " & .filepos & vbCrLf & _
            "Source Text: " & .srcText & vbCrLf & _
            "Document URL: " & .url
        End With

        MsgBox strErrText, vbExclamation End If

        Set xPE = Nothing
      End If

Example taken from here.