问:
How to fix Validation error in a JSON string with special chars
I have a following JSON string:

```<code>{
    "my_regex": "(?<somevalue>^(\S*\s*\S*)*$)"
}
</code>```

When I try to validate the format using online tools like jsonlint, I get following error:

Error: Parse error on line 2:

..."object_condition": "(?^(\S*

-----------------------^

Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got >'undefined'

So my question is, what should I do to make it a valid JSON?

答:
You need to escape the \'s:

```<code>{
    "my_regex": "(?<somevalue>^(\\S*\\s*\\S*)*$)"
}
</code>```

jsonlint :

Body:
I have a following JSON string:

{
    "my_regex": "(?<somevalue>^(\S*\s*\S*)*$)"
}

When I try to validate the format using online tools like jsonlint, I get following error:

Error: Parse error on line 2:

..."object_condition": "(?^(\S*

-----------------------^

Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got >'undefined'

So my question is, what should I do to make it a valid JSON?

Body:
You need to escape the \'s:

{
    "my_regex": "(?<somevalue>^(\\S*\\s*\\S*)*$)"
}

jsonlint :


来源: stackexchange

问:
How to prevent background image from scrolling in form field in IE?
The problem is in IE7 and 6 (I have to support 6 at work).

```<code>.myForm input { background: url(../images/input_bg.jpg) no-repeat; }

<form class='myForm'>
     <input type="text" />
     <input type="text" />
     <button>Submit</button>
</form>
</code>```

In IE when you type in the input field, once you reach the end the image stops repeating and text is shown without any background image in the back of the input field. In firefox and other browsers including IE8 the text just scrolls but the image stays in place. Why does it end in IE7 and 6?

P.S. I can't remove no-repeat in the image since it has borders and you can tell it's repeating in a weird way.

答:
Tested in IE6/7/8 / Firefox / Chrome.

Add wrapper div around each input, like this:

```<code><div><input type="text" /></div>
</code>```

Use CSS like this:

```<code>.myForm input { background: transparent }
.myForm div { background: url(../images/input_bg.jpg) no-repeat; display:inline }
.myForm input, .myForm div { width: 150px }
</code>```

It's not fantastic, but it works. A more eloquent way would be to add the wrapper div and modify the styles using JS if the browser is <=IE7.

ContentLicense: CC BY-SA 2.5

Body:
The problem is in IE7 and 6 (I have to support 6 at work).

.myForm input { background: url(../images/input_bg.jpg) no-repeat; }

<form class='myForm'>
     <input type="text" />
     <input type="text" />
     <button>Submit</button>
</form>

In IE when you type in the input field, once you reach the end the image stops repeating and text is shown without any background image in the back of the input field. In firefox and other browsers including IE8 the text just scrolls but the image stays in place. Why does it end in IE7 and 6?

P.S. I can't remove no-repeat in the image since it has borders and you can tell it's repeating in a weird way.

Body:
Tested in IE6/7/8 / Firefox / Chrome.

Add wrapper div around each input, like this:

<div><input type="text" /></div>

Use CSS like this:

.myForm input { background: transparent }
.myForm div { background: url(../images/input_bg.jpg) no-repeat; display:inline }
.myForm input, .myForm div { width: 150px }

It's not fantastic, but it works. A more eloquent way would be to add the wrapper div and modify the styles using JS if the browser is <=IE7.


问:
Web Scraping Table to JSON
I have a task that I think my python skills far slightly short at. I have a oil production data scraped from an open data website and looking to turn this into a json format.

At present with some help I have run through html table tags to build a list of headers and the row data. What I am struggling with is to nest some of this data within one json record.

Right now I either have all the json by row or per header. I have a header and all the column data under it, then the next header with its data going onto the next header (as below).

If possible I would like to have either the headers and the rows data assigned to it as one record, the next would have the headers again but with row 2 data and then onto the next json record with headers and row 3.
The other option will make sense if looking at the table source…. would be to have a record per oil field, this field might have multiple rows for different years/months production values.

If possible I would like to capture all that in on json field record.
Within the json record it would have the multiple year/,month rows should they exist, captured in the one json record.

Essentially it think it needs to make use of a few loops with the rest of the python on distinct html table cells, which I think is achievable just is slightly outside my python capabilities. Hope this makes sense tried to be quite descriptive.

JSON by Row

```<code>[
"\u00c5SGARD",
"2017",
"8",
"0.19441",
"0.81545",
"0.26954",
"0.00000",
"1.27940",
"0.07432",
"43765"
]
</code>```

Per Headers (every data column under these fields)

```<code>[
"Field (Discovery)":[cell1,cell2,cell3,cell4 etc]
"Year":[cell1,cell2,cell3,cell4 etc],
"Month":[cell1,cell2,cell3,cell4 etc],
"Oil - saleable div[mill Sm3]":[cell1,cell2,cell3,cell4 etc],
"Gas - saleable div[bill Sm3]":[cell1,cell2,cell3,cell4 etc],
"NGL - saleable div[mill Sm3]",
"Condensate - saleable div[mill Sm3]",
"Oil equivalents - saleable div[mill Sm3]",
"Water - wellbores div[mill Sm3]",
"NPDID information carrier"
]
</code>```

Desired per record (year:month fields concatenated)

```<code>{
 " Field (Discovery)":"asset1" ,
 " Oil – saleable":
  [
   { "yearmonth":"201701","unit":"mmboe","value":"1234.456"},
   { "yearmonth ":"201702","unit":"mmboe","value":"124.46"}],
 "Gas - saleable":
  [
    {"yearmonth":"201701","unit":" bill Sm3","value":"1234.456"},
    {" yearmonth ":"201702","unit":"mill Sm3","value":"14.456"}],
 "NGL - saleable ":
  [
   {"yearmonth":"201704","unit":"mill Sm3","value":"1.456"},
   {" yearmonth ":"201706","unit":" bill Sm3","value":"14.456"}],
 "Condensate – saleable":
  [
   {"yearmonth":"201701","unit":" mill Sm3","value":"23.60"},
   {"yearmonth ":"201608","unit":"mill Sm3","value":"4.4"}],
  "NPDID information carrier":"43765"
}
</code>```

current python script

```<code>import requests
from bs4 import BeautifulSoup
import json
import boto3
import botocore
from datetime import datetime
from collections import OrderedDict

starttime = datetime.now()

#Agent detail to prevent scraping bot detection
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47
Safari/537.36'

header = {'User-Agent' : user_agent }

# Webpage connection
html = "http://factpages.npd.no/ReportServer?/FactPages/TableView/
field_production_monthly&rs:Command=Render&rc:Toolbar=false
&rc:Parameters=f&Top100=True&IpAddress=108.171.128.174&CultureCode=en"

r=requests.get(html, headers=header)
c=r.content
soup=BeautifulSoup(c,"html.parser")

rows = soup.findAll('td', {
'class': ['a61cl', 'a65cr', 'a69cr', 'a73cr', 'a77cr', 'a81cr',
'a85cr','a89cr', 'a93c', 'a97cr']})

headers = soup.findAll('td', {
'class': ['a20c', 'a24c', 'a28c', 'a32c', 'a36c', 'a40c', 'a44c',
'a48c','a52c', 'a56c']})

headers_list = [item.getText('div') for item in headers]

rows_list=[item.getText('div') for item in rows]

final=[rows_list[item:item+10] for item in range(0,len(rows_list),10)]

row_header={}
 for item in final:
  for indices in range(0,10):
    if headers_list[indices] not in row_header:
        row_header[headers_list[indices]]=[item[indices]]
      else:
        row_header[headers_list[indices]].append(item[indices])

#OrderedDict
result= (json.dumps(row_header, indent=4, sort_keys=True,
ensure_ascii=False))
 with open('data.txt', 'wt') as outfile:

#json dump print
json.dump(result, outfile,indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)

#Time
runtime = datetime.now() - starttime
print(runtime)
</code>```

答:
Without seeing the HTML it is hard to tell but I am guessing parsing your table would be better done like this: python BeautifulSoup parsing table . That way you can be sure the headers and values match up.

I think it would be a disservice to your education to give the answer. So I hope the following helps:

If we have a list of items (rows!) [ ('a', 1 ), {'a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)] and we want to turn them into a list of [ ( 'a': [1, 2, 3] ), ('b': [1, 2, 3] ) ]

then we could just add a dictionary

```<code>d = {}
for v1, v2 in items:
  d.setdefault(v1, []).append(v2)
</code>```

setdefault here is just a shortcut for having a list by default for our list.

After this d.items() will have the values. The next step would then be to incorporate the headers. Perhaps start with one column Oil – saleable only at first and build from there.

ContentLicense: CC BY-SA 3.0

Title: Web Scraping Table to JSON

Body:
I have a task that I think my python skills far slightly short at. I have a oil production data scraped from an open data website and looking to turn this into a json format.

At present with some help I have run through html table tags to build a list of headers and the row data. What I am struggling with is to nest some of this data within one json record.

Right now I either have all the json by row or per header. I have a header and all the column data under it, then the next header with its data going onto the next header (as below).

If possible I would like to have either the headers and the rows data assigned to it as one record, the next would have the headers again but with row 2 data and then onto the next json record with headers and row 3.
The other option will make sense if looking at the table source…. would be to have a record per oil field, this field might have multiple rows for different years/months production values.

If possible I would like to capture all that in on json field record.
Within the json record it would have the multiple year/,month rows should they exist, captured in the one json record.

Essentially it think it needs to make use of a few loops with the rest of the python on distinct html table cells, which I think is achievable just is slightly outside my python capabilities. Hope this makes sense tried to be quite descriptive.

JSON by Row

[
"\u00c5SGARD",
"2017",
"8",
"0.19441",
"0.81545",
"0.26954",
"0.00000",
"1.27940",
"0.07432",
"43765"
]

Per Headers (every data column under these fields)

[
"Field (Discovery)":[cell1,cell2,cell3,cell4 etc]
"Year":[cell1,cell2,cell3,cell4 etc],
"Month":[cell1,cell2,cell3,cell4 etc],
"Oil - saleable div[mill Sm3]":[cell1,cell2,cell3,cell4 etc],
"Gas - saleable div[bill Sm3]":[cell1,cell2,cell3,cell4 etc],
"NGL - saleable div[mill Sm3]",
"Condensate - saleable div[mill Sm3]",
"Oil equivalents - saleable div[mill Sm3]",
"Water - wellbores div[mill Sm3]",
"NPDID information carrier"
]

Desired per record (year:month fields concatenated)

{
 " Field (Discovery)":"asset1" ,
 " Oil – saleable":
  [
   { "yearmonth":"201701","unit":"mmboe","value":"1234.456"},
   { "yearmonth ":"201702","unit":"mmboe","value":"124.46"}],
 "Gas - saleable":
  [
    {"yearmonth":"201701","unit":" bill Sm3","value":"1234.456"},
    {" yearmonth ":"201702","unit":"mill Sm3","value":"14.456"}],
 "NGL - saleable ":
  [
   {"yearmonth":"201704","unit":"mill Sm3","value":"1.456"},
   {" yearmonth ":"201706","unit":" bill Sm3","value":"14.456"}],
 "Condensate – saleable":
  [
   {"yearmonth":"201701","unit":" mill Sm3","value":"23.60"},
   {"yearmonth ":"201608","unit":"mill Sm3","value":"4.4"}],
  "NPDID information carrier":"43765"
}

current python script

import requests
from bs4 import BeautifulSoup
import json
import boto3
import botocore
from datetime import datetime
from collections import OrderedDict

starttime = datetime.now()

#Agent detail to prevent scraping bot detection
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47
Safari/537.36'

header = {'User-Agent' : user_agent }

# Webpage connection
html = "http://factpages.npd.no/ReportServer?/FactPages/TableView/
field_production_monthly&rs:Command=Render&rc:Toolbar=false
&rc:Parameters=f&Top100=True&IpAddress=108.171.128.174&CultureCode=en"

r=requests.get(html, headers=header)
c=r.content
soup=BeautifulSoup(c,"html.parser")

rows = soup.findAll('td', {
'class': ['a61cl', 'a65cr', 'a69cr', 'a73cr', 'a77cr', 'a81cr',
'a85cr','a89cr', 'a93c', 'a97cr']})

headers = soup.findAll('td', {
'class': ['a20c', 'a24c', 'a28c', 'a32c', 'a36c', 'a40c', 'a44c',
'a48c','a52c', 'a56c']})

headers_list = [item.getText('div') for item in headers]

rows_list=[item.getText('div') for item in rows]

final=[rows_list[item:item+10] for item in range(0,len(rows_list),10)]

row_header={}
 for item in final:
  for indices in range(0,10):
    if headers_list[indices] not in row_header:
        row_header[headers_list[indices]]=[item[indices]]
      else:
        row_header[headers_list[indices]].append(item[indices])

#OrderedDict
result= (json.dumps(row_header, indent=4, sort_keys=True,
ensure_ascii=False))
 with open('data.txt', 'wt') as outfile:

#json dump print
json.dump(result, outfile,indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)

#Time
runtime = datetime.now() - starttime
print(runtime)

Body:
Without seeing the HTML it is hard to tell but I am guessing parsing your table would be better done like this: python BeautifulSoup parsing table . That way you can be sure the headers and values match up.

I think it would be a disservice to your education to give the answer. So I hope the following helps:

If we have a list of items (rows!) [ ('a', 1 ), {'a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)] and we want to turn them into a list of [ ( 'a': [1, 2, 3] ), ('b': [1, 2, 3] ) ]

then we could just add a dictionary

d = {}
for v1, v2 in items:
  d.setdefault(v1, []).append(v2)

setdefault here is just a shortcut for having a list by default for our list.

After this d.items() will have the values. The next step would then be to incorporate the headers. Perhaps start with one column Oil – saleable only at first and build from there.


问:
How do I exit this function?
Essentially its built like so:

```<code>.If

..other stuff

.Else

..For

...For

....If (this is where I need to be able to break out of the whole thing)
</code>```

I've tried using return, and break, but they just are not working for whatever reason. I added in a ticker and it appears that the break command isn't working?

The code just continues going on and repeating the for loop even AFTER it is 'broken' in the If statement.

My function is only about 150 lines long, so I've been able to study it closely, and this seems to be where the problem is.

答:
If you have

```<code>for (...)
    for (...)
        if (true)
            break;
    end
end
</code>```

you'll only break out of the inner loop. But, of course, the outer loop will continue as normal!

Breaking out of nested-loops is one of the very few reasonable use cases for a goto. However, MATLAB does not have a goto, so you'll have to repeat yourself in some way or another:

```<code>for (...)

    for (...)
        if (condition)
            break;
    end

    if (condition)
        break;

end
</code>```

An equally ugly yet common and less verbose way:

```<code>try

    for (...)

        for (...)
            if (condition)
                error(' ');
        end
    end

catch %#ok

    (code you want to be executed after the nested loop)

end
</code>```

or, to be pedantic,

```<code>breakout_ID = 'fcn:breakout_condition';

try

    for (...)

        for (...)
            if (condition)
                error(breakout_ID, ' ');
        end
    end

catch ME

    % graceful breakout
    if strcmp(ME.Identifier, breakout_ID)
        (code you want to be executed after the nested loop)

    % something else went wrong; throw that error
    else
        rethrow(ME);
    end

end
</code>```

Or you build a (nested) function containing just that nested loop, and use return to break out. But that may not always give the most "obvious" code structure, as well as cause you to have to write lots of boilerplate code (subfunction) and/or have unforeseen side effects (nested functions), so...

Personally, I favor the try/catch above.

Title: How do I exit this function?

Body:
Essentially its built like so:

.If

..other stuff

.Else

..For

...For

....If (this is where I need to be able to break out of the whole thing)

I've tried using return, and break, but they just are not working for whatever reason. I added in a ticker and it appears that the break command isn't working?

The code just continues going on and repeating the for loop even AFTER it is 'broken' in the If statement.

My function is only about 150 lines long, so I've been able to study it closely, and this seems to be where the problem is.

Body:
If you have

for (...)
    for (...)
        if (true)
            break;
    end
end

you'll only break out of the inner loop. But, of course, the outer loop will continue as normal!

Breaking out of nested-loops is one of the very few reasonable use cases for a goto. However, MATLAB does not have a goto, so you'll have to repeat yourself in some way or another:

for (...)

    for (...)
        if (condition)
            break;
    end

    if (condition)
        break;

end

An equally ugly yet common and less verbose way:

try

    for (...)

        for (...)
            if (condition)
                error(' ');
        end
    end

catch %#ok

    (code you want to be executed after the nested loop)

end

or, to be pedantic,

breakout_ID = 'fcn:breakout_condition';

try

    for (...)

        for (...)
            if (condition)
                error(breakout_ID, ' ');
        end
    end

catch ME

    % graceful breakout
    if strcmp(ME.Identifier, breakout_ID)
        (code you want to be executed after the nested loop)

    % something else went wrong; throw that error
    else
        rethrow(ME);
    end

end

Or you build a (nested) function containing just that nested loop, and use return to break out. But that may not always give the most "obvious" code structure, as well as cause you to have to write lots of boilerplate code (subfunction) and/or have unforeseen side effects (nested functions), so...

Personally, I favor the try/catch above.


问:
VIM - Add a space before left parens if a space doesn't exist before
What would the quickest way for me to insert a single space before a left parentheses if there is not one there yet?

Examples:

```<code>hello() -> hello ()
world () -> world ()
hello(world ()) -> hello (world ())
</code>```

It's required for a style guide, I'm supposed to follow for class, and I just don't do it automatically, so how can I have vim do this for me.

答:
How about a mapping:

```<code>function! SpaceBeforeLeftParen()
    :silent! s/\v \(/(/g
    :silent! s/\v\(/ (/g
endfunction
nnoremap c( :call SpaceBeforeLeftParen()<CR>
</code>```

Just hit c( on a line where you want the space to be added. Or you can directly call the function: :call SpaceBeforeLeftParen()

--

Some other approaches for the substitution:

s/\(\s\+\)\@<!(/ (/

s/\v([^ ])(\()/\1 (/g

--

Possibly the best complete answer, derived from @Marth's comment would be:

```<code>function! SpaceBeforeLeftParen()
  :silent! %s/\(\s\+\)\@<!(/ (/
endfunction
</code>```

...which will handle the whole file in one shot. Invoke with :call SpaceBeforeLeftParen()

Body:
What would the quickest way for me to insert a single space before a left parentheses if there is not one there yet?

Examples:

hello() -> hello ()
world () -> world ()
hello(world ()) -> hello (world ())

It's required for a style guide, I'm supposed to follow for class, and I just don't do it automatically, so how can I have vim do this for me.

Body:
How about a mapping:

function! SpaceBeforeLeftParen()
    :silent! s/\v \(/(/g
    :silent! s/\v\(/ (/g
endfunction
nnoremap c( :call SpaceBeforeLeftParen()<CR>

Just hit c( on a line where you want the space to be added. Or you can directly call the function: :call SpaceBeforeLeftParen()

--

Some other approaches for the substitution:

s/\(\s\+\)\@<!(/ (/

s/\v([^ ])(\()/\1 (/g

--

Possibly the best complete answer, derived from @Marth's comment would be:

function! SpaceBeforeLeftParen()
  :silent! %s/\(\s\+\)\@<!(/ (/
endfunction

...which will handle the whole file in one shot. Invoke with :call SpaceBeforeLeftParen()


问:
JSP - How to write a valid search form
I have a problem with a search form in a JSP project. In particular an user can subscribe to an event and the admin must be able to search all the members of that event.

I write a form like this:

```<code>out.println("<fieldset><legend>Search</legend><form action=\"cercaIscritti.jsp\" method=\"post\">"
            + "Name: <input name=\"name\" type=\"text\"><br>Surname: <input name=\"surname\" type=\"text\"><br>"
            + "Belonging: <input name=\"belonging\" type=\"text\"><br>Countr: <input name=\"country\" type=\"text\"><br>"
            + "<input type=\"submit\" value=\"Cerca\"></fieldset></form>");
</code>```

(If it isn't readable: there are four <input>, one for each column in the table user and a <input> for submit).

I would like all the fields to be optional so that the admin can fill what it wants, but how do I build the query?

I tried something like this :

```<code>public ResultSet searchSubs(String name, String surname, String belonging, String country) {
    try {
        boolean n = false, s = false, b = false, c = false;
        String query = "SELECT * FROM user WHERE ";
        if (!isEmpty(name)) {
            query += "firstName = ?";
            n = true;
        }
        if (!isEmpty(surname)) {
            if (n) {
                query += " AND lastName = ?";
            } else {
                query += "lastName = ?";
            }
            s = true;
        }
        if (!isEmpty(belonging)) {
            if (n || s) {
                query += " AND belonging = ?";
            } else {
                query += "belonging = ?";
            }
            b = true;
        }//and go on
</code>```

But how can I add the values with the PreparedStatement? Is this the correct way? If it's not, how can I do something like that?

The booleans are there in the middle only for test, I thought I would use them in some way but I do not know how.

答:
Here is a way you can follow to search with multiples values :

```<code>public ResultSet searchSubs(String name, String surname, String belonging, String country){
    try {
        String query = "SELECT * FROM user WHERE 1=1";
        //---------------------------------------^^^
        int index = 1;
        if (!name.isEmpty()) {
            query += " AND firstName = ?";
        }
        if (!surname.isEmpty()) {
            query += " AND surname = ?";
        }
        if (!belonging.isEmpty()) {
            query += " AND belonging = ?";
        }

        if (!country.isEmpty()) {
            query += " AND country = ?";
        }

        PreparedStatement ps = connection.prepareStatement(query);

        if (!name.isEmpty()) {
            ps.setString(index++, name);
        }
        if (!surname.isEmpty()) {
            ps.setString(index++, surname);
        }
        if (!belonging.isEmpty()) {
            ps.setString(index++, belonging);
        }
        if (!country.isEmpty()) {
            ps.setString(index++, country);
        }

        ResultSet rs = ps.executeQuery();
        //...
</code>```

The idea is simple :

In the Where clause use 1=1 to not get an error if the user not enter any value(in this case your query is SELECT * FROM user WHERE 1=1 and it will return every thing)

The first part if to fill the query with the non empty fields

The second if to fill the prepared statement with the right values.

finally execute the prepared statement and get the results.

Title: JSP - How to write a valid search form

Body:
I have a problem with a search form in a JSP project. In particular an user can subscribe to an event and the admin must be able to search all the members of that event.

I write a form like this:

out.println("<fieldset><legend>Search</legend><form action=\"cercaIscritti.jsp\" method=\"post\">"
            + "Name: <input name=\"name\" type=\"text\">
Surname: <input name=\"surname\" type=\"text\">
"
            + "Belonging: <input name=\"belonging\" type=\"text\">
Countr: <input name=\"country\" type=\"text\">
"
            + "<input type=\"submit\" value=\"Cerca\"></fieldset></form>");

(If it isn't readable: there are four <input>, one for each column in the table user and a <input> for submit).

I would like all the fields to be optional so that the admin can fill what it wants, but how do I build the query?

I tried something like this :

public ResultSet searchSubs(String name, String surname, String belonging, String country) {
    try {
        boolean n = false, s = false, b = false, c = false;
        String query = "SELECT * FROM user WHERE ";
        if (!isEmpty(name)) {
            query += "firstName = ?";
            n = true;
        }
        if (!isEmpty(surname)) {
            if (n) {
                query += " AND lastName = ?";
            } else {
                query += "lastName = ?";
            }
            s = true;
        }
        if (!isEmpty(belonging)) {
            if (n || s) {
                query += " AND belonging = ?";
            } else {
                query += "belonging = ?";
            }
            b = true;
        }//and go on

But how can I add the values with the PreparedStatement? Is this the correct way? If it's not, how can I do something like that?

The booleans are there in the middle only for test, I thought I would use them in some way but I do not know how.

Body:
Here is a way you can follow to search with multiples values :

public ResultSet searchSubs(String name, String surname, String belonging, String country){
    try {
        String query = "SELECT * FROM user WHERE 1=1";
        //---------------------------------------^^^
        int index = 1;
        if (!name.isEmpty()) {
            query += " AND firstName = ?";
        }
        if (!surname.isEmpty()) {
            query += " AND surname = ?";
        }
        if (!belonging.isEmpty()) {
            query += " AND belonging = ?";
        }

        if (!country.isEmpty()) {
            query += " AND country = ?";
        }

        PreparedStatement ps = connection.prepareStatement(query);

        if (!name.isEmpty()) {
            ps.setString(index++, name);
        }
        if (!surname.isEmpty()) {
            ps.setString(index++, surname);
        }
        if (!belonging.isEmpty()) {
            ps.setString(index++, belonging);
        }
        if (!country.isEmpty()) {
            ps.setString(index++, country);
        }

        ResultSet rs = ps.executeQuery();
        //...

The idea is simple :

In the Where clause use 1=1 to not get an error if the user not enter any value(in this case your query is SELECT * FROM user WHERE 1=1 and it will return every thing)

The first part if to fill the query with the non empty fields

The second if to fill the prepared statement with the right values.

finally execute the prepared statement and get the results.


问:
Marklogic 9.0-3 REST Parameters accessing in REST extensions
I have a REST extension and I have beeing accessing the parameters that have been passed, both in GET and POST as follows.. The parameters are passed as form-data or x-www-form-urlencoded. In my REST extension I would access the parameters via xdmp:get-request-field("remoteURL").

In ML-8, this worked where in when calling the WS I would pass in the parameters as remoteURL and it worked..

Now in ML-9.0-3, it does not work, so I tried passing the parameters via rs:remoteURL and access in the REST extension as xdmp:get-request-field("remoteURL") and it fails, but when I access as xdmp:get-request-field("rs:remoteURL"). it works.. Did this got changed in ML-9.0-3 ?

Just for complete I am including my REST extension code as well

```<code>declare function repoTest:post($context as map:map, $params  as map:map,$input   as document-node()*) as document-node()*
{
  let $_ := xdmp:log("Inside the Repo Test POST")
  let $remoteURL :=xdmp:get-request-field("remoteURL")
  let $_ := xdmp:log($remoteURL)
  let $output := json:object()
  let $_ :=  map:put($output, "remoteURL", $remoteURL)
  return document { xdmp:to-json($output) }
};
</code>```

答:
I am not aware of a change in this, though it could be very well possible. I'd recommend accessing parameters via the $params map:map, which is the recommended way for REST extensions anyhow. $params will always contains any rs: request parameters without the rs: prefix.

HTH!

Body:
I have a REST extension and I have beeing accessing the parameters that have been passed, both in GET and POST as follows.. The parameters are passed as form-data or x-www-form-urlencoded. In my REST extension I would access the parameters via xdmp:get-request-field("remoteURL").

In ML-8, this worked where in when calling the WS I would pass in the parameters as remoteURL and it worked..

Now in ML-9.0-3, it does not work, so I tried passing the parameters via rs:remoteURL and access in the REST extension as xdmp:get-request-field("remoteURL") and it fails, but when I access as xdmp:get-request-field("rs:remoteURL"). it works.. Did this got changed in ML-9.0-3 ?

Just for complete I am including my REST extension code as well

declare function repoTest:post($context as map:map, $params  as map:map,$input   as document-node()*) as document-node()*
{
  let $_ := xdmp:log("Inside the Repo Test POST")
  let $remoteURL :=xdmp:get-request-field("remoteURL")
  let $_ := xdmp:log($remoteURL)
  let $output := json:object()
  let $_ :=  map:put($output, "remoteURL", $remoteURL)
  return document { xdmp:to-json($output) }
};


问:
SQL Server Backup to Azure Storage Issues
We are currently backing up SQL Server databases to an Azure URL as a page blob.  SQL Server version is 2012 SP3.  At times I need to get the backups to our Dev, Beta, and Test environments to be restored.  I'm having an issue with a large backup (~50 GB).  There are several smaller backups that are copied and restored okay but the one large backup is the problem.  I've tried using PowerShell scripts and AzCopy.  When attempting to restore it using the GUI, the backup is not recognized.  When attempting to RESTORE VERIFYONLY, I get the error - Msg 3013 (VERIFY DATABASE is terminating abnormally.)

If I do a restore verify from URL, the backup is valid.  If I try to restore from URL, it restores but takes forever (almost 6 hours).

Has anybody else had this problem?

答:
The problem is that the backup is not being completely copied because the AzCopy program is interrupted.
After doing a little research, I discovered there are many options to AzCopy.  One of them is the capability to resume the copy if it is interrupted.  This is handled through a PowerShell script.
AzCopy has great help - AzCopy.exe /?.   </p>


问:
R only specify optional parameters if specified
I have an R function with optional parameters like so:

```<code>myFunc <- function(
    requiredParam,
    optionalParam1 = optionalValue1,
    optionalParam2 = optionalValue2,
    ...
    optionalParamN = optionalValueN) {
    # implementation
}
</code>```

I have another function which calls this function and has the necessary parameters stored in a dataframe:

```<code>  optionalParam1 optionalParam3 optionalParam10
1         "val1"         "val2"          "val3"
</code>```

I only want to pass the optional parameters specified in the dataframe. For the others, I want it to use the default values. How can I accomplish this without typing up all permutations of optionalParameters existing/not existing?

答:
You can also build your function call as a string by parsing your dataframe column names and using paste.

Then, use eval(parse(text="your string"))

Body:
I have an R function with optional parameters like so:

myFunc <- function(
    requiredParam,
    optionalParam1 = optionalValue1,
    optionalParam2 = optionalValue2,
    ...
    optionalParamN = optionalValueN) {
    # implementation
}

I have another function which calls this function and has the necessary parameters stored in a dataframe:

  optionalParam1 optionalParam3 optionalParam10
1         "val1"         "val2"          "val3"

I only want to pass the optional parameters specified in the dataframe. For the others, I want it to use the default values. How can I accomplish this without typing up all permutations of optionalParameters existing/not existing?


问:
Add
 every 2 images from mysql in a variable
I'm trying to make this code insert a line break after 2 images when there are a total of 4 images. The Code listed below adds the line break after all images are displayed instead of after 2 images. Could someone please help me with this?

```<code>$images = "";
$i = 0;
while ($info = mysqli_fetch_array($imglist)) {
  $style = $info['Style'];
  $imgpath = $info['ImgPath'];
  $standardimg = $info['StandardImg'];
  $colorname = $info['ColorName'];
  $smallimgwidth = $info['SmallImgWidth'];

  $images = $images.
  "<img src='$imgpath/$standardimg-Small.jpg'
  alt = '$mill $style - $colorname'
  title = '$mill $style - $colorname'
  style = 'min-width:35px; max-width:$smallimgwidthpx;' / > ";

  if (mysqli_num_rows($imglist) == 4) {
    if ($i != 0 && $i % 2 == 1) {
      echo '<br />';
    }
  }
  $i++;
}
</code>```

答:
Change

```<code>echo '<br />';
</code>```

to

```<code>$images = $images . '<br />';
</code>```

Just like that.

I little explanation: you're not 'grouping' br output with image output, since one goes into a variable (image) and the other is displayed immediately (br).

Title: Add <br /> every 2 images from mysql in a variable

Body:
I'm trying to make this code insert a line break after 2 images when there are a total of 4 images. The Code listed below adds the line break after all images are displayed instead of after 2 images. Could someone please help me with this?

$images = "";
$i = 0;
while ($info = mysqli_fetch_array($imglist)) {
  $style = $info['Style'];
  $imgpath = $info['ImgPath'];
  $standardimg = $info['StandardImg'];
  $colorname = $info['ColorName'];
  $smallimgwidth = $info['SmallImgWidth'];

  $images = $images.
  " ";

  if (mysqli_num_rows($imglist) == 4) {
    if ($i != 0 && $i % 2 == 1) {
      echo '
';
    }
  }
  $i++;
}

Body:
Change

echo '<br />';

to

$images = $images . '<br />';

Just like that.

I little explanation: you're not 'grouping' br output with image output, since one goes into a variable (image) and the other is displayed immediately (br).


问:
Git Push restored code to old commit but didn't push any of changes made
So I am using Github very infrequently because I am the only one working on a project. After about two weeks, I decided I should probably push some code to Github. When I pushed the code, it set the files I am working on back to where they were two weeks ago (I am using Xcode and it basically erased everything from the last two weeks) and didn't push any of the changes to Github.

How can I undo this?

Thanks

答:
I could be wrong.  But if you were on a separate branch and pushed and committed those changes you worked on the last two weeks.  Then switch to master and pushed you might want to switch back to your older branch and reload your project to get those new changes.

If you want your master to reflect these changes you are going to need to merge the two branches


问:
How to create a column on a SQL table, based on values of another table
I currently have 2 SQL tables:  table1 and table2. table1 has 2 columns called id_a and column_a. table2 has 2 columns called id_b and column_b.

I would like to create a new_column in table1. The value of new_column should be 1 if the value of table1.id_a exists in table2.id_b. Otherwise, new_column should have the value of 0.

How do I do this? I'm using SQLite3 and table1 is significantly larger than table2.

答:
How about a simple exists?

```<code>select t1.*,
       (case when exists (select 1 from table2 t2 where t2.id_b = t1.id_a)
             then 1 else 0
        end) as flag
from table1 t1
</code>```

Body:
How about a simple exists?

select t1.*,
       (case when exists (select 1 from table2 t2 where t2.id_b = t1.id_a)
             then 1 else 0
        end) as flag
from table1 t1


问:
Excel Search Date formats
I am using Excels 2013 mid and search function to get the date from a comment column but I don't know how to do this to cover the 8 date formats(dd/mm/yyyy, dd/mm/yy and so on). Three of my formulas are below although I would need to join them all together to capture all the date formats.The comment column can be any text with a date anywhere within it.

```<code>=MID(A6, SEARCH("??/??/????", A6, 1), 10)
=MID(A7, SEARCH("?/??/????", A7, 1), 9)
=MID(A8, SEARCH("??/?/????", A8, 1), 9)
</code>```

There must be a better way of doing this as the only way I can think of is to put each formula on a separate column and then use an if statement to show the date.
Any help would be much appreciative. thanks

Sample Column data

```<code>Paid on 01/01/2017
Paid on 1/01/2017, Reference AAA123
Reference BBB456 Paid on  01/1/2017
</code>```

答:
This is what Regular Expressions are used for.

Here's a function that implements Regular Expressions as referenced here:  How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

(Note that you have to add the "Microsoft VBScript Regular Expressions 5.5" reference, as mentioned in the link)

```<code>Function showDate(thisVal As String)

    Dim strPattern As String
    Dim regEx As New RegExp

    strPattern = "[0-9]?[0-9]/[0-9]?[0-9]/[0-9]?[0-9]?[0-9][0-9]"

    If strPattern <> "" Then

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        Set objMatches = regEx.Execute(thisVal)
        For Each Match In objMatches             'The variable match will contain the full match
            showDate = Match
        Next

    End If

End Function
</code>```

Use it like: =showDate(A1)

the bit of code:

```<code>    strPattern = "[0-9]?[0-9]/[0-9]?[0-9]/[0-9]?[0-9]?[0-9][0-9]"
</code>```

Controls what patterns will be looked for.  The ? after each [0-9] range denotes an "optional" character, so the leading zero or one in the month can be accepted if present, but the lack of it won't cause the match/find to miss.

Do note that this solution provides the last instance of a date from a string.  If you only have one instance of a date it's fine but multiple dates per string is a consideration you have to scope for.

Title: Excel Search Date formats

Body:
I am using Excels 2013 mid and search function to get the date from a comment column but I don't know how to do this to cover the 8 date formats(dd/mm/yyyy, dd/mm/yy and so on). Three of my formulas are below although I would need to join them all together to capture all the date formats.The comment column can be any text with a date anywhere within it.

=MID(A6, SEARCH("??/??/????", A6, 1), 10)
=MID(A7, SEARCH("?/??/????", A7, 1), 9)
=MID(A8, SEARCH("??/?/????", A8, 1), 9)

There must be a better way of doing this as the only way I can think of is to put each formula on a separate column and then use an if statement to show the date.
Any help would be much appreciative. thanks

Sample Column data

Paid on 01/01/2017
Paid on 1/01/2017, Reference AAA123
Reference BBB456 Paid on  01/1/2017

Body:
This is what Regular Expressions are used for.

Here's a function that implements Regular Expressions as referenced here:  How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

(Note that you have to add the "Microsoft VBScript Regular Expressions 5.5" reference, as mentioned in the link)

Function showDate(thisVal As String)

    Dim strPattern As String
    Dim regEx As New RegExp

    strPattern = "[0-9]?[0-9]/[0-9]?[0-9]/[0-9]?[0-9]?[0-9][0-9]"

    If strPattern <> "" Then

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        Set objMatches = regEx.Execute(thisVal)
        For Each Match In objMatches             'The variable match will contain the full match
            showDate = Match
        Next

    End If

End Function

Use it like: =showDate(A1)

the bit of code:

    strPattern = "[0-9]?[0-9]/[0-9]?[0-9]/[0-9]?[0-9]?[0-9][0-9]"

Controls what patterns will be looked for.  The ? after each [0-9] range denotes an "optional" character, so the leading zero or one in the month can be accepted if present, but the lack of it won't cause the match/find to miss.

Do note that this solution provides the last instance of a date from a string.  If you only have one instance of a date it's fine but multiple dates per string is a consideration you have to scope for.


问:
Simplify/RESTify my routes!
Here is a sample of my routes.rb
Basically I have users that have pictures and that can rate other people's pictures

This is not very RESTful at all, but I cannot figure out how to turn this around?

```<code>  resources :users do
    member do
      post :reset_password
    end
  end
  # to list images
  get 'images/list/:order/:page/:per_page/:category', :to => 'images#list_filtered'
  # to rate images
  post 'images/rate', :to => 'images#rate'
  # to list a user's images
  get 'images/user/:user_id/:category/:order/:page/:per_page', :to => "images#user"
  # to list users that rated an image
  get 'users/rated/:image_id', :to => 'users#rated'
</code>```

答:
Why don't you treat images and ratings as resources? Nest images under their users and add a Rating model that belongs to an image and a user (the user giving the rating, not the owner of the rated image)

```<code>resources :users do
  resources :images do
    resources :ratings, :only => [:create, :destroy]
  end
  post :reset_password, :on => :member
end
</code>```

then you can set up your cotroller like this

```<code># ratings_controller.rb
class RatingsController < ApplicationController
  before_filter :find_image

  # POST /users/26/images/351/ratings
  def create
    @image.ratings.create(params[:rating])
    redirect_to image_path(@image), :notice => "You just rated this image"
  end

  # DELETE /users/26/images/351/ratings/35477
  def destroy
    @image.ratings.find(params[:id]).destroy!
    redirect_to image_path(@image), :notice => "Deleted rating"
  end

  private

  def find_image
    @image = Image.where(:user_id => params[:user_id], :id => params[:image_id])
  end
end
</code>```

Title: Simplify/RESTify my routes!

Body:
Here is a sample of my routes.rb
Basically I have users that have pictures and that can rate other people's pictures

This is not very RESTful at all, but I cannot figure out how to turn this around?

  resources :users do
    member do
      post :reset_password
    end
  end
  # to list images
  get 'images/list/:order/:page/:per_page/:category', :to => 'images#list_filtered'
  # to rate images
  post 'images/rate', :to => 'images#rate'
  # to list a user's images
  get 'images/user/:user_id/:category/:order/:page/:per_page', :to => "images#user"
  # to list users that rated an image
  get 'users/rated/:image_id', :to => 'users#rated'

Body:
Why don't you treat images and ratings as resources? Nest images under their users and add a Rating model that belongs to an image and a user (the user giving the rating, not the owner of the rated image)

resources :users do
  resources :images do
    resources :ratings, :only => [:create, :destroy]
  end
  post :reset_password, :on => :member
end

then you can set up your cotroller like this

# ratings_controller.rb
class RatingsController < ApplicationController
  before_filter :find_image

  # POST /users/26/images/351/ratings
  def create
    @image.ratings.create(params[:rating])
    redirect_to image_path(@image), :notice => "You just rated this image"
  end

  # DELETE /users/26/images/351/ratings/35477
  def destroy
    @image.ratings.find(params[:id]).destroy!
    redirect_to image_path(@image), :notice => "Deleted rating"
  end

  private

  def find_image
    @image = Image.where(:user_id => params[:user_id], :id => params[:image_id])
  end
end


问:
Celery and Rabbit MQ Django
I installed Celery and RabbitMQ with the commands:
pip install celery and sudo apt-get install rabbitmq.
Celery doesn't work; I get this error:

```<code>Traceback (most recent call last):
  File "/home/morilon/dj/shop/lib/python3.5/site-
packages/celery/app/utils.py", line 361, in find_app
    found = sym.app
AttributeError: module 'myshop' has no attribute 'app'
</code>```

During handling of the above exception, another exception occurred:

```<code>Traceback (most recent call last):
  File "/home/morilon/dj/shop/bin/celery", line 11, in <module>
    sys.exit(main())
 File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/__main__.py", line 14, in main
    _main()
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 326, in main
    cmd.execute_from_commandline(argv)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 279, in execute_from_commandline
    argv = self.setup_app_from_commandline(argv)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 481, in setup_app_from_commandline
    self.app = self.find_app(app)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 503, in find_app
    return find_app(app, symbol_by_name=self.symbol_by_name)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/app/utils.py", line 366, in find_app
    found = sym.celery
AttributeError: module 'myshop' has no attribute 'celery'
</code>```

I don't understand what to do with this?

tasks.py

```<code>from celery import task
from django.core.mail import send_mail
from .models import Order

@task
def order_created(order_id):
    """
    Task to send an e-mail notification when an order is successfully created.
    """
    order = Order.objects.get(id=order_id)
    subject = 'Order nr. {}'.format(order.id)
    message = 'Dear {},\n\nYou have successfully placed an order. Your order id is {}.'.format(order.first_name,
                                                                             order.id)
    mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email])
    return mail_sent
</code>```

celery.py

```<code>import os
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings')

app = Celery('myshop')

app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
</code>```

init.py

from .celery import app as celery_app

This project on GitHub https://github.com/Loctarogar/Django-by-Example

答:
Try to double check spelling for file celery.py on your project directory where settings.py is located

Or you can follow THIS documentation for using celery with Django for more explanations

You can also check this post!

Title: Celery and Rabbit MQ Django

Body:
I installed Celery and RabbitMQ with the commands:
pip install celery and sudo apt-get install rabbitmq.
Celery doesn't work; I get this error:

Traceback (most recent call last):
  File "/home/morilon/dj/shop/lib/python3.5/site-
packages/celery/app/utils.py", line 361, in find_app
    found = sym.app
AttributeError: module 'myshop' has no attribute 'app'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/morilon/dj/shop/bin/celery", line 11, in <module>
    sys.exit(main())
 File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/__main__.py", line 14, in main
    _main()
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 326, in main
    cmd.execute_from_commandline(argv)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 279, in execute_from_commandline
    argv = self.setup_app_from_commandline(argv)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 481, in setup_app_from_commandline
    self.app = self.find_app(app)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 503, in find_app
    return find_app(app, symbol_by_name=self.symbol_by_name)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/app/utils.py", line 366, in find_app
    found = sym.celery
AttributeError: module 'myshop' has no attribute 'celery'

I don't understand what to do with this?

tasks.py

from celery import task
from django.core.mail import send_mail
from .models import Order

@task
def order_created(order_id):
    """
    Task to send an e-mail notification when an order is successfully created.
    """
    order = Order.objects.get(id=order_id)
    subject = 'Order nr. {}'.format(order.id)
    message = 'Dear {},\n\nYou have successfully placed an order. Your order id is {}.'.format(order.first_name,
                                                                             order.id)
    mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email])
    return mail_sent

celery.py

import os
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings')

app = Celery('myshop')

app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

init.py

from .celery import app as celery_app

This project on GitHub https://github.com/Loctarogar/Django-by-Example


问:
ansible: getting values out of dictsort
I have the following dictionary:

```<code>bigip_provider:
  bigip1: "10.0.0.16"
  bigip2: "10.0.0.18"
  bigip3: "10.0.0.17"
  bigip4: "10.0.0.19"
  bigip5: "10.0.0.27"
  bigip6: "10.0.0.23"
  bigip7: "10.0.0.25"
  bigip8: "10.0.0.28"
</code>```

And I wanted to get the values converting them into a string:

```<code>{{ bigip_provider.values() | list | join('/24 ') +'/24' }}
</code>```

but with the values sorted by the key: ie {{ bigip_provider | dictsort ... }

I've tried to extract only the values output by dictsort with  map and selectattr but I haven't found a way of doing this.

Many thanks

答:
As you can access list elements with dot-notation (like mylist.1), so you can use map(attribute='1') to reduce lists (kind of hack, but it's ok):

```<code>- hosts: localhost
  gather_facts: no
  vars:
    bigip_provider:
      bigip9: "10.0.0.16"
      bigip2: "10.0.0.18"
      bigip3: "10.0.0.17"
  tasks:
    - debug:
        msg: "{{ bigip_provider | dictsort | map(attribute='1') | map('regex_replace','$','/24') | list }}"
</code>```

Result:

```<code>ok: [localhost] => {
    "msg": [
        "10.0.0.18/24",
        "10.0.0.17/24",
        "10.0.0.16/24"
    ]
}
</code>```

Title: ansible: getting values out of dictsort

Body:
I have the following dictionary:

bigip_provider:
  bigip1: "10.0.0.16"
  bigip2: "10.0.0.18"
  bigip3: "10.0.0.17"
  bigip4: "10.0.0.19"
  bigip5: "10.0.0.27"
  bigip6: "10.0.0.23"
  bigip7: "10.0.0.25"
  bigip8: "10.0.0.28"

And I wanted to get the values converting them into a string:

{{ bigip_provider.values() | list | join('/24 ') +'/24' }}

but with the values sorted by the key: ie {{ bigip_provider | dictsort ... }

I've tried to extract only the values output by dictsort with  map and selectattr but I haven't found a way of doing this.

Many thanks

Body:
As you can access list elements with dot-notation (like mylist.1), so you can use map(attribute='1') to reduce lists (kind of hack, but it's ok):

- hosts: localhost
  gather_facts: no
  vars:
    bigip_provider:
      bigip9: "10.0.0.16"
      bigip2: "10.0.0.18"
      bigip3: "10.0.0.17"
  tasks:
    - debug:
        msg: "{{ bigip_provider | dictsort | map(attribute='1') | map('regex_replace','$','/24') | list }}"

Result:

ok: [localhost] => {
    "msg": [
        "10.0.0.18/24",
        "10.0.0.17/24",
        "10.0.0.16/24"
    ]
}


问:
Closing then opening browser with Watir
I want to close the current browser, open a new one and let it continue it's work.
It looks something like this:

```<code>browser = Watir::Browser.new :chrome
.....
browser = browser.close

browser = browser.new
..
</code>```

But after closing the browser it returns

uninitialized constant Browser (NameError)

Thanks :)

答:
when you call browser.close, the browser object gets removed after the actual browser is closed.   To make a new one you need to use the same syntax you did the first time  (as indicated by Justin in the comments to your question) </p>

```<code>browser = Watir::Browser.new :chrome
</code>```

Title: Closing then opening browser with Watir

Body:
I want to close the current browser, open a new one and let it continue it's work.
It looks something like this:

browser = Watir::Browser.new :chrome
.....
browser = browser.close

browser = browser.new
..

But after closing the browser it returns

uninitialized constant Browser (NameError)

Thanks :)

Body:
when you call browser.close, the browser object gets removed after the actual browser is closed.   To make a new one you need to use the same syntax you did the first time  (as indicated by Justin in the comments to your question)

browser = Watir::Browser.new :chrome


问:
Asking for pairs of information on a x_mdialog for scilab
I'm creating a program to calculate the linear regression of data. The program should, when you start, ask for the number of pairs of values (x and y) to be used. And according to the number of pairs that you define, it should go asking for the data to apply the regression (on pairs of X, Y). The program must apply regression for all methods available.

I already have the code for the regressions but the problem that I have is that I don't know how to ask for the data (the pairs of x and y) and for x create a vector, and for y create a separate vector. Also, it can be from 3 pairs to infinite number of pairs.

答:
There are many ways to accomplish what you want. One possible way is to use a for-loop:

Inquiry the users on how many points they want to input, n_pairs, as you said.

Use a for-loop from 1 to n_pairs asking for inputs using x_mdialog.

At each iteration, evaluate the input and store the data.

Something like the following could work for you:

```<code>//inquiry how many pairs
n_pairs = x_mdialog("Data acquisition","How many points will you enter?","3");
n_pairs = evstr(n_pairs);

//initialise data
X_data = []; Y_data = [];

for i = 1 : n_pairs
    //acquire each pair
    pair = x_mdialog("Data acquisition",["X:","Y:"],["",""])

    if pair(1) == "" | pair(2) == "" | pair == [] then
        //break loop in case of blank input
        break
    else
        //non-blank inputs are stored
        X_data(i) = evstr(pair(1));
        Y_data(i) = evstr(pair(2));
    end
end

//sort values accordint to X
[X_data,idx] = gsort(X_data,"r","i");
Y_data = Y_data(idx);
</code>```

Body:
There are many ways to accomplish what you want. One possible way is to use a for-loop:

Inquiry the users on how many points they want to input, n_pairs, as you said.

Use a for-loop from 1 to n_pairs asking for inputs using x_mdialog.

At each iteration, evaluate the input and store the data.

Something like the following could work for you:

//inquiry how many pairs
n_pairs = x_mdialog("Data acquisition","How many points will you enter?","3");
n_pairs = evstr(n_pairs);

//initialise data
X_data = []; Y_data = [];

for i = 1 : n_pairs
    //acquire each pair
    pair = x_mdialog("Data acquisition",["X:","Y:"],["",""])

    if pair(1) == "" | pair(2) == "" | pair == [] then
        //break loop in case of blank input
        break
    else
        //non-blank inputs are stored
        X_data(i) = evstr(pair(1));
        Y_data(i) = evstr(pair(2));
    end
end

//sort values accordint to X
[X_data,idx] = gsort(X_data,"r","i");
Y_data = Y_data(idx);


问:
How cookies are managed by networking code
I was recently migrating over from C# and looking to create some of my old applications. As such I have needed to find a way to manage sessions within Go web requests. I found a solution in the form of this code:

```<code>// Jar is session object struct - cookie jar including mutex for syncing
type Jar struct {
    sync.Mutex
    cookies map[string][]*http.Cookie
}

// NewJar is a function for creating cookie jar for use
func NewJar() *Jar {
    jar := new(Jar)
    jar.cookies = make(map[string][]*http.Cookie)
    return jar
}

// SetCookies sets the cookies for the jar
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    jar.Lock()
    if _, ok := jar.cookies[u.Host]; ok {
        for _, c := range cookies {
            jar.cookies[u.Host] = append(jar.cookies[u.Host], c)
        }
    } else {
        jar.cookies[u.Host] = cookies
    }
    jar.Unlock()
}

// Cookies returns cookies for each host
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
    return jar.cookies[u.Host]
}

// NewJarClient creates new client, utilising a NewJar()
func NewJarClient() *http.Client {

    proxyURL, _ := url.Parse("http://127.0.0.1:8888")

    tr := &http.Transport{
        MaxIdleConns:       10,
        IdleConnTimeout:    30 * time.Second,
        DisableCompression: true,
        Proxy:              http.ProxyURL(proxyURL),
    }

    return &http.Client{
        Jar:       NewJar(),
        Transport: tr,
    }
}
</code>```

The problem I'm having is in understanding how this works. I create a client doing the following

```<code>client := NewJarClient()
</code>```

but then when I issue networking fuctions using it such as a get request, the cookies automatically carry on and it all works as planned. The problem is  Ihave no idea why. I see no mention of methods such as the Cookies one or the SetCookies one ever being called and it seems to just handle each one by magically running the functions. Could someone annotate or explain the given methods line by line or in a way so that they'd make better sense to me coming over from a C# background. Thanks :)

答:
NewJar allocates and returns a new instance of type *Jar, now type *Jar, thanks to the methods defined on it, implements the interface called CookieJar, implicitly.

The http.Client type has a field called Jar which is defined as having the type CookieJar, that means that you can set http.Client.Jar to anything that implements the CookieJar interface, including the *Jar type. The NewJarClient function returns a new *http.Client instance with it's Jar field set to the *Jar instance returned by NewJar.

This allows the returned client value to use *Jar's methods without really knowing that it's a *Jar, it only knows that the value in its Jar field has the same set of methods as those defined by the CookieJar interface.

So the http.Client instance, when sending requests, uses your *Jar by calling its methods providing the parameters and handling the returned values. How your *Jar is used by the client is an implementation detail of the http.Client type and you don't have to worry about that. You just need to make sure that the methods that implement the CookieJar interface do what you want them to do, how and when they are called is up to the client.

But if you're interested in the implementation details of the client anyway, you can check out the source file of http.Client.

Body:
I was recently migrating over from C# and looking to create some of my old applications. As such I have needed to find a way to manage sessions within Go web requests. I found a solution in the form of this code:

// Jar is session object struct - cookie jar including mutex for syncing
type Jar struct {
    sync.Mutex
    cookies map[string][]*http.Cookie
}

// NewJar is a function for creating cookie jar for use
func NewJar() *Jar {
    jar := new(Jar)
    jar.cookies = make(map[string][]*http.Cookie)
    return jar
}

// SetCookies sets the cookies for the jar
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    jar.Lock()
    if _, ok := jar.cookies[u.Host]; ok {
        for _, c := range cookies {
            jar.cookies[u.Host] = append(jar.cookies[u.Host], c)
        }
    } else {
        jar.cookies[u.Host] = cookies
    }
    jar.Unlock()
}

// Cookies returns cookies for each host
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
    return jar.cookies[u.Host]
}

// NewJarClient creates new client, utilising a NewJar()
func NewJarClient() *http.Client {

    proxyURL, _ := url.Parse("http://127.0.0.1:8888")

    tr := &http.Transport{
        MaxIdleConns:       10,
        IdleConnTimeout:    30 * time.Second,
        DisableCompression: true,
        Proxy:              http.ProxyURL(proxyURL),
    }

    return &http.Client{
        Jar:       NewJar(),
        Transport: tr,
    }
}

The problem I'm having is in understanding how this works. I create a client doing the following

client := NewJarClient()

but then when I issue networking fuctions using it such as a get request, the cookies automatically carry on and it all works as planned. The problem is  Ihave no idea why. I see no mention of methods such as the Cookies one or the SetCookies one ever being called and it seems to just handle each one by magically running the functions. Could someone annotate or explain the given methods line by line or in a way so that they'd make better sense to me coming over from a C# background. Thanks :)


问:
Tableau extracts update
I would like to know if there's a way to automatically update my extracts?

I have a live connection with redshift and use tableau desktop and publish some workbooks on tableau online.

I like to share some reports using extracts and tableau reader and I really need a way to update the extracts everyday

答:
if I understand your question correctly, you should be able to refresh your Tableau Data Extracts by setting up "Refresh Schedules" on Tableau Online. Tableau Online supports variety of Data Sources to set up Extracts instead of using Live Connection.
Check this link on setting up refresh schedules.

Hope this helps!

ContentLicense: CC BY-SA 4.0

Title: Tableau extracts update


问:
NODE-RED only receives UDP packets from the same machine
A UDP node in node-red app receives successfully osc messages sent from the same computer, but fails to do so if the messages are sent from another computer on the same subnet.

Firewall you say? No firewall installed on the network or any computers. More over, the same node-red flow works fine on another computer in both scenarios.

What's interesting is the

```<code>sudo tcpdump -A -vv 'udp and port 3001'
</code>```

does show the packets arriving when sent from another computer. It just they do reach the computer, but not the node-red.

Also

```<code>sudo nmap -sU -p 3001 192.168.1.34
</code>```

from both another and local terminal will produce this

```<code>Nmap scan report for 192.168.1.34
Host is up.
PORT     STATE         SERVICE
3001/udp open|filtered unknown
</code>```

What are my next steps?

UPD: It seems that "Ports already in use: 3001" message confuses some commenters. This not a warning, it's a notification that the port being added uses this port.

Anyway I solved the problem by reformatting and reinstalling the OS.

答:
The warning shown in the config window shows that there is another node already bound to port 3001.

You can only bind to a port once. If you want to run multiple flows from the same input you can wire them all to the same UDP input node.

Body:
A UDP node in node-red app receives successfully osc messages sent from the same computer, but fails to do so if the messages are sent from another computer on the same subnet.

Firewall you say? No firewall installed on the network or any computers. More over, the same node-red flow works fine on another computer in both scenarios.

What's interesting is the

sudo tcpdump -A -vv 'udp and port 3001'

does show the packets arriving when sent from another computer. It just they do reach the computer, but not the node-red.

Also

sudo nmap -sU -p 3001 192.168.1.34

from both another and local terminal will produce this

Nmap scan report for 192.168.1.34
Host is up.
PORT     STATE         SERVICE
3001/udp open|filtered unknown

What are my next steps?

UPD: It seems that "Ports already in use: 3001" message confuses some commenters. This not a warning, it's a notification that the port being added uses this port.

Anyway I solved the problem by reformatting and reinstalling the OS.


问:
How to group ranged values using SQL Server
I have a table of values like this

```<code>978412, 400
978813, 20
978834, 50
981001, 20
</code>```

As you can see the second number when added to the first is 1 number before the next in the sequence. The last number is not in the range (doesnt follow a direct sequence, as in the next value). What I need is a CTE (yes, ideally) that will output this

```<code>978412, 472
981001, 20
</code>```

The first row contains the start number of the range then the sum of the nodes within. The next row is the next range which in this example is the same as the original data.

答:
Check out this MSDN Article. It gives you a solution to your problem, if it will work for you depends on the ammount of data you have and your performance requirements for the query.

Edit:

Well using the example in the query, and going with his last solution the second way to get islands (first way resulted in an error on SQL 2005).

```<code>SELECT MIN(start) AS  startGroup, endGroup, (endgroup-min(start) +1) as NumNodes
FROM (SELECT g1.gapID AS start,
(SELECT min(g2.gapID) FROM #gaps g2
WHERE g2.gapID >= g1.gapID and NOT EXISTS
(SELECT * FROM #gaps g3
WHERE g3.gapID - g2.gapID = 1)) as endGroup
FROM #gaps g1) T1 GROUP BY endGroup
</code>```

The thing I added is (endgroup-min(start) +1) as NumNodes. This will give you the counts.

OwnerDisplayName: Coolcoder

Body:
I have a table of values like this

978412, 400
978813, 20
978834, 50
981001, 20

As you can see the second number when added to the first is 1 number before the next in the sequence. The last number is not in the range (doesnt follow a direct sequence, as in the next value). What I need is a CTE (yes, ideally) that will output this

978412, 472
981001, 20

The first row contains the start number of the range then the sum of the nodes within. The next row is the next range which in this example is the same as the original data.

LastEditorDisplayName: Coolcoder

Body:
Check out this MSDN Article. It gives you a solution to your problem, if it will work for you depends on the ammount of data you have and your performance requirements for the query.

Edit:

Well using the example in the query, and going with his last solution the second way to get islands (first way resulted in an error on SQL 2005).

SELECT MIN(start) AS  startGroup, endGroup, (endgroup-min(start) +1) as NumNodes
FROM (SELECT g1.gapID AS start,
(SELECT min(g2.gapID) FROM #gaps g2
WHERE g2.gapID >= g1.gapID and NOT EXISTS
(SELECT * FROM #gaps g3
WHERE g3.gapID - g2.gapID = 1)) as endGroup
FROM #gaps g1) T1 GROUP BY endGroup

The thing I added is (endgroup-min(start) +1) as NumNodes. This will give you the counts.

OwnerDisplayName: Josh

LastEditorDisplayName: Josh


问:
Getting a select's value with javascript
I have the following condensed form

```<code><form name="thecars">
<select name="cars">
    <option value="mustang">Mustang</option>
    <option value="pinto">Pinto</option>
    <option value="pinto">Chevelle</option>
    <option value="pinto">Other</option>
</select>
</form>
</code>```

I am trying to get the value of the selected car by the following but it is not working

```<code>selectedCar = document.forms["thecars"].elements["cars"].options[thecars.cars.options.selectedIndex].value;
</code>```

答:
Assign an ID to your select element:

```<code><select name="cars" id="cars">
</code>```

And you can get the value like this:

```<code>document.getElementById('cars').value
</code>```

Body:
I have the following condensed form

<form name="thecars">
<select name="cars">
    <option value="mustang">Mustang</option>
    <option value="pinto">Pinto</option>
    <option value="pinto">Chevelle</option>
    <option value="pinto">Other</option>
</select>
</form>

I am trying to get the value of the selected car by the following but it is not working

selectedCar = document.forms["thecars"].elements["cars"].options[thecars.cars.options.selectedIndex].value;

Body:
Assign an ID to your select element:

<select name="cars" id="cars">

And you can get the value like this:

document.getElementById('cars').value


问:
Subscribe to Event only works when component is loaded
I have trouble handling data fetched from a Database. I'd like to send it to a central service in order to use it later when I load the components that will use the data.
My problem is that the central service only seems to receive the data when I initialize the component that depends on this service.
Consequence: the data is not ready yet when the component loads and I get this type of error:

ERROR TypeError: Cannot read property 'gender' of undefined

Here is how my app is structured:

-a dataStorage service which handles the http requests

-a central service which stores all the data (in that case, an array of objects).

-both a placed in a "shared" folder

-various components (with lazy loading) taking data from the central service

-the http request is sent when the app is initialized

Here is the data storage service. When the http request is made I send the data via an event in the constructor

```<code>@Injectable()
export class DataStorageService {
    constructor(private http:Http,private authService:AuthService){
      this.getStoredCatList().subscribe(
      (response:Response)=> {
             const data = response.json();
             this.dataFetched.emit(data);
        },
      (error:Error)=>console.log(error)
      );
  }

dataFetched = new EventEmitter<Cat[]>();

    getStoredCatList(){
        return this.http.get('https://adopt-meow.firebaseio.com/data.json');

    }
}
</code>```

And here is the central service where I subscribe to the event.

```<code>@Injectable()
export class CatListService implements OnInit{

    constructor(private dataStorageService:DataStorageService){
        this.dataStorageService.dataFetched.subscribe(
            (catList:Cat[])=>this.catList = catList,
            console.log("event received by catList service"))
        }
</code>```

From my understanding of Angular, I think I should get the message "event received by catList service" as soon as the event emits. So why do I get it only when I load the components?

EDIT
For those of you interested in following up that matter, I managed to find a solution by importing the services in app.component.ts, right when the app starts.

```<code>constructor(private dataStorageService: DataStorageService,
    private catListService:CatListService) { }
</code>```

答:
It sounds like the data is not yet loaded when you try to display it in your template.

U could try adding the async pipe where you are displaying the data.

```<code><span>{{ genders | async }}</span>
</code>```

That should avoid the error you are getting.

Body:
I have trouble handling data fetched from a Database. I'd like to send it to a central service in order to use it later when I load the components that will use the data.
My problem is that the central service only seems to receive the data when I initialize the component that depends on this service.
Consequence: the data is not ready yet when the component loads and I get this type of error:

ERROR TypeError: Cannot read property 'gender' of undefined

Here is how my app is structured:

-a dataStorage service which handles the http requests

-a central service which stores all the data (in that case, an array of objects).

-both a placed in a "shared" folder

-various components (with lazy loading) taking data from the central service

-the http request is sent when the app is initialized

Here is the data storage service. When the http request is made I send the data via an event in the constructor

@Injectable()
export class DataStorageService {
    constructor(private http:Http,private authService:AuthService){
      this.getStoredCatList().subscribe(
      (response:Response)=> {
             const data = response.json();
             this.dataFetched.emit(data);
        },
      (error:Error)=>console.log(error)
      );
  }

dataFetched = new EventEmitter<Cat[]>();

    getStoredCatList(){
        return this.http.get('https://adopt-meow.firebaseio.com/data.json');

    }
}

And here is the central service where I subscribe to the event.

@Injectable()
export class CatListService implements OnInit{

    constructor(private dataStorageService:DataStorageService){
        this.dataStorageService.dataFetched.subscribe(
            (catList:Cat[])=>this.catList = catList,
            console.log("event received by catList service"))
        }

From my understanding of Angular, I think I should get the message "event received by catList service" as soon as the event emits. So why do I get it only when I load the components?

EDIT
For those of you interested in following up that matter, I managed to find a solution by importing the services in app.component.ts, right when the app starts.

constructor(private dataStorageService: DataStorageService,
    private catListService:CatListService) { }

Body:
It sounds like the data is not yet loaded when you try to display it in your template.

U could try adding the async pipe where you are displaying the data.

<span>{{ genders | async }}</span>

That should avoid the error you are getting.


问:
what code can i use to clear the screen(java)?
I'm writing a text-based unit converter and I want to be able to run a clear command so that the window that the program I want to know how I can do it.</p>

答:
I think you can System.exec("clear") but that depends on what operating system the program is running on. </p>

<p>This is my choice for clear: </p>

```<code>public static void clearConsole() {
        String value = "\n\r";
        for (int i = 0; i < 5; ++i) {
            value = value + value;
            System.out.printf(value);
        }
    }
</code>```

Body:
I think you can System.exec("clear") but that depends on what operating system the program is running on.

This is my choice for clear:

public static void clearConsole() {
        String value = "\n\r";
        for (int i = 0; i < 5; ++i) {
            value = value + value;
            System.out.printf(value);
        }
    }


问:
Unable to use SevenZFile at Java6 to unzip 7z File
I can unzip 7z File by using org.apache.commons.compress.archivers.sevenz.SevenZFile at Java 7 and java 8. But I cant do that by using Java6. Can you please help me to fix that issue by Java 6 ? SeekableByteChannel cannot be found by Java6 :( </p>

<p>You can find out the sample code below : </p>

```<code>SeekableInMemoryByteChannel inMemoryByteChannel = new
 SeekableInMemoryByteChannel(targetArray);
    SevenZFile sevenZFile = new SevenZFile(inMemoryByteChannel);
</code>```

答:
Starting with Apache Commons Compress 1.13 it requires Java 7 at runtime. If you need support for Java6 version 1.12 or earlier will work (but may have less features or a different set of bugs).

In the case of 7z 1.12 and earlier only allow reading of files, not arbitrary streams. It was the move to Java7 and the chance to use SeekableByteChannel that allowed supporting reading from more general inputs.

Body:
I can unzip 7z File by using org.apache.commons.compress.archivers.sevenz.SevenZFile at Java 7 and java 8. But I cant do that by using Java6. Can you please help me to fix that issue by Java 6 ? SeekableByteChannel cannot be found by Java6 :(

You can find out the sample code below :

SeekableInMemoryByteChannel inMemoryByteChannel = new
 SeekableInMemoryByteChannel(targetArray);
    SevenZFile sevenZFile = new SevenZFile(inMemoryByteChannel);


问:
PerformActionFor shortcutItem AppDelegate.swift (Swift 4)
I would like to create a 3D Touch ShortCut on my app, I've done everything about the shortcut it self, it appear correctly, with text and icon.

When I run this shortcut, my app crashes, because the function in AppDelegate.swift calls a function inside my root viewController that instantiate AVPlayer(), make it play and finally, updates the user interface by changing the image of my play/stop button and there is where I have my problem.

I give you the code bellow.

here is a part of my AppDelegate.swift:

```<code>func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "fr.xxxxxxxxxxx.xxxxxxxxxxxxxx.playRadio" {
        let playerVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"Player") as! ViewController
        playerVC.playPlayer()
    }
}
</code>```

and here is a part of my ViewController.swift:

```<code>@objc func playPlayer() {
    initAVAudioSession()
    setupPlayer()
    RadioPlayer.rate = 1.0
    RadioPlayer.play()
    playButton.setImage(UIImage(named: "stopbutton"), for: .normal)
}
</code>```

It crashes at playButton line with this error :

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
  Optional value

Note: If I insert a question mark (?) on my playButton inside playPlayer() (like so playButton?.setImage(...)), everything works well, but my UI is not updated.
My rootViewController is a UITabBarController placed before Player:ViewController

How to make this working correctly?

答:
I found the solution due to this post this post</p>

```<code> func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        if shortcutItem.type == "fr.xxxxxxxxxx.xxxxxxxxxxxx.playRadio" {
            //window!.rootViewController?.present("Player", animated: true, completion: nil)
            //selectedViewController .playPlayer()
            if let rootViewController = window?.rootViewController as? UITabBarController {
                if let viewController = rootViewController.viewControllers?.first as? ViewController {
                    viewController.playPlayer()
                }
            }
        }
    }
</code>```

Body:
I would like to create a 3D Touch ShortCut on my app, I've done everything about the shortcut it self, it appear correctly, with text and icon.

When I run this shortcut, my app crashes, because the function in AppDelegate.swift calls a function inside my root viewController that instantiate AVPlayer(), make it play and finally, updates the user interface by changing the image of my play/stop button and there is where I have my problem.

I give you the code bellow.

here is a part of my AppDelegate.swift:

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "fr.xxxxxxxxxxx.xxxxxxxxxxxxxx.playRadio" {
        let playerVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"Player") as! ViewController
        playerVC.playPlayer()
    }
}

and here is a part of my ViewController.swift:

@objc func playPlayer() {
    initAVAudioSession()
    setupPlayer()
    RadioPlayer.rate = 1.0
    RadioPlayer.play()
    playButton.setImage(UIImage(named: "stopbutton"), for: .normal)
}

It crashes at playButton line with this error :

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
  Optional value

Note: If I insert a question mark (?) on my playButton inside playPlayer() (like so playButton?.setImage(...)), everything works well, but my UI is not updated.
My rootViewController is a UITabBarController placed before Player:ViewController

How to make this working correctly?

Body:
I found the solution due to this post this post

 func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        if shortcutItem.type == "fr.xxxxxxxxxx.xxxxxxxxxxxx.playRadio" {
            //window!.rootViewController?.present("Player", animated: true, completion: nil)
            //selectedViewController .playPlayer()
            if let rootViewController = window?.rootViewController as? UITabBarController {
                if let viewController = rootViewController.viewControllers?.first as? ViewController {
                    viewController.playPlayer()
                }
            }
        }
    }


问:
Java configuration for spring aws cloud SNS endpoint argument resolver
I am struggling to find spring boot java configuration equivalent to the below xml configuration for my spring aws cloud SNS http endpoint. Could some one please help?.</p>

```<code><mvc:annotation-driven>
        <mvc:argument-resolvers>
            <ref bean="notificationResolver" />
        </mvc:argument-resolvers>
       </mvc:annotation-driven>
     <aws-messaging:notification-argument-resolver id="notificationResolver" />
</code>```

答:
The Java config is in the spring-cloud-aws project here on GitHub

```<code>import com.amazonaws.services.sns.AmazonSNS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.aws.context.annotation.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

import static org.springframework.cloud.aws.messaging.endpoint.config.NotificationHandlerMethodArgumentResolverConfigurationUtils.getNotificationHandlerMethodArgumentResolver;

/**
 * @author Agim Emruli
 */
@Configuration
@ConditionalOnClass("org.springframework.web.servlet.config.annotation.WebMvcConfigurer")
public class SnsWebConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private AmazonSNS amazonSns;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(getNotificationHandlerMethodArgumentResolver(this.amazonSns));
    }
}
</code>```

Body:
I am struggling to find spring boot java configuration equivalent to the below xml configuration for my spring aws cloud SNS http endpoint. Could some one please help?.

<mvc:annotation-driven>
        <mvc:argument-resolvers>
            <ref bean="notificationResolver" />
        </mvc:argument-resolvers>
       </mvc:annotation-driven>
     <aws-messaging:notification-argument-resolver id="notificationResolver" />

Body:
The Java config is in the spring-cloud-aws project here on GitHub

import com.amazonaws.services.sns.AmazonSNS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.aws.context.annotation.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

import static org.springframework.cloud.aws.messaging.endpoint.config.NotificationHandlerMethodArgumentResolverConfigurationUtils.getNotificationHandlerMethodArgumentResolver;

/**
 * @author Agim Emruli
 */
@Configuration
@ConditionalOnClass("org.springframework.web.servlet.config.annotation.WebMvcConfigurer")
public class SnsWebConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private AmazonSNS amazonSns;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(getNotificationHandlerMethodArgumentResolver(this.amazonSns));
    }
}


问:
How to create a column on a SQL table, based on values of another table
I currently have 2 SQL tables:  table1 and table2. table1 has 2 columns called id_a and column_a. table2 has 2 columns called id_b and column_b.

I would like to create a new_column in table1. The value of new_column should be 1 if the value of table1.id_a exists in table2.id_b. Otherwise, new_column should have the value of 0.

How do I do this? I'm using SQLite3 and table1 is significantly larger than table2.

答:
A left join solution for fun! In certain circumstances might even be more efficient than correlated subquery as well.

```<code>select
    t1.*,
    case
        when t2.id_b is null then 0
        else 1
    end as new_column
from
    table1 t1
left join
    table2 t2
    on t2.id_b = t1.id_a
</code>```

Body:
A left join solution for fun! In certain circumstances might even be more efficient than correlated subquery as well.

select
    t1.*,
    case
        when t2.id_b is null then 0
        else 1
    end as new_column
from
    table1 t1
left join
    table2 t2
    on t2.id_b = t1.id_a


问:
merge arrays and convert to JSON string
I have two arrays consist of strings
["25","36","32"] and ["GradeA", "GradeB", "GradeC"]

I want to merge them all together and want to produce JSON string something like this:

{"GradeA" : "25", "GradeB" : "36", "GradeC": "32"}

How do I do this in js?

答:
And for an extra 2 cents I give you the forEach loop version of it. This is taking into consideration that each array is going to be 1 for 1 and in the appropriate order.</p>

```<code>var grade = ["GradeA", "GradeB", "GradeC"];
var number = ["25","36","32"];
var obj = {};

grade.forEach(function(x, i){
    obj[x] = number[i];
});

console.log(JSON.stringify(obj));
</code>```

Title: merge arrays and convert to JSON string

Body:
And for an extra 2 cents I give you the forEach loop version of it. This is taking into consideration that each array is going to be 1 for 1 and in the appropriate order.

var grade = ["GradeA", "GradeB", "GradeC"];
var number = ["25","36","32"];
var obj = {};

grade.forEach(function(x, i){
    obj[x] = number[i];
});

console.log(JSON.stringify(obj));


问:
BizTalk and DB2 CLOB
Has anyone had experience dealing with DB2 stored procedures which take a CLOB input parameter and calling that stored procedure from BizTalk?

I've tried changing the schema type to string, base64binary, hexbinary, byte, but no matter what I get this error:

Error details: The parameter value for parameter 1 could not be converted to a native data type. Parameter Name: P_EML_BODY, Data Type: Long strings of input text
 More long strings of input text
More long strings of input text, Value : CharForBit

答: It might be the way the parameters are being created and in what order.  Take a look here.  Are any of them null or empty?</p>

Title: BizTalk and DB2 CLOB


问:
"transaction interface" error when updating table on linked server
I'm getting this error when trying to update a db2 database that is a linked server on our SQL Server db.

ERROR:root:('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]The requested operation could not be performed because OLE DB provider "IBMDA400" for linked server "iSeries" does not support the required transaction interface. (7390) (SQLExecDirectW)')

I am connecting to sql server via pyodbc and can run sql scripts with no issues. Here is the sql I get the error with

```<code>sql3 = " exec ('UPDATE SVCEN2DEV.SRVMAST SET SVRMVD = ? WHERE svtype != ''*DCS-'' AND svcid = ? and svacct = ? ') AT [iSeries]"
db.execute(sql3, (row[2],srvid,row[0]))
db.commit()
</code>```

And just in case here is my connection string  using pyodbc:

```<code>conn = pyodbc.connect("DRIVER={SQL Server};SERVER="+ Config_Main.dbServer +";DATABASE="+ Config_Main.encludeName +";UID="+ Config_Main.encludeUser +";PWD=" + Config_Main.encludePass)
db = conn.cursor()
</code>```

Also note that this query runs just fine in SSMS. I have also tried the openquery method but had no luck. Any ideas?

答:
Python's DB API 2.0 specifies that, by default, connections should open with autocommit "off". This results in all database operations being performed in a transaction that must be explicitly committed (or rolled back) in the Python code.

When a pyodbc connection with autocommit = False (the default) sends an UPDATE to the SQL Server, that UPDATE is enclosed in a Local Transaction managed by SQL Server. When the SQL Server determines that the target table is on a Linked Server it tries to promote the transaction to a Distributed Transaction managed by MSDTC. If the connection technology used to manage the Linked Server does not support Distributed Transactions then the operation will fail.

This issue can often be avoided by ensuring that the pyodbc connection has autocommit enabled, either by

cnxn = pyodbc.connect(conn_str, autocommit=True)
```

<p>or</p>

<pre class="lang-python prettyprint-override"><code>cnxn = pyodbc.connect(conn_str)
cnxn.autocommit = True
</code>```

That will send each SQL statement individually, without being wrapped in an implicit transaction.

Body:
I'm getting this error when trying to update a db2 database that is a linked server on our SQL Server db.

ERROR:root:('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]The requested operation could not be performed because OLE DB provider "IBMDA400" for linked server "iSeries" does not support the required transaction interface. (7390) (SQLExecDirectW)')

I am connecting to sql server via pyodbc and can run sql scripts with no issues. Here is the sql I get the error with

sql3 = " exec ('UPDATE SVCEN2DEV.SRVMAST SET SVRMVD = ? WHERE svtype != ''*DCS-'' AND svcid = ? and svacct = ? ') AT [iSeries]"
db.execute(sql3, (row[2],srvid,row[0]))
db.commit()

And just in case here is my connection string  using pyodbc:

conn = pyodbc.connect("DRIVER={SQL Server};SERVER="+ Config_Main.dbServer +";DATABASE="+ Config_Main.encludeName +";UID="+ Config_Main.encludeUser +";PWD=" + Config_Main.encludePass)
db = conn.cursor()

Also note that this query runs just fine in SSMS. I have also tried the openquery method but had no luck. Any ideas?

Body:
Python's DB API 2.0 specifies that, by default, connections should open with autocommit "off". This results in all database operations being performed in a transaction that must be explicitly committed (or rolled back) in the Python code.

When a pyodbc connection with autocommit = False (the default) sends an UPDATE to the SQL Server, that UPDATE is enclosed in a Local Transaction managed by SQL Server. When the SQL Server determines that the target table is on a Linked Server it tries to promote the transaction to a Distributed Transaction managed by MSDTC. If the connection technology used to manage the Linked Server does not support Distributed Transactions then the operation will fail.

This issue can often be avoided by ensuring that the pyodbc connection has autocommit enabled, either by

cnxn = pyodbc.connect(conn_str, autocommit=True)

or

cnxn = pyodbc.connect(conn_str)
cnxn.autocommit = True

That will send each SQL statement individually, without being wrapped in an implicit transaction.


问:
Compress html output from zend framework 2
I'm currently using Zend Framework 2 beta for on PHP 5.4.4 to develop a personal webapp for self-study purpose.

I was wondering if it is possible to intercept the html output just before it is sent to the browser in order to minify it by removing all unnecessary white spaces.

How could I achieve this result in ZF2?

答:
Just put this two method inside any module.php . It will gzip and send compressed out put to the browser.</p>

```<code> public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    $eventManager->attach("finish", array($this, "compressOutput"), 100);
}

public function compressOutput($e)
    {
        $response = $e->getResponse();
        $content = $response->getBody();
        $content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//<![CDATA[n" . '1' . "n//]]>"), $content);

        if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
            header('Content-Encoding: gzip');
            $content = gzencode($content, 9);
        }

        $response->setContent($content);
    }
</code>```

Body:
Just put this two method inside any module.php . It will gzip and send compressed out put to the browser.

 public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    $eventManager->attach("finish", array($this, "compressOutput"), 100);
}

public function compressOutput($e)
    {
        $response = $e->getResponse();
        $content = $response->getBody();
        $content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//&lt;![CDATA[n" . '1' . "n//]]>"), $content);

        if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
            header('Content-Encoding: gzip');
            $content = gzencode($content, 9);
        }

        $response->setContent($content);
    }


问:
Python virtualenv export to windows
I would like you to suggest me some way how non-IT person would install program I created.

So basically I have virtualenv with python with libs. I am looking for some program that would create something (some exe or whatever necessary) that I would just put on usb, and when another human copied it on newly installed windows pc, it would just work. Its going to be PyQT application.

I would easily be able to setup everything, but it needs to be dumb-proof way. Just some 'exe-like' solution that would do everything itself.

Any suggestions would be highly appreciated. If you feel like this is duplicate, please point me into right direction...but all examples I found needed at least little bit of "IT mind".

答:
pyinstaller package is the best one! see : http://www.pyinstaller.org/

with pyinstaller you can convert your .py files to .exe

you should install ( pywin32 pakcage too ), then you can try this ( run this on your commandline ):

```<code>pyinstaller.exe --onefile --windowed --icon=app.ico your_app.py
</code>```

you can find all its commands on : https://pythonhosted.org/PyInstaller/usage.html, https://mborgerson.com/creating-an-executable-from-a-python-script/

Title: Python virtualenv export to windows

Body:
pyinstaller package is the best one! see : http://www.pyinstaller.org/

with pyinstaller you can convert your .py files to .exe

you should install ( pywin32 pakcage too ), then you can try this ( run this on your commandline ):

pyinstaller.exe --onefile --windowed --icon=app.ico your_app.py

you can find all its commands on : https://pythonhosted.org/PyInstaller/usage.html, https://mborgerson.com/creating-an-executable-from-a-python-script/