问:
send data from one page to another using Query String
I have two HTML pages I want to pass data from one page to another page using a query string. I tried this way but it doesn't work, what might be the problem can anyone help out.

$(function () {
   $("#btnQueryString").bind("click", function () {

    var pack = document.getElementById('pack-val').value;
    var info = document.getElementById('info').value;

     var url = "packages-style-1.html?&pack=" + pack + "&download=" + info;
     window.location.href = url;
     });
  });

 var queryString = new Array();
        $(function () {
    if (queryString.length == 0) {
      if (window.location.search.split('?').length > 1) {
         var params = window.location.search.split('?')[1].split('&');
         for (var i = 0; i < params.length; i++) {
           var key = params[i].split('=')[0];
             var value = decodeURIComponent(params[i].split('=')[1]);
              queryString[key] = value;
       }
        }
       }
            if (queryString["pack"] != null && queryString["download"]) {
                var data = "Values from QueryString

";
               pack += "Pack: " + queryString["pack"] + " Download: " + queryString["info"];
                $("#lblData").html(data);
            }
     });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="at-intenet-package" id="pack">
  <thead></thead>
 <tbody>
   <tr>
  <td class="at-int-speedname" id="pack-val">
   <h2 class="at-IntHdr">Value Pack</h2>
   <ul>
   <li><b>768Kbps</b> Download Speed</li>
               <li><b>384Kbps</b> Upload Speed</li>
   </ul>
   </td>
   <td class="at-int-dl1">
     <h2 class="at-IntHdr">6.2<span class="time-sep">hrs</span></h2>
   <span class="todownload">to download*</span>
   </td>
   <td class="at-int-dl2">
     <h2 class="at-IntHdr">55<span class="time-sep">min</span></h2>
     <span class="todownload">to download*</span>
    </td>
    <td class="at-int-dl3">
   <h2 class="at-IntHdr">11<span class="time-sep">min</span></h2>
   <span class="todownload">to download*</span>
    </td>
    <td class="at-int-price" id="info">
    <h2 class="at-IntHdr"><span>$</span>17.95<span class="per-month"> per mon*</span></h2>
   <span class="check-info">12 Month Pricing<br>No Contract Required<br>Equipment Priced Separately</span>
     </td>
     <td class="at-int-check">Check Availability</td>
  </tr>
    </tbody>
  </table></code>```

when I click on check Availability button the data send to another page i want only first and last  info.

Image 1:

Image 2: Expected o/p after sent Data.

答:
It appears you are trying to get the contents of the pack-val and info elements. It is possible to send query string parameters to another page like you are doing as long as you are setting the window.location.href like you are doing. However, I believe your values for pack-val and info will always be "undefined".

Are you trying to send the html contents of those elements to the next page? If so that is not advised as you will need to escape and unescape the contents and generally it is not good to pass html content back and forth as query strings.

It would be better to store the package details in an array or variable and just pass the selected package key back and forth.

Body:
I have two HTML pages I want to pass data from one page to another page using a query string. I tried this way but it doesn't work, what might be the problem can anyone help out.

$(function () {
   $("#btnQueryString").bind("click", function () {

    var pack = document.getElementById('pack-val').value;
    var info = document.getElementById('info').value;

     var url = "packages-style-1.html?&pack=" + pack + "&download=" + info;
     window.location.href = url;
     });
  });

 var queryString = new Array();
        $(function () {
    if (queryString.length == 0) {
      if (window.location.search.split('?').length > 1) {
         var params = window.location.search.split('?')[1].split('&');
         for (var i = 0; i < params.length; i++) {
           var key = params[i].split('=')[0];
             var value = decodeURIComponent(params[i].split('=')[1]);
              queryString[key] = value;
       }
        }
       }
            if (queryString["pack"] != null && queryString["download"]) {
                var data = "Values from QueryString

";
               pack += "Pack: " + queryString["pack"] + " Download: " + queryString["info"];
                $("#lblData").html(data);
            }
     });

Value Pack

768Kbps Download Speed

384Kbps Upload Speed

6.2hrs

   to download*

55min

     to download*

11min

   to download*

$17.95 per mon*

   12 Month Pricing
No Contract Required
Equipment Priced Separately

     Check Availability

when I click on check Availability button the data send to another page i want only first and last  info.

Image 1:

Image 2: Expected o/p after sent Data.


来源: stackexchange

问:
Spring Websocket - How can I detect client disconnect
I am new to spring

I have this class :

```<code>public class Server extends TextWebSocketHandler implements WebSocketHandler {

    WebSocketSession clientsession;
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {

        clientsession = session;

    }
</code>```

I need to detect a client disconnect on clientsession.
implement ApplicationListener  but its not clear how I can register the listener?
do I need to do it in my web.xml ?

答:
You can use listeners to detect when session is connected or closed.
More information about listeners you can find by this link.

Example how to detect connected session:

```<code>@Component
public class SessionConnectedEventListener implements ApplicationListener<SessionConnectedEvent> {

    private IWebSocketSessionService webSocketSessionService;

    public SessionConnectedEventListener(IWebSocketSessionService webSocketSessionService) {
        this.webSocketSessionService = webSocketSessionService;
    }

    @Override
    public void onApplicationEvent(SessionConnectedEvent event) {
        webSocketSessionService.saveSession(event);
    }
}
</code>```

Example how to detect when session is disconneted:

```<code>@Component
public class SessionDisconnectEventListener implements ApplicationListener<SessionDisconnectEvent> {

    private IWebSocketSessionService webSocketSessionService;

    public SessionDisconnectEventListener(IWebSocketSessionService webSocketSessionService) {
        this.webSocketSessionService = webSocketSessionService;
    }

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        webSocketSessionService.removeSession(event);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to spring

I have this class :

public class Server extends TextWebSocketHandler implements WebSocketHandler {

    WebSocketSession clientsession;
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {

        clientsession = session;

    }

I need to detect a client disconnect on clientsession.
implement ApplicationListener  but its not clear how I can register the listener?
do I need to do it in my web.xml ?

Body:
You can use listeners to detect when session is connected or closed.
More information about listeners you can find by this link.

Example how to detect connected session:

@Component
public class SessionConnectedEventListener implements ApplicationListener<SessionConnectedEvent> {

    private IWebSocketSessionService webSocketSessionService;

    public SessionConnectedEventListener(IWebSocketSessionService webSocketSessionService) {
        this.webSocketSessionService = webSocketSessionService;
    }

    @Override
    public void onApplicationEvent(SessionConnectedEvent event) {
        webSocketSessionService.saveSession(event);
    }
}

Example how to detect when session is disconneted:

@Component
public class SessionDisconnectEventListener implements ApplicationListener<SessionDisconnectEvent> {

    private IWebSocketSessionService webSocketSessionService;

    public SessionDisconnectEventListener(IWebSocketSessionService webSocketSessionService) {
        this.webSocketSessionService = webSocketSessionService;
    }

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        webSocketSessionService.removeSession(event);
    }
}


问:
eclipse field editor for password
I have a preferences page that has some StringFieldEditor to hold different values. One of them is meant for password. I want the password to be displayed as asterisk or some other special character. I have to use org.eclipse.jface.preference.FieldEditor or any of its subclass only. Please suggest how I can achieve this.</p>

答:
```<code>StringFieldEditor passwordField = new StringFieldEditor("password", "Password", getFieldEditorParent());
passwordField.getTextControl(getFieldEditorParent()).setEchoChar('*');

addField(passwordField);
</code>```

Title: eclipse field editor for password


问:
Consider marking one of the beans as @Primary
In my Java spring application, I have

```<code>public class BinarySearchImpl {

    @Autowired
    @Qualifier("Quick")
    SortAlgorithem sorter;

    Log log=LogFactory.getLog(BinarySearchImpl.class);

    public BinarySearchImpl(SortAlgorithem sorter) {
        log.info("Binary Search Bean is created");
        this.sorter=sorter;
    }
</code>```

SortAlgorithem is an interface which makes my application loosely coupled:

```<code>public interface SortAlgorithem {

    public int[] sort(int[] arrayNumbers);

}
</code>```

And then there are 2 implementations for this interface. One is BubbleSort:

```<code>@Component
@Qualifier("Bubble")
public class BubbleSort implements SortAlgorithem {

    Log log=LogFactory.getLog(BubbleSort.class);

    public int[] sort(int[] numbers) {
        log.info("Bubble sort is called");
        return numbers;
    }
}
</code>```

and the other is QuickSort:

```<code>@Component
@Qualifier("Quick")
//@Primary
public class QuickSort implements SortAlgorithem{

    Log log= LogFactory.getLog(QuickSort.class);

    public int[] sort(int[] numbers) {
        log.info("Quick Sort is called");
        return numbers;
    }

}
</code>```

At the end, when I call my app it complains with this message:

```<code>Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
</code>```

I am wondering... Why @Qualifier annotation does not work?

答:
try </p>

```<code>@Component("qualifier_name")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my Java spring application, I have

public class BinarySearchImpl {

    @Autowired
    @Qualifier("Quick")
    SortAlgorithem sorter;

    Log log=LogFactory.getLog(BinarySearchImpl.class);

    public BinarySearchImpl(SortAlgorithem sorter) {
        log.info("Binary Search Bean is created");
        this.sorter=sorter;
    }

SortAlgorithem is an interface which makes my application loosely coupled:

public interface SortAlgorithem {

    public int[] sort(int[] arrayNumbers);

}

And then there are 2 implementations for this interface. One is BubbleSort:

@Component
@Qualifier("Bubble")
public class BubbleSort implements SortAlgorithem {

    Log log=LogFactory.getLog(BubbleSort.class);

    public int[] sort(int[] numbers) {
        log.info("Bubble sort is called");
        return numbers;
    }
}

and the other is QuickSort:

@Component
@Qualifier("Quick")
//@Primary
public class QuickSort implements SortAlgorithem{

    Log log= LogFactory.getLog(QuickSort.class);

    public int[] sort(int[] numbers) {
        log.info("Quick Sort is called");
        return numbers;
    }

}

At the end, when I call my app it complains with this message:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

I am wondering... Why @Qualifier annotation does not work?

Body:
try

@Component("qualifier_name")


问:
error C2011: 'SelectorBox' : 'class' type redefinition
I have a problem with a following code:

```<code> #ifndef HEADER_H_

    class SelectorBox{
    public:
        string selectorName;
        map < string, string > attributeMap;
        void setSelectorName(string name);
        void setAttribute(string key, string value);
    };
    string trimTheString(string str); //trimming a string
    #endif

//include libraries
#include "Header.h"
using namespace std;
int main()
{
    vector <SelectorBox> vectorSelectBox;
    SelectorBox *selectorBox;

//code
return 0;
}

#include "Header.h"
#include "main.cpp"

void SelectorBox::setSelectorName(string name)   //setter
{
    name = trimTheString(name);
    selectorName = name;
}

void SelectorBox::setAttribute(string key, string value)  //setter
{
    key = trimTheString(key);
    value = trimTheString(value);
    attributeMap[key] = value;
}
</code>```

When I compile a program, it shows many errors (specifically errors 4430 and 2061), but I believe that the main error is:
error C2011: 'SelectorBox' : 'class' type redefinition.

答:
I guess, you have 3 files:

Header.h

main.cpp

FileX.cpp (you didn't disclose the real name of mister X so far)

In main.cpp you are including Header.h, in FileX.cpp you are including Header.h and main.cpp. Let me show a simplified version of what happens here:

The contents of main.cpp gets transformed into

```<code>//include libraries
class SelectorBox{
public:
    string selectorName;
    map < string, string > attributeMap;
    void setSelectorName(string name);
    void setAttribute(string key, string value);
};
string trimTheString(string str); //trimming a string

using namespace std;
int main()
{
    vector <SelectorBox> vectorSelectBox;
    SelectorBox *selectorBox;

//code
return 0;
}
</code>```

Assuming you included string and map and there is another using namespace std; somewhere before your class definition, this could compile without errors.

But now let's see what happens in FileX.cpp. Its contents gets transformed into the following, and I hope you'll see now what the compilers sees: there is more than one definition of the class SelectorBox:

```<code>class SelectorBox{
public:
    string selectorName;
    map < string, string > attributeMap;
    void setSelectorName(string name);
    void setAttribute(string key, string value);
};
string trimTheString(string str); //trimming a string
//include libraries
class SelectorBox{
public:
    string selectorName;
    map < string, string > attributeMap;
    void setSelectorName(string name);
    void setAttribute(string key, string value);
};
string trimTheString(string str); //trimming a string

using namespace std;
int main()
{
    vector <SelectorBox> vectorSelectBox;
    SelectorBox *selectorBox;

//code
return 0;
}

void SelectorBox::setSelectorName(string name)   //setter
{
    name = trimTheString(name);
    selectorName = name;
}

void SelectorBox::setAttribute(string key, string value)  //setter
{
    key = trimTheString(key);
    value = trimTheString(value);
    attributeMap[key] = value;
}
</code>```

... compilers use to call that a "redefinition".

Body:
I have a problem with a following code:

 #ifndef HEADER_H_

    class SelectorBox{
    public:
        string selectorName;
        map < string, string > attributeMap;
        void setSelectorName(string name);
        void setAttribute(string key, string value);
    };
    string trimTheString(string str); //trimming a string
    #endif

//include libraries
#include "Header.h"
using namespace std;
int main()
{
    vector <SelectorBox> vectorSelectBox;
    SelectorBox *selectorBox;

//code
return 0;
}

#include "Header.h"
#include "main.cpp"

void SelectorBox::setSelectorName(string name)   //setter
{
    name = trimTheString(name);
    selectorName = name;
}

void SelectorBox::setAttribute(string key, string value)  //setter
{
    key = trimTheString(key);
    value = trimTheString(value);
    attributeMap[key] = value;
}

When I compile a program, it shows many errors (specifically errors 4430 and 2061), but I believe that the main error is:
error C2011: 'SelectorBox' : 'class' type redefinition.

Body:
I guess, you have 3 files:

Header.h

main.cpp

FileX.cpp (you didn't disclose the real name of mister X so far)

In main.cpp you are including Header.h, in FileX.cpp you are including Header.h and main.cpp. Let me show a simplified version of what happens here:

The contents of main.cpp gets transformed into

//include libraries
class SelectorBox{
public:
    string selectorName;
    map < string, string > attributeMap;
    void setSelectorName(string name);
    void setAttribute(string key, string value);
};
string trimTheString(string str); //trimming a string

using namespace std;
int main()
{
    vector <SelectorBox> vectorSelectBox;
    SelectorBox *selectorBox;

//code
return 0;
}

Assuming you included string and map and there is another using namespace std; somewhere before your class definition, this could compile without errors.

But now let's see what happens in FileX.cpp. Its contents gets transformed into the following, and I hope you'll see now what the compilers sees: there is more than one definition of the class SelectorBox:

class SelectorBox{
public:
    string selectorName;
    map < string, string > attributeMap;
    void setSelectorName(string name);
    void setAttribute(string key, string value);
};
string trimTheString(string str); //trimming a string
//include libraries
class SelectorBox{
public:
    string selectorName;
    map < string, string > attributeMap;
    void setSelectorName(string name);
    void setAttribute(string key, string value);
};
string trimTheString(string str); //trimming a string

using namespace std;
int main()
{
    vector <SelectorBox> vectorSelectBox;
    SelectorBox *selectorBox;

//code
return 0;
}

void SelectorBox::setSelectorName(string name)   //setter
{
    name = trimTheString(name);
    selectorName = name;
}

void SelectorBox::setAttribute(string key, string value)  //setter
{
    key = trimTheString(key);
    value = trimTheString(value);
    attributeMap[key] = value;
}

... compilers use to call that a "redefinition".


问:
Find a phrase in defined list with a file
I have a list name my= ['cbs is down','abnormal']
and I have opened a file in read mode

Now I want to search any of the string available in list that exist in that file and perform the if action

```<code>fopen  =  open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
    if my in line:
            print ("down")
</code>```

and when I execute it, I get the following

```<code>Traceback (most recent call last):
  File "E:/python/fileread.py", line 4, in <module>
    if my in line:
TypeError: 'in <string>' requires string as left operand, not list
</code>```

答:
```<code>fopen  =  open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
    for x in my:
        if x in line:
            print ("down")
</code>```

Sample input

```<code>Some text cbs is down
Yes, abnormal
not in my list
cbs is down
</code>```

Output

```<code>down
down
down
</code>```

Body:
I have a list name my= ['cbs is down','abnormal']
and I have opened a file in read mode

Now I want to search any of the string available in list that exist in that file and perform the if action

fopen  =  open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
    if my in line:
            print ("down")

and when I execute it, I get the following

Traceback (most recent call last):
  File "E:/python/fileread.py", line 4, in <module>
    if my in line:
TypeError: 'in <string>' requires string as left operand, not list

Body:
fopen  =  open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
    for x in my:
        if x in line:
            print ("down")

Sample input

Some text cbs is down
Yes, abnormal
not in my list
cbs is down

Output

down
down
down


问:
How to flatten an xarray dataset into a 1D numpy array?
Is there a simple way of flattening an xarray dataset into a single 1D numpy array?

For example, flattening the following test dataset:

```<code>xr.Dataset({
    'a' : xr.DataArray(
                   data=[10,11,12,13,14],
                   coords={'x':[0,1,2,3,4]},
                   dims={'x':5}
          ),
    'b' : xr.DataArray(data=1,coords={'y':0}),
    'c' : xr.DataArray(data=2,coords={'y':0}),
    'd' : xr.DataArray(data=3,coords={'y':0})
})
</code>```

to

```<code>[10,11,12,13,14,1,2,3]
</code>```

?

答:
Get Dataset from question:

```<code>ds = xr.Dataset({
'a' : xr.DataArray(
               data=[10,11,12,13,14],
               coords={'x':[0,1,2,3,4]},
               dims={'x':5}
      ),
'b' : xr.DataArray(data=1,coords={'y':0}),
'c' : xr.DataArray(data=2,coords={'y':0}),
'd' : xr.DataArray(data=3,coords={'y':0})
})
</code>```

Get the list of data variables:

```<code>variables = ds.data_vars
</code>```

Use the np.flatten()  method to reduce arrays to 1D:

```<code>arrays = [ ds[i].values.flatten() for i in variables ]
</code>```

Then expand list of 1D arrays (as detailed in this answer):

```<code>arrays = [i for j in arrays for i in j  ]
</code>```

Now convert this to an array as requested in Q (as currently a list):

```<code>array = np.array(arrays)
</code>```

Body:
Is there a simple way of flattening an xarray dataset into a single 1D numpy array?

For example, flattening the following test dataset:

xr.Dataset({
    'a' : xr.DataArray(
                   data=[10,11,12,13,14],
                   coords={'x':[0,1,2,3,4]},
                   dims={'x':5}
          ),
    'b' : xr.DataArray(data=1,coords={'y':0}),
    'c' : xr.DataArray(data=2,coords={'y':0}),
    'd' : xr.DataArray(data=3,coords={'y':0})
})

to

[10,11,12,13,14,1,2,3]

?

Body:
Get Dataset from question:

ds = xr.Dataset({
'a' : xr.DataArray(
               data=[10,11,12,13,14],
               coords={'x':[0,1,2,3,4]},
               dims={'x':5}
      ),
'b' : xr.DataArray(data=1,coords={'y':0}),
'c' : xr.DataArray(data=2,coords={'y':0}),
'd' : xr.DataArray(data=3,coords={'y':0})
})

Get the list of data variables:

variables = ds.data_vars

Use the np.flatten()  method to reduce arrays to 1D:

arrays = [ ds[i].values.flatten() for i in variables ]

Then expand list of 1D arrays (as detailed in this answer):

arrays = [i for j in arrays for i in j  ]

Now convert this to an array as requested in Q (as currently a list):

array = np.array(arrays)


问:
Appcelerator studio won't start (on loading screen)
After updating Appcelerator Studio it won't load. Starting it produces starting screen showing "loading studio" 4ever. It is just stuck there. Any idea on what might have caused this?

Thanks.enter image description here

答:
I had this problem too (on a Mac). You can try this:

download and install the latest Appcelerator version

logout of Appcelerator using CLI or terminal window (if you can open it of course), using "appc logout -D".

Start Appcelerator again and login again. This works for me.


问:
Xcode 8 playground live view doesn't work
In my Swift playground, I entered the following code to test the live view feature:

```<code>let view = UIView()

PlaygroundPage.current.liveView = view
</code>```

But for some reason the live view doesn't display on the right in the Assistant Editor. Initially I thought that Xcode wasn't finished running the playground. But I waited and waited and it still doesn't show.

Screenshot:

Any help?

答:
In Xcode 9.0 as well as having:

```<code>PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

You have to manually open the assistant editor then the playground with current focus will show the UIView.

Body:
In my Swift playground, I entered the following code to test the live view feature:

let view = UIView()

PlaygroundPage.current.liveView = view

But for some reason the live view doesn't display on the right in the Assistant Editor. Initially I thought that Xcode wasn't finished running the playground. But I waited and waited and it still doesn't show.

Screenshot:

Any help?

Body:
In Xcode 9.0 as well as having:

PlaygroundPage.current.needsIndefiniteExecution = true

You have to manually open the assistant editor then the playground with current focus will show the UIView.


答:
This should work things out:

```<code>if any(i in line for i in my):
    ...
</code>```

Basically you are going through my and checking whether any of its elements is present in line.

Title: Find a phrase in defined list with a file

Body:
This should work things out:

if any(i in line for i in my):
    ...

Basically you are going through my and checking whether any of its elements is present in line.


问:
How do I center text horizontally and vertically in a TextView?
How do I center the text horizontally and vertically in a TextView, so that it appears exactly in the middle of the TextView in Android?

答:
You can center a Text View using android:gravity="center"

The code goes as follows

```<code>    <TextView
     android:text="@string/yourText"
     android layout_height="wrap_content"
     android layout_height="wrap_content"
     android:gravity="center" />
</code>```

OwnerDisplayName: J. Pablo Fernández

Body:
You can center a Text View using android:gravity="center"

The code goes as follows

    <TextView
     android:text="@string/yourText"
     android layout_height="wrap_content"
     android layout_height="wrap_content"
     android:gravity="center" />


问:
styling for all elements except for a div and all divs inside it

$('#main div').not('#2 > #3').each(function() {
  $(this).css('background-color', 'blue');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">

  <div id="1">
    <div>Some text in paragraph 1</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="2">
    <div id="3">Some text in paragraph 2</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="3">
    <div>Some text in paragraph 3</div>
    <div>Some text in paragraph 1</div>
  </div><br>

</div></code>```

I want the css not to be applied for the nested divs of div with id=2. Any suggestions?

答:
$('#main>div').not('#2').each(function() {
  $(this).css('background-color', 'blue');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">

  <div id="1">
    <div>Some text in paragraph 1</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="2">
    <div id="3">Some text in paragraph 2</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="3">
    <div>Some text in paragraph 3</div>
    <div>Some text in paragraph 1</div>
  </div><br>

</div></code>```

Body:
$('#main div').not('#2 > #3').each(function() {
  $(this).css('background-color', 'blue');
});

Some text in paragraph 1

Some text in paragraph 1

Some text in paragraph 2

Some text in paragraph 1

Some text in paragraph 3

Some text in paragraph 1

I want the css not to be applied for the nested divs of div with id=2. Any suggestions?

Body:
$('#main>div').not('#2').each(function() {
  $(this).css('background-color', 'blue');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">

  <div id="1">
    <div>Some text in paragraph 1</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="2">
    <div id="3">Some text in paragraph 2</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="3">
    <div>Some text in paragraph 3</div>
    <div>Some text in paragraph 1</div>
  </div><br>

</div>


问:
How to blur background images in Android
What is the best way to blur background images like the image below? I saw some code and libraries but their are a couple of years old or like BlurBehind library, but it doesn't give the same effect.

答:
The simplest way to achieve this is given below,

I)

```<code>Glide.with(context.getApplicationContext())
                        .load(Your Path)
                        .override(15, 15) // (change according to your wish)
                        .error(R.drawable.placeholder)
                        .into(image.score);
</code>```

else you can follow the code below..

II)

1.Create a class.(Code is given below)

```<code>public class BlurTransformation extends BitmapTransformation {

    private RenderScript rs;

    public BlurTransformation(Context context) {
        super( context );

        rs = RenderScript.create( context );
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );

        // Allocate memory for Renderscript to work with
        Allocation input = Allocation.createFromBitmap(
            rs,
            blurredBitmap,
            Allocation.MipmapControl.MIPMAP_FULL,
            Allocation.USAGE_SHARED
        );
        Allocation output = Allocation.createTyped(rs, input.getType());

        // Load up an instance of the specific script that we want to use.
        ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setInput(input);

        // Set the blur radius
        script.setRadius(10);

        // Start the ScriptIntrinisicBlur
        script.forEach(output);

        // Copy the output to the blurred bitmap
        output.copyTo(blurredBitmap);

        toTransform.recycle();

        return blurredBitmap;
    }

    @Override
    public String getId() {
        return "blur";
    }
}
</code>```

2.Set image to ImageView using Glide.

eg:

```<code>Glide.with(this)
     .load(expertViewDetailsModel.expert.image)
     .asBitmap()
     .transform(new BlurTransformation(this))
     .into(ivBackground);
</code>```

Body:
The simplest way to achieve this is given below,

I)

Glide.with(context.getApplicationContext())
                        .load(Your Path)
                        .override(15, 15) // (change according to your wish)
                        .error(R.drawable.placeholder)
                        .into(image.score);

else you can follow the code below..

II)

1.Create a class.(Code is given below)

public class BlurTransformation extends BitmapTransformation {

    private RenderScript rs;

    public BlurTransformation(Context context) {
        super( context );

        rs = RenderScript.create( context );
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );

        // Allocate memory for Renderscript to work with
        Allocation input = Allocation.createFromBitmap(
            rs,
            blurredBitmap,
            Allocation.MipmapControl.MIPMAP_FULL,
            Allocation.USAGE_SHARED
        );
        Allocation output = Allocation.createTyped(rs, input.getType());

        // Load up an instance of the specific script that we want to use.
        ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setInput(input);

        // Set the blur radius
        script.setRadius(10);

        // Start the ScriptIntrinisicBlur
        script.forEach(output);

        // Copy the output to the blurred bitmap
        output.copyTo(blurredBitmap);

        toTransform.recycle();

        return blurredBitmap;
    }

    @Override
    public String getId() {
        return "blur";
    }
}

2.Set image to ImageView using Glide.

eg:

Glide.with(this)
     .load(expertViewDetailsModel.expert.image)
     .asBitmap()
     .transform(new BlurTransformation(this))
     .into(ivBackground);


问:
node.js async/await using with MySQL
I need to get all results synchronized and append to a  string with async/await keywords like c#. </p>

<p>I am new to node.js and I can not adapt this new syntax to my code.    </p>

```<code>var string1 = '';
var string2 = '';
var string3 = '';
var string4 = '';

DatabasePool.getConnection(function(err, connection) {

        connection.query(query,function (err, result) {
            if (err){};
            string1 = result;
        });

        connection.query(query,function (err, result) {
            if (err){};
            string2 = result;
        });

        connection.query(query,function (err, result) {
            if (err){};
            string3 = result;
        });

        connection.query(query,function (err, result) {
            if (err){};
            string4 = result;
        });

       //I need to append all these strings to appended_text but
       //all variables remain blank because below code runs first.
       var appended_text = string1 + string2 + string3 + string4;
});
</code>```

答:
Use mysql2 packet. It has promise wrapper so you can do that: </p>

```<code>async function example1 () {
  const mysql = require('mysql2/promise');
  const conn = await mysql.createConnection({ database: test });
  let [rows, fields] = await conn.execute('select ?+? as sum', [2, 2]);
}
</code>```

Title: node.js async/await using with MySQL

Body:
I need to get all results synchronized and append to a  string with async/await keywords like c#.

I am new to node.js and I can not adapt this new syntax to my code.

var string1 = '';
var string2 = '';
var string3 = '';
var string4 = '';

DatabasePool.getConnection(function(err, connection) {

        connection.query(query,function (err, result) {
            if (err){};
            string1 = result;
        });

        connection.query(query,function (err, result) {
            if (err){};
            string2 = result;
        });

        connection.query(query,function (err, result) {
            if (err){};
            string3 = result;
        });

        connection.query(query,function (err, result) {
            if (err){};
            string4 = result;
        });

       //I need to append all these strings to appended_text but
       //all variables remain blank because below code runs first.
       var appended_text = string1 + string2 + string3 + string4;
});

Body:
Use mysql2 packet. It has promise wrapper so you can do that:

async function example1 () {
  const mysql = require('mysql2/promise');
  const conn = await mysql.createConnection({ database: test });
  let [rows, fields] = await conn.execute('select ?+? as sum', [2, 2]);
}


问:
Docker access container IP/Port directly
I have docker container for experiments. So I don't know which ports I will use later when I trying new apps.
Isn't it possible to access docker container application with ip/port from the host without exposing it in the docker-run command?</p>

答:
update: the OP didn't provide that it was about docker-for-mac in the original question, so the rest cannot be applied if you are using this version of docker.

Original answer:

Yes, you can do that.

Let's say that you have a container named boring_pare and a web app running on port 8080. You can access it from your host machine by requesting http://[ip_of_boring_pare]:8080. If you are using the default docker network, this ip will probably be in the 172.17.0.xxx range.

To find this IP, you can inspect your container by using:

```<code>docker container inspect boring_pare
</code>```

Also, you mention:

Isn't it possible to access docker container application with ip/port from the host without exposing it in the docker-run command?

The correct term here would be publishing. Further reading:

Documentation about EXPOSE / Dockerfile

...The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. To actually publish the port when running the container, use the -p flag on docker run to publish and map one or more ports, or the -P flag to publish all exposed ports and map them to to high-order ports.

Difference between “expose” and “publish” in docker

Update to answer to @robie2011's comment:

Below, I run 3 commands:

run a nginx container without publishing port 80 to a host port

inspect its ip address

use curl from host to access the nginx home page

My console output:

```<code>$ docker run --rm --name some-nginx -d nginx
0e53d3b5ef6d65a4731c4066f3523c5ecd3c118abedae44b33e89fdf8e401632

$ docker container inspect --format '{{ .NetworkSettings.IPAddress }}' some-nginx
172.17.0.3

$ curl 172.17.0.3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
$
</code>```

Body:
update: the OP didn't provide that it was about docker-for-mac in the original question, so the rest cannot be applied if you are using this version of docker.

Original answer:

Yes, you can do that.

Let's say that you have a container named boring_pare and a web app running on port 8080. You can access it from your host machine by requesting http://[ip_of_boring_pare]:8080. If you are using the default docker network, this ip will probably be in the 172.17.0.xxx range.

To find this IP, you can inspect your container by using:

docker container inspect boring_pare

Also, you mention:

Isn't it possible to access docker container application with ip/port from the host without exposing it in the docker-run command?

The correct term here would be publishing. Further reading:

Documentation about EXPOSE / Dockerfile

...The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. To actually publish the port when running the container, use the -p flag on docker run to publish and map one or more ports, or the -P flag to publish all exposed ports and map them to to high-order ports.

Difference between “expose” and “publish” in docker

Update to answer to @robie2011's comment:

Below, I run 3 commands:

run a nginx container without publishing port 80 to a host port

inspect its ip address

use curl from host to access the nginx home page

My console output:

$ docker run --rm --name some-nginx -d nginx
0e53d3b5ef6d65a4731c4066f3523c5ecd3c118abedae44b33e89fdf8e401632

$ docker container inspect --format '{{ .NetworkSettings.IPAddress }}' some-nginx
172.17.0.3

$ curl 172.17.0.3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
$


问:
android alert dialog not showing
I am trying to show an alert inside of an onTouchListener but I can't get it to show. I am pretty new at this but I have been following some good tutorials to no avail.
This is part of the code...any ideas why this alert won't show?

```<code>mSwitcher.setOnTouchListener(new OnTouchListener()
{
   public void onItemClick(AdapterView<?> parent, View v, int position, long id)
   {
   }

   @Override public boolean onTouch(View v, MotionEvent event)
   {
      // the attempt at the alert
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("Are you sure you want to exit?")
             .setCancelable(false)
             .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      MyActivity.this.finish();
                   }
                })
             .setNegativeButton("No", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      dialog.cancel();
                   }
                });
      AlertDialog alert = builder.create();
      return false;
   }
});
</code>```

I think my structure is ok, but I can't even compile.

答: I updated the code so the brackets are in the proper place.  It should compile now.  And as JLund points out, change the last line from builder.create(); to builder.show(); and that should work.  If you wish to keep the builder.create(); call, just add alert.show(); after it.

Title: android alert dialog not showing

Body:
I am trying to show an alert inside of an onTouchListener but I can't get it to show. I am pretty new at this but I have been following some good tutorials to no avail.
This is part of the code...any ideas why this alert won't show?

mSwitcher.setOnTouchListener(new OnTouchListener()
{
   public void onItemClick(AdapterView<?> parent, View v, int position, long id)
   {
   }

   @Override public boolean onTouch(View v, MotionEvent event)
   {
      // the attempt at the alert
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("Are you sure you want to exit?")
             .setCancelable(false)
             .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      MyActivity.this.finish();
                   }
                })
             .setNegativeButton("No", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      dialog.cancel();
                   }
                });
      AlertDialog alert = builder.create();
      return false;
   }
});

I think my structure is ok, but I can't even compile.

ContentLicense: CC BY-SA 2.5


问:
Automated way to update a view code using sql script?
Lets suppose i have a table A with 4 columns and I've created a view for the same table which consists of all 4 columns. Now i want to write a script/stored procedure which should update the view code whenever new column is added to Table A in a same physical order.

For Example:
Table  A has following columns

```<code>'Name','Age','Gender','Address'
</code>```

Supposed view code is:

```<code>Select Name,Age,Gender,Address from Table A
</code>```

Now i add an additional column PhoneNumber on Table A. When i run script/Stored Procedure this new column should automatically be added to the query as follows:

Desired view code generated after i run script should be like this:

```<code>Select Name,Age,Gender,Address,PhoneNumber from Table A
</code>```

答:
If I understand what are you asking, then why you need to specify the columns, instead of that change your code in the view to:

```<code>SELECT * FROM TableA
</code>```

In this way the View will always return all columns in that table.

Body:
Lets suppose i have a table A with 4 columns and I've created a view for the same table which consists of all 4 columns. Now i want to write a script/stored procedure which should update the view code whenever new column is added to Table A in a same physical order.

For Example:
Table  A has following columns

'Name','Age','Gender','Address'

Supposed view code is:

Select Name,Age,Gender,Address from Table A

Now i add an additional column PhoneNumber on Table A. When i run script/Stored Procedure this new column should automatically be added to the query as follows:

Desired view code generated after i run script should be like this:

Select Name,Age,Gender,Address,PhoneNumber from Table A

Body:
If I understand what are you asking, then why you need to specify the columns, instead of that change your code in the view to:

SELECT * FROM TableA

In this way the View will always return all columns in that table.


问:
Sencha - ExtJS - QuickTipManager - Build Failed c2008
Settings: Ubuntu 16.04.3 LTS, MATE 1.12.1
What I've done:

Install the Sencha CMD;

Download the Sencha ExtJS (trial version 6.5.2.15);

Created the folder /home/master/sencha/test;

Do
cd /home/master/sencha/test; sencha app init --ext@6.5.2
in the terminal;

Put next code into app.js:

```<code>Ext.application({
name: 'Test',

requires: [
    'Ext.tip.QuickTipManager'
],

launch: function () {
   Ext.tip.QuickTipManager.init();
}
});
</code>```

Do sencha app watch in the terminal.

What I've got:

```<code>Sencha Cmd v6.5.2.15
[INF] Processing Build Descriptor : default (development environment)
[INF] Starting server on port : 1841
[INF] Mapping http://localhost:1841/~cmd to /home/scilef/bin/Sencha/Cmd/6.5.2.15...
[INF] Mapping http://localhost:1841/ to /home/scilef/sencha/test...
[INF] Server started at port : 1841
[INF] Application available at http://localhost:1841
[INF] Loading compiler context
[INF] Loading app json manifest...
[ERR] C2008: Requirement had no matching files (Ext.tip.QuickTipManager) -- /home/scilef/sencha/test/app.js:7:150
[ERR]
[ERR] BUILD FAILED
[ERR] com.sencha.exceptions.ExBuild: Failed to find any files for /home/scilef/sencha/test/app.js::ClassRequire::Ext.tip.QuickTipManager
[ERR]   at or
[ERR] g.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
[ERR]
[ERR] Total time: 9 seconds

[ERR] /home/scilef/bin/Sencha/Cmd/6.5.2.15/plugin.xml:378: The following error occurred while executing this line:
/home/scilef/bin/Sencha/Cmd/6.5.2.15/ant/build/app/build-impl.xml:253: The following error occurred while executing this line:
/home/scilef/bin/Sencha/Cmd/6.5.2.15/ant/build/app/watch-impl.xml:87: The following error occurred while executing this line:
/home/scilef/bin/Sencha/Cmd/6.5.2.15/ant/build/app/build-impl.xml:387: The following error occurred while executing this line:
/home/scilef/bin/Sencha/Cmd/6.5.2.15/ant/build/app/init-impl.xml:436: com.sencha.exceptions.ExBuild: Failed to find any files for /home/scilef/sencha/test/app.js::ClassRequire::Ext.tip.QuickTipManager
[ERR] A log is available in the file "/home/scilef/sencha/test/sencha-error-20171113.log"
</code>```

Same errors I've got when tried to require (or use) Ext.form.field.Number, Ext.form.field.Date or Ext.progressBar.

I'm new with ExtJS and I spent all last day to find the way to fix this problem, but haven't any success. What am I doing wrong?

答:
The problem is that since ExtJS 6.0.0, there are two toolkits in one bundle, named classic and modern. Your command creates a so-called "universal app" that supports both toolkits. The app.js file is also used for both toolkits; and in the subfolders classic and modern, there are files that are used for only one toolkit.

Modern toolkit is for modern devices with touch, classic toolkit for classic devices with mouse and keyboard.

Ext.tip.QuickTipManager is only available for the classic toolkit, since tooltips are shown on mouseover - you cannot hover on touch devices. So you have to move all the QuickTipManager code to classic/Application.js or whatever javascript files you have in your classic folder.

Body:
Settings: Ubuntu 16.04.3 LTS, MATE 1.12.1
What I've done:

Install the Sencha CMD;

Download the Sencha ExtJS (trial version 6.5.2.15);

Created the folder /home/master/sencha/test;

Do
cd /home/master/sencha/test; sencha app init --ext@6.5.2
in the terminal;

Put next code into app.js:

Ext.application({
name: 'Test',

requires: [
    'Ext.tip.QuickTipManager'
],

launch: function () {
   Ext.tip.QuickTipManager.init();
}
});

Do sencha app watch in the terminal.

What I've got:

Sencha Cmd v6.5.2.15
[INF] Processing Build Descriptor : default (development environment)
[INF] Starting server on port : 1841
[INF] Mapping http://localhost:1841/~cmd to /home/scilef/bin/Sencha/Cmd/6.5.2.15...
[INF] Mapping http://localhost:1841/ to /home/scilef/sencha/test...
[INF] Server started at port : 1841
[INF] Application available at http://localhost:1841
[INF] Loading compiler context
[INF] Loading app json manifest...
[ERR] C2008: Requirement had no matching files (Ext.tip.QuickTipManager) -- /home/scilef/sencha/test/app.js:7:150
[ERR]
[ERR] BUILD FAILED
[ERR] com.sencha.exceptions.ExBuild: Failed to find any files for /home/scilef/sencha/test/app.js::ClassRequire::Ext.tip.QuickTipManager
[ERR]   at or
[ERR] g.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
[ERR]
[ERR] Total time: 9 seconds

[ERR] /home/scilef/bin/Sencha/Cmd/6.5.2.15/plugin.xml:378: The following error occurred while executing this line:
/home/scilef/bin/Sencha/Cmd/6.5.2.15/ant/build/app/build-impl.xml:253: The following error occurred while executing this line:
/home/scilef/bin/Sencha/Cmd/6.5.2.15/ant/build/app/watch-impl.xml:87: The following error occurred while executing this line:
/home/scilef/bin/Sencha/Cmd/6.5.2.15/ant/build/app/build-impl.xml:387: The following error occurred while executing this line:
/home/scilef/bin/Sencha/Cmd/6.5.2.15/ant/build/app/init-impl.xml:436: com.sencha.exceptions.ExBuild: Failed to find any files for /home/scilef/sencha/test/app.js::ClassRequire::Ext.tip.QuickTipManager
[ERR] A log is available in the file "/home/scilef/sencha/test/sencha-error-20171113.log"

Same errors I've got when tried to require (or use) Ext.form.field.Number, Ext.form.field.Date or Ext.progressBar.

I'm new with ExtJS and I spent all last day to find the way to fix this problem, but haven't any success. What am I doing wrong?


问:
How to extract CSRF cookie from request and send into HTTP Request without using parameter in JMeter
I am new to JMeter. I am performing login test. I am trying to extract CSRF token but i don't get it. I don't know how to resolve it.

request data

regular expression extractor

When i try to put CSRF token - "reference name" into HTTP Request - "Parameters" i got the error.

HTTP Request - Parameters

I am stuck here. I don't know how to put CSRF token - "reference name" without "Parameters". Please help me.

答:
The easiest way of extracting a cookie into a JMeter Variable is using HTTP Cookie Manager

Add HTTP Cookie Manager to your Test Plan

Add the next line to user.properties file (lives in "bin" folder of your JMeter installation)

```<code>CookieManager.save.cookies=false
</code>```

Restart JMeter to pick the property up

When the cookie will come from the server you will be able to access it as ${COOKIE_csrftoken} where required.

More information: HTTP Cookie Manager Advanced Usage - A Guide

Body:
The easiest way of extracting a cookie into a JMeter Variable is using HTTP Cookie Manager

Add HTTP Cookie Manager to your Test Plan

Add the next line to user.properties file (lives in "bin" folder of your JMeter installation)

CookieManager.save.cookies=false

Restart JMeter to pick the property up

When the cookie will come from the server you will be able to access it as ${COOKIE_csrftoken} where required.

More information: HTTP Cookie Manager Advanced Usage - A Guide


问:
div is showing twice on click
i have this code:

    function swap(id1, id2, id3, id4) {
    $("#" + id1).fadeOut(500);
    $("#" + id2).fadeOut(500);
    $("#" + id3).fadeOut(500, function () {

        document.getElementById(id1).src = document.getElementById(id2).src;

        document.getElementById(id3).innerHTML = document.getElementById(id4).innerHTML;
    });
    $("#" + id1).fadeIn(500);
    $("#" + id2).fadeIn(500);
    $("#" + id3).fadeIn(500);
    $(document).ready(function () {
        $("html, body").animate({scrollTop: 0}, 600);
    });
       }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

                        <div class="content-overlay" onclick="swap('img0', 'img1', 'desc0', 'desc1')"></div>
                        <img src="https://wallpaperbrowse.com/media/images/eiffel-tower-wallpaper-18.jpg" id="img1" class="newsImage"/>
                        <div class="content-details fadeIn-bottom" onclick="swap('img0', 'img1', 'desc0', 'desc1')">
                            <h3 class="content-title">This is a title</h3>
                            <p class="content-text">This is a short description</p>
                        </div>

     <div class="no-display" id="desc1">
                    <div class="gathering">
                        <span class="gatheringTitle">gathering 2017</span>
                        <div class="gatheringDate">
                            <span class="datee">Tue 7, Dec 2017</span>

                        </div>
                        <div class="gath">
                            <p class="text-justify gatheringText">Lorem ipsum dolor sit amet, consectetur adipiscing
                                elit, sed do eiusmod tempor incididunt ut
                                labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
                                ullamco
                                laboris nisi ut aliquip ex ea commodo cons. ullamco

                                laboris nisi ut aliquip ex ea commodo cons.</p>
                        </div>
                    </div>
                </div>

                        <div class="content-overlay" onclick="swap('img0', 'img1', 'desc0', 'desc1')"></div>
                        <img src="https://wallpaperbrowse.com/media/images/Pattern-1920X1200-Wallpaper-Widescreen_318iyIu.jpg" id="img2" class="newsImage"/>
                        <div class="content-details fadeIn-bottom" onclick="swap('img0', 'img2', 'desc0', 'desc2')">
                            <h3 class="content-title">This is a title</h3>
                            <p class="content-text">This is a short description</p>
                        </div>

              </div>
                        <div class="no-display" id="desc2">
                            <div class="gathering">
                                <span class="gatheringTitle">gathering 2017</span>
                                <div class="gatheringDate">
                                    <span class="datee">Tue 8, Dec 2017</span>

                                </div>
                                <div class="gath">
                                    <p class="text-justify gatheringText">Lorem ipsum dolor sit amet, consectetur
                                        adipiscing
                                        elit, sed do eiusmod tempor incididunt ut
                                        labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                                        exercitation
                                        ullamco
                                        laboris nisi ut aliquip ex ea commodo cons.</p>
                                </div>
                            </div>
                        </div>
            </li></code>```

on click i need to change the image to another image so i did this using javascript also the div that contains the description and this how i did it but still not working

when i click on it the image change but on inspect it shows with div class=""gathering twice with tab-index value i just want to remove it and show it one time... anu idea? thx in advance

答:
When calling swap() you specify

onclick="swap('img0', 'img1', 'desc0', 'desc1')"

you use

'desc0', 'desc1'

while html has

id="desc1" and id="desc2"

Not sure if this is the reason for your issue, but a snippet attached would be great advantage :) Hope this was helpful

Title: div is showing twice on click

Body:
i have this code:

    function swap(id1, id2, id3, id4) {
    $("#" + id1).fadeOut(500);
    $("#" + id2).fadeOut(500);
    $("#" + id3).fadeOut(500, function () {

        document.getElementById(id1).src = document.getElementById(id2).src;

        document.getElementById(id3).innerHTML = document.getElementById(id4).innerHTML;
    });
    $("#" + id1).fadeIn(500);
    $("#" + id2).fadeIn(500);
    $("#" + id3).fadeIn(500);
    $(document).ready(function () {
        $("html, body").animate({scrollTop: 0}, 600);
    });
       }

This is a title

This is a short description

                        gathering 2017

                            Tue 7, Dec 2017

Lorem ipsum dolor sit amet, consectetur adipiscing
                                elit, sed do eiusmod tempor incididunt ut
                                labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
                                ullamco
                                laboris nisi ut aliquip ex ea commodo cons. ullamco

                                laboris nisi ut aliquip ex ea commodo cons.

This is a title

This is a short description

                                gathering 2017

                                    Tue 8, Dec 2017

Lorem ipsum dolor sit amet, consectetur
                                        adipiscing
                                        elit, sed do eiusmod tempor incididunt ut
                                        labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                                        exercitation
                                        ullamco
                                        laboris nisi ut aliquip ex ea commodo cons.

on click i need to change the image to another image so i did this using javascript also the div that contains the description and this how i did it but still not working

when i click on it the image change but on inspect it shows with div class=""gathering twice with tab-index value i just want to remove it and show it one time... anu idea? thx in advance


问:
Is there an efficient way to find out whether a queue item is "before" another one?
For my Java application, I need some method that finds out if item1 is "before" item2 in my Queue Q. Of course, I can just use an iterator and start traversing the list. However, maybe there is another way of finding this out?

For my specific application, I can't use a LinkedList (which provides indexes and makes it easy to determine if one object is before another).

答: LinkedList is such a basic class it hard to imagine something which I could suggest as an alternative. except ArrayList which supports random access and can be much faster for indexed access. ArrayList is not as efficient as queue however.</p>


问:
Add noexcept on otherwise-non-throwing inline functions calling C functions?
I've implemented C++ bindings for some C library. The library API calls can fail, but obviously can't throw anything; and my bindings are, for the purposes of this question, all inline.

Now, the compiler can figure out, for most of my inlined functions/methods, that an exception can't be thrown; for example, suppose I have:

```<code>bool foo() {
    auto result = wrapped_lib_foo();
    return some_constexpr_nothrow_cond(result);
}
</code>```

should I mark such functions/methods with noexcept?

Notes:

Not a dupe of Should I use noexcept for simple functions that obviously cannot throw?, as in that case the compiler doesn't know whether the function can throw or not; for C functions - it does know.

The more general question When should I really use noexcept? has potentially conflicting answers, plus, the accepted answer is from 5 years ago and says "it's too early to say".

答:
even if wrapped_lib_foo is a extern "C" function, the compiler has no way of knowing that somewhere down the stack wrapped_lib_foo never throws unless you tell it explicitly.

Then there is also that fact that marking the function noexcept explicitly informs your audience that the function does not throw.

So yes noexcept is a good idea.

Body:
I've implemented C++ bindings for some C library. The library API calls can fail, but obviously can't throw anything; and my bindings are, for the purposes of this question, all inline.

Now, the compiler can figure out, for most of my inlined functions/methods, that an exception can't be thrown; for example, suppose I have:

bool foo() {
    auto result = wrapped_lib_foo();
    return some_constexpr_nothrow_cond(result);
}

should I mark such functions/methods with noexcept?

Notes:

Not a dupe of Should I use noexcept for simple functions that obviously cannot throw?, as in that case the compiler doesn't know whether the function can throw or not; for C functions - it does know.

The more general question When should I really use noexcept? has potentially conflicting answers, plus, the accepted answer is from 5 years ago and says "it's too early to say".


问:
Passing parameter between 2 angular apps within a cordova app
I have a cordova application which consists of 2 angular apps ("login-app" and "app"), with this structure :

```<code>index.html
login-app
  |-- ...
  |-- index.html
app
  |-- ...
  |-- index.html
</code>```

First, we get to "login-app" which redirects to "app" when the user credentials are right :

```<code>window.location.href = '../app/index.html';
</code>```

Then, for some reason (update the user password for example), I want to go from "app" to "login-app", so I do something like this :

```<code>window.location.href = '../web-login/index.html?pageName=chgPwd';
</code>```

In order to switch to the "login-app" and knowing that I want to change my password, so I can display the right component.
In my browser console I get this :

```<code>Navigated to file:///android_asset/www/web-login/index.html?pageName=chgt-pwd
</code>```

But I don't know how to get this "pageName" parameter in my angular component (in 'login-app'), I've tried this, with the variable 'route' of type 'ActivatedRoute' :

```<code>this.route.queryParams.subscribe(queryParams => {
      console.log('pageName >>> ' + queryParams['pageName']);
});
</code>```

But it is 'undefined'.

In fact, the URL is turned into this : 'file:///android_asset/www/web-login/#/' and I lose the parameter.

Is there a 'clean way' of doing this ? or maybe I have to set a parent global variable ?

Thanks,

答: OK, problem solved by using localStorage</p>

Body:
I have a cordova application which consists of 2 angular apps ("login-app" and "app"), with this structure :

index.html
login-app
  |-- ...
  |-- index.html
app
  |-- ...
  |-- index.html

First, we get to "login-app" which redirects to "app" when the user credentials are right :

window.location.href = '../app/index.html';

Then, for some reason (update the user password for example), I want to go from "app" to "login-app", so I do something like this :

window.location.href = '../web-login/index.html?pageName=chgPwd';

In order to switch to the "login-app" and knowing that I want to change my password, so I can display the right component.
In my browser console I get this :

Navigated to file:///android_asset/www/web-login/index.html?pageName=chgt-pwd

But I don't know how to get this "pageName" parameter in my angular component (in 'login-app'), I've tried this, with the variable 'route' of type 'ActivatedRoute' :

this.route.queryParams.subscribe(queryParams => {
      console.log('pageName >>> ' + queryParams['pageName']);
});

But it is 'undefined'.

In fact, the URL is turned into this : 'file:///android_asset/www/web-login/#/' and I lose the parameter.

Is there a 'clean way' of doing this ? or maybe I have to set a parent global variable ?

Thanks,


问:
Php Mail Going For spam
```<code><?php if (isset ($_POST['submit'])&& ($_POST['submit']!='')){
      $to = 'manojpraharsha@gmail.com';
      $subject = 'Website Enquery Request';
      $email = $_POST['email'];
      $name = $_POST['name'];
      $headers = 'From: Timespaces <'.$to.'>' . "\r\n";
      $headers .= 'Reply-To: '.$name.' <'.$email.'> ' . "\r\n";
      $headers .= 'Return-Path:' .$to . "\r\n";
      $headers .= 'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";
      $message .= '<html><body>';
      $message .= '<table rules="all" style="border-color:rgb(130,0,67);" cellpadding="10">';
      $message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['name']) . "</td></tr>";
      $message .= "<tr><td><strong>Email:</strong> </td><td>" . $email . "</td></tr>";
      $message .= "<tr><td><strong>Phone:</strong> </td><td>" . strip_tags($_POST['phone']) . "</td></tr>";
      $message .= "<tr><td><strong>Subject:</strong> </td><td>" . strip_tags($_POST['subject']) . "</td></tr>";
      $message .= "</table>";
      $message .= "</body></html>";
      mail($to, $subject, $message, $headers);
      }
      ?>
</code>```

<p>is there any mistakes in here where i tried all possibilities but also all mails goes to my spam </p>

答: You can use PHP Mailer with SMTP authentication, or send using dedicated IP  with popular( in active conversation ) sender email ID

Title: Php Mail Going For spam

Body:
<?php if (isset ($_POST['submit'])&& ($_POST['submit']!='')){
      $to = 'manojpraharsha@gmail.com';
      $subject = 'Website Enquery Request';
      $email = $_POST['email'];
      $name = $_POST['name'];
      $headers = 'From: Timespaces <'.$to.'>' . "\r\n";
      $headers .= 'Reply-To: '.$name.' <'.$email.'> ' . "\r\n";
      $headers .= 'Return-Path:' .$to . "\r\n";
      $headers .= 'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";
      $message .= '';
      $message .= '
';
      $message .= "
Name: 	" . strip_tags($_POST['name']) . "
";
      $message .= "
Email: 	" . $email . "
";
      $message .= "
Phone: 	" . strip_tags($_POST['phone']) . "
";
      $message .= "
Subject: 	" . strip_tags($_POST['subject']) . "
";
      $message .= "
";
      $message .= "";
      mail($to, $subject, $message, $headers);
      }
      ?>

is there any mistakes in here where i tried all possibilities but also all mails goes to my spam


问:
Eclipse plugin rt.jar semms not to be in classpath
We've developed a plugin for eclipse (helios) and it works perfectly at the workbench, but when I try to export and deploy it, the follow expcetion is being raised:

```<code>java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at learsoft.system.plugin.handlers.endOracleSession.conect(endOracleSession.java:31)
    at learsoft.system.plugin.handlers.SampleHandler.execute(SampleHandler.java:45)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
    at org.eclipse.ui.internal.handlers.SlaveHandlerService.executeCommand(SlaveHandlerService.java:241)
    at org.eclipse.ui.menus.CommandContributionItem.handleWidgetSelection(CommandContributionItem.java:820)
    at org.eclipse.ui.menus.CommandContributionItem.access$19(CommandContributionItem.java:806)
    at org.eclipse.ui.menus.CommandContributionItem$5.handleEvent(CommandContributionItem.java:796)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3552)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3171)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2629)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2593)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2427)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:670)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:663)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1407)
</code>```

I've setted at the overview tab in plugin configuration to use JavaSE-1.6 and tryed several different configurations.
As far as I know JdbcOjdbcDriver is a class included in rt.jar and seems confusing to me that it is missing.
What am I missing?

Regards,
Fernando

答:
JdbcOdbcDriver is really packaged into rt.jar that must be automatically included into classpath. If it does not exist I believe that your rt.jar in eclipse and in deployment environments are different:

versions are different

vendors are different.

You did not mention how are you deploying your application. I believe that your can compile your application. If you are using the driver directly in your code it is in your classpath when compiling. In this case check what is the difference between compilation and runtime env.

If your are referencing to this driver via dynamic class loading: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") the problem just cannot determined in compile time.

In this case first try to strike Ctrl-Shift-T,  type JDbcOdbcDriver and see whether Eclipse finds something. If yes, see that it is coming from rt.jar and that this is the rt.jar that is used by your JDK configured in Eclipse. Probably you have several JDKs: one of them contains the driver, other does not?

Body:
We've developed a plugin for eclipse (helios) and it works perfectly at the workbench, but when I try to export and deploy it, the follow expcetion is being raised:

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at learsoft.system.plugin.handlers.endOracleSession.conect(endOracleSession.java:31)
    at learsoft.system.plugin.handlers.SampleHandler.execute(SampleHandler.java:45)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
    at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
    at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
    at org.eclipse.ui.internal.handlers.SlaveHandlerService.executeCommand(SlaveHandlerService.java:241)
    at org.eclipse.ui.menus.CommandContributionItem.handleWidgetSelection(CommandContributionItem.java:820)
    at org.eclipse.ui.menus.CommandContributionItem.access$19(CommandContributionItem.java:806)
    at org.eclipse.ui.menus.CommandContributionItem$5.handleEvent(CommandContributionItem.java:796)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1258)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3552)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3171)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2629)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2593)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2427)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:670)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:663)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1407)

I've setted at the overview tab in plugin configuration to use JavaSE-1.6 and tryed several different configurations.
As far as I know JdbcOjdbcDriver is a class included in rt.jar and seems confusing to me that it is missing.
What am I missing?

Regards,
Fernando


问:
How to dock a sidebar created with Firefox WebExtensions?
I've created a sidebar using Firefox WebExtensions, but I'd love to dock the sidebar to the bottom, I did search a lot, and couldn't find anything.

The code I used is this one:

Sidebar.js

```<code>var thisPanel = browser.extension.getURL("/this.html");
var thatPanel = browser.extension.getURL("/that.html");

function toggle(panel) {
  if (panel === thisPanel) {
    browser.sidebarAction.setPanel({panel: thatPanel});
  } else {
    browser.sidebarAction.setPanel({panel: thisPanel});
  }
}

browser.browserAction.onClicked.addListener(() => {
  browser.sidebarAction.getPanel({}).then(toggle);
});
</code>```

答:
Well, it's called a sidebar..

Quoting WebExtension documentation, emphasis mine:

A sidebar is a pane that is displayed at the left-hand side of the browser window, next to the web page.

If you want something docked elsewhere, either you need to inject DOM into the page with content scripts (fragile), or write a devtools.panels extension and dock it within Dev Tools.

Body:
I've created a sidebar using Firefox WebExtensions, but I'd love to dock the sidebar to the bottom, I did search a lot, and couldn't find anything.

The code I used is this one:

Sidebar.js

var thisPanel = browser.extension.getURL("/this.html");
var thatPanel = browser.extension.getURL("/that.html");

function toggle(panel) {
  if (panel === thisPanel) {
    browser.sidebarAction.setPanel({panel: thatPanel});
  } else {
    browser.sidebarAction.setPanel({panel: thisPanel});
  }
}

browser.browserAction.onClicked.addListener(() => {
  browser.sidebarAction.getPanel({}).then(toggle);
});


问:
rest controller not working in spring boot
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

```<code>2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
</code>```

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

```<code>package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}
</code>```

the controller file:

```<code>@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

```<code>@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

it works fine!

答:
There are a couple of things missing here. First, you need to add RequestMapping to the defined function and for returning the JSONObject, you need to use the @ResponseBody Annotation along with ResponseEntity as the return type of the function
Example Code:

```<code>@RequestMapping(value = "/testing", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON)
public @ResponseBody ResponseEntity<JSONObject> HelloWorld() {
    JSONObject res = new JSONObject();
    LOGGER.info("HelloWorld Test!");
    res.put("data", "hello world!");
    res.put("errCode", 0);
    return ResponseEntity.status(HttpStatus.OK).body(res);
}
</code>```

The @RequestMapping Annotation can used on both Function level as well as Class Level. Class Level Annotation value should be prepended to all function @RequestMapping Annotation values in the final REST Endpoint.

Body:
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}

the controller file:

@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

it works fine!

Body:
There are a couple of things missing here. First, you need to add RequestMapping to the defined function and for returning the JSONObject, you need to use the @ResponseBody Annotation along with ResponseEntity as the return type of the function
Example Code:

@RequestMapping(value = "/testing", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON)
public @ResponseBody ResponseEntity<JSONObject> HelloWorld() {
    JSONObject res = new JSONObject();
    LOGGER.info("HelloWorld Test!");
    res.put("data", "hello world!");
    res.put("errCode", 0);
    return ResponseEntity.status(HttpStatus.OK).body(res);
}

The @RequestMapping Annotation can used on both Function level as well as Class Level. Class Level Annotation value should be prepended to all function @RequestMapping Annotation values in the final REST Endpoint.