问:
Python - Use RegEx on HTML file for specific word?
I have emails that have embedded HTML tables in them. I use BeautifulSoup to extract the data tables, but there is data just outside the tables that I can't capture with this method.

Here is an example email with two data tables:

Like I said, I use bs4 to capture the information from inside the tables' cells. I then turn this data into a DataFrame. I would like to also capture the Package price in order to append it to each Fish-Weight value. Simple commands like:

```<code>for line in f:
    if ("Package" in line):
    print("line:", line)
</code>```

...fail to print anything. When I examine the HTML closer I see that it looks like this:

```
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>FW: NEFS 11 fish available</title>
<link rel="important stylesheet" href="">

Subject: FW: NEFS 11 fish available

From: Claire Fitz-Gerald <claire@capecodfishermen.org>

Date: 6/2/2016 5:55 PM

<meta http-equiv="Content-Type" content="text/html; ">
<meta name="Generator" content="Microsoft Word 15 (filtered medium)">

Please see below quota listings.<o:p></o:p>

<o:p> </o:p>

Thanks,<o:p></o:p>

<o:p> </o:p>

Claire Fitz-Gerald<o:p></o:p>

<o:p> </o:p>

Cape Cod Commercial Fishermen's Alliance<o:p></o:p>

~ Small Boats.  Big Ideas. ~<o:p></o:p>

Celebrating 25 years. Navigating 25 more.
<o:p></o:p>

<o:p> </o:p>

From: NEFS V [mailto:nefsector5@gmail.com]

Sent: Thursday, June 02, 2016 12:32 PM

To: Ben Martens <ben@mainecoastfishermen.org>; Claire Fitz-Gerald <claire@capecodfishermen.org>; Dave Leveille 2 & 6 <nefs02@gmail.com>; Hank SHS <shsector@gmail.com>; John Haran 10 & 13 <sector13@comcast.net>; Linda MaCann 7 & 8 <nbsector07@comcast.net>;
 mike walsh 6 <fisherwoman2042003@yahoo.com>; Patrick NCCS <patrick@penobscoteast.org>; paula lynch 12 <paulasectorx@yahoo.com>; Spice Montgomery 3 <nefsiii@gmail.com>; Stephanie Rafael-DeMello 9 <nbsector9@gmail.com>; tory bramante 6 <torybra@aol.com>; NEFS
 11 Charles Felch <boat1151@aol.com>; NEFS 11 David Goethel <egoethel@comcast.net>; NEFS 11 Fanel Dobre <stormdancer4@yahoo.com>; NEFS 11 Geordie King <kinggeordie@comcast.net>; NEFS 11 Jamie Hayward <jamienjolyn@comcast.net>; NEFS 11 Jayson Driscoll <jaysondriscoll@yahoo.com>;
 NEFS 11 Mike and Pat Anderson <padi.anderson@gmail.com>; NEFS 11 Neil Pike <sandipike@hotmail.com>; NEFS 11 Richard Anderson <monkfishing@hotmail.com>; NEFS 11 Tom Lyons <tomrlyons@hotmail.com>; Puggy <charles.felch@yahoo.com>

Subject: NEFS 11 fish available<o:p></o:p>

<o:p> </o:p>

All,<o:p></o:p>

NEFS 11 has the following available:<o:p></o:p>

<o:p> </o:p>

Package 1:  $ 500.00<o:p></o:p>

gb cod east<o:p></o:p>

1<o:p></o:p>

gb cod west<o:p></o:p>

5<o:p></o:p>

gom cod<o:p></o:p>

148<o:p></o:p>

gb haddock east<o:p></o:p>

1<o:p></o:p>

gb haddock west<o:p></o:p>

2<o:p></o:p>

gom haddock<o:p></o:p>

12<o:p></o:p>

white hake<o:p></o:p>

4<o:p></o:p>

pollock<o:p></o:p>

162<o:p></o:p>

redfish<o:p></o:p>

25<o:p></o:p>

<o:p> </o:p>

Package 2: $ 5,225.00<o:p></o:p>

gom cod<o:p></o:p>

916<o:p></o:p>

gom winter fl<o:p></o:p>

498<o:p></o:p>

<o:p> </o:p>

gom haddock<o:p></o:p>

284<o:p></o:p>

white hake<o:p></o:p>

505<o:p></o:p>

dab<o:p></o:p>

1,293<o:p></o:p>

pollock<o:p></o:p>

812<o:p></o:p>

redfish<o:p></o:p>

1,910<o:p></o:p>

witch fl<o:p></o:p>

352<o:p></o:p>

cc/gom yellowtail<o:p></o:p>

306<o:p></o:p>

<o:p></o:p>

Package 3:  $ 44,150.00<o:p></o:p>

gb cod east<o:p></o:p>

5<o:p></o:p>

gb cod west<o:p></o:p>

17<o:p></o:p>

gom cod<o:p></o:p>

5,000<o:p></o:p>

gom winter fl<o:p></o:p>

2,900<o:p></o:p>

gb haddock east<o:p></o:p>

836<o:p></o:p>

gb haddock west<o:p></o:p>

2,118<o:p></o:p>

gom haddock<o:p></o:p>

18,000<o:p></o:p>

white hake<o:p></o:p>

8,842<o:p></o:p>

dab<o:p></o:p>

8,650<o:p></o:p>

pollock<o:p></o:p>

78,000<o:p></o:p>

redfish<o:p></o:p>

35,923<o:p></o:p>

witch fl<o:p></o:p>

3,250<o:p></o:p>

cc/gom yellowtail<o:p></o:p>

2,250<o:p></o:p>

<o:p> </o:p>

Package 4:  $ 43,135.00<o:p></o:p>

GOM cod          6,900<o:p></o:p>

dabs                3,800<o:p></o:p>

witch fl             4,000<o:p></o:p>

cc/gom yt         5,100<o:p></o:p>

<o:p> </o:p>

GB West Cod  - 3,251 lbs libe weight = $ 6,500.00<o:p></o:p>

<o:p></o:p>

-- <o:p></o:p>

Daniel Salerno<o:p></o:p>

NEFS 5 & NEFS 11<o:p></o:p>

401-932-0070<o:p></o:p>

401-633-6539 (fax)<o:p></o:p>

```

<p>I am not an expert with HTML, is there a way to capture and append the <code>Package</code> price to its corresponding Fish-Weight values?</p>

<p>My relevant code is:</p>

```package_regex = re.compile(r'package(.*)(?=\n)', re.IGNORECASE)
with open(file_path) as in_f:
    for line in in_f:
        for match in package_regex.finditer(in_f.read()):
            price, stuff = match.groups()
            print("price:", price)
            print("stuff:", stuff)

with open(file_path) as in_f:
    msg = email.message_from_file(in_f)             #type: <class 'email.message.Messgae'>

html_msg = msg.get_payload(1)                       #type: <class 'email.message.Message'>

body = html_msg.get_payload(decode=True)            #type: <class 'bytes'> or type: 'int'

html = body.decode()                                #type: <class 'str'>
for line in html:
    if ("Package" in line):
        print("line:", line)

tables = bs4.BeautifulSoup(html).find_all("table")  #type: <class 'bs4.element.ResultSet'>
data = []
for table in tables:
    for row in table.find_all("tr"):
        data.append([cell.text.strip() for cell in row.find_all("td")])
```

答:
```<code>from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

tables = soup.find_all(lambda tag: tag.name=='table') # and tag.has_attr('id') and tag['id']=="Table1")

chunks = soup.find_all('p',  {'class' : "MsoNormal"})

for line in chunks:
    if 'Package' in line.text:
        print line.text
        for table in tables:
            for row in table.find_all("tr"):
                print [cell.text.strip() for cell in row.find_all("td")]
</code>```

output:

```<code>Package 1:  $ 500.00
[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
[u'gb cod east', u'', u'1']
[u'gb cod west', u'', u'5']
[u'gom cod', u'', u'148']
[u'gb haddock east', u'', u'1']
[u'gb haddock west', u'', u'2']
[u'gom haddock', u'', u'12']
[u'white hake', u'', u'4']
[u'pollock', u'', u'162']
[u'redfish', u'', u'25']
[u'gom cod', u'', u'916']
[u'gom winter fl', u'', u'498']
[u'gom haddock', u'', u'284']
[u'white hake', u'', u'505']
[u'dab', u'', u'1,293']
[u'pollock', u'', u'812']
[u'redfish', u'', u'1,910']
[u'witch fl', u'', u'352']
[u'cc/gom yellowtail', u'', u'306']
[u'gb cod east', u'', u'', u'5']
[u'gb cod west', u'', u'', u'17']
[u'gom cod', u'', u'', u'5,000']
[u'gom winter fl', u'', u'', u'2,900']
[u'gb haddock east', u'', u'', u'836']
[u'gb haddock west', u'', u'', u'2,118']
[u'gom haddock', u'', u'', u'18,000']
[u'white hake', u'', u'', u'8,842']
[u'dab', u'', u'', u'8,650']
[u'pollock', u'', u'', u'78,000']
[u'redfish', u'', u'', u'35,923']
[u'witch fl', u'', u'', u'3,250']
[u'cc/gom yellowtail', u'', u'', u'2,250']
Package 2: $ 5,225.00
[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
[u'gb cod east', u'', u'1']
[u'gb cod west', u'', u'5']
[u'gom cod', u'', u'148']
[u'gb haddock east', u'', u'1']
[u'gb haddock west', u'', u'2']
[u'gom haddock', u'', u'12']
[u'white hake', u'', u'4']
[u'pollock', u'', u'162']
[u'redfish', u'', u'25']
[u'gom cod', u'', u'916']
[u'gom winter fl', u'', u'498']
[u'gom haddock', u'', u'284']
[u'white hake', u'', u'505']
[u'dab', u'', u'1,293']
[u'pollock', u'', u'812']
[u'redfish', u'', u'1,910']
[u'witch fl', u'', u'352']
[u'cc/gom yellowtail', u'', u'306']
[u'gb cod east', u'', u'', u'5']
[u'gb cod west', u'', u'', u'17']
[u'gom cod', u'', u'', u'5,000']
[u'gom winter fl', u'', u'', u'2,900']
[u'gb haddock east', u'', u'', u'836']
[u'gb haddock west', u'', u'', u'2,118']
[u'gom haddock', u'', u'', u'18,000']
[u'white hake', u'', u'', u'8,842']
[u'dab', u'', u'', u'8,650']
[u'pollock', u'', u'', u'78,000']
[u'redfish', u'', u'', u'35,923']
[u'witch fl', u'', u'', u'3,250']
[u'cc/gom yellowtail', u'', u'', u'2,250']
Package 3:  $ 44,150.00
[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
[u'gb cod east', u'', u'1']
[u'gb cod west', u'', u'5']
[u'gom cod', u'', u'148']
[u'gb haddock east', u'', u'1']
[u'gb haddock west', u'', u'2']
[u'gom haddock', u'', u'12']
[u'white hake', u'', u'4']
[u'pollock', u'', u'162']
[u'redfish', u'', u'25']
[u'gom cod', u'', u'916']
[u'gom winter fl', u'', u'498']
[u'gom haddock', u'', u'284']
[u'white hake', u'', u'505']
[u'dab', u'', u'1,293']
[u'pollock', u'', u'812']
[u'redfish', u'', u'1,910']
[u'witch fl', u'', u'352']
[u'cc/gom yellowtail', u'', u'306']
[u'gb cod east', u'', u'', u'5']
[u'gb cod west', u'', u'', u'17']
[u'gom cod', u'', u'', u'5,000']
[u'gom winter fl', u'', u'', u'2,900']
[u'gb haddock east', u'', u'', u'836']
[u'gb haddock west', u'', u'', u'2,118']
[u'gom haddock', u'', u'', u'18,000']
[u'white hake', u'', u'', u'8,842']
[u'dab', u'', u'', u'8,650']
[u'pollock', u'', u'', u'78,000']
[u'redfish', u'', u'', u'35,923']
[u'witch fl', u'', u'', u'3,250']
[u'cc/gom yellowtail', u'', u'', u'2,250']
Package 4:  $ 43,135.00
[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
[u'gb cod east', u'', u'1']
[u'gb cod west', u'', u'5']
[u'gom cod', u'', u'148']
[u'gb haddock east', u'', u'1']
[u'gb haddock west', u'', u'2']
[u'gom haddock', u'', u'12']
[u'white hake', u'', u'4']
[u'pollock', u'', u'162']
[u'redfish', u'', u'25']
[u'gom cod', u'', u'916']
[u'gom winter fl', u'', u'498']
[u'gom haddock', u'', u'284']
[u'white hake', u'', u'505']
[u'dab', u'', u'1,293']
[u'pollock', u'', u'812']
[u'redfish', u'', u'1,910']
[u'witch fl', u'', u'352']
[u'cc/gom yellowtail', u'', u'306']
[u'gb cod east', u'', u'', u'5']
[u'gb cod west', u'', u'', u'17']
[u'gom cod', u'', u'', u'5,000']
[u'gom winter fl', u'', u'', u'2,900']
[u'gb haddock east', u'', u'', u'836']
[u'gb haddock west', u'', u'', u'2,118']
[u'gom haddock', u'', u'', u'18,000']
[u'white hake', u'', u'', u'8,842']
[u'dab', u'', u'', u'8,650']
[u'pollock', u'', u'', u'78,000']
[u'redfish', u'', u'', u'35,923']
[u'witch fl', u'', u'', u'3,250']
[u'cc/gom yellowtail', u'', u'', u'2,250']
</code>```

Unfortunately there is some redundant, non-correlated repetition in each iteration with

```<code>[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
</code>```

which may be circumvented if desired.

Body:
I have emails that have embedded HTML tables in them. I use BeautifulSoup to extract the data tables, but there is data just outside the tables that I can't capture with this method.

Here is an example email with two data tables:

Like I said, I use bs4 to capture the information from inside the tables' cells. I then turn this data into a DataFrame. I would like to also capture the Package price in order to append it to each Fish-Weight value. Simple commands like:

for line in f:
    if ("Package" in line):
    print("line:", line)

...fail to print anything. When I examine the HTML closer I see that it looks like this:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>FW: NEFS 11 fish available</title>
<link rel="important stylesheet" href="">

Subject: FW: NEFS 11 fish available

From: Claire Fitz-Gerald <claire@capecodfishermen.org>

Date: 6/2/2016 5:55 PM

<meta http-equiv="Content-Type" content="text/html; ">
<meta name="Generator" content="Microsoft Word 15 (filtered medium)">

Please see below quota listings.<o:p></o:p>

<o:p> </o:p>

Thanks,<o:p></o:p>

<o:p> </o:p>

Claire Fitz-Gerald<o:p></o:p>

<o:p> </o:p>

Cape Cod Commercial Fishermen's Alliance<o:p></o:p>

~ Small Boats.  Big Ideas. ~<o:p></o:p>

Celebrating 25 years. Navigating 25 more.
<o:p></o:p>

<o:p> </o:p>

From: NEFS V [mailto:nefsector5@gmail.com]

Sent: Thursday, June 02, 2016 12:32 PM

To: Ben Martens <ben@mainecoastfishermen.org>; Claire Fitz-Gerald <claire@capecodfishermen.org>; Dave Leveille 2 & 6 <nefs02@gmail.com>; Hank SHS <shsector@gmail.com>; John Haran 10 & 13 <sector13@comcast.net>; Linda MaCann 7 & 8 <nbsector07@comcast.net>;
 mike walsh 6 <fisherwoman2042003@yahoo.com>; Patrick NCCS <patrick@penobscoteast.org>; paula lynch 12 <paulasectorx@yahoo.com>; Spice Montgomery 3 <nefsiii@gmail.com>; Stephanie Rafael-DeMello 9 <nbsector9@gmail.com>; tory bramante 6 <torybra@aol.com>; NEFS
 11 Charles Felch <boat1151@aol.com>; NEFS 11 David Goethel <egoethel@comcast.net>; NEFS 11 Fanel Dobre <stormdancer4@yahoo.com>; NEFS 11 Geordie King <kinggeordie@comcast.net>; NEFS 11 Jamie Hayward <jamienjolyn@comcast.net>; NEFS 11 Jayson Driscoll <jaysondriscoll@yahoo.com>;
 NEFS 11 Mike and Pat Anderson <padi.anderson@gmail.com>; NEFS 11 Neil Pike <sandipike@hotmail.com>; NEFS 11 Richard Anderson <monkfishing@hotmail.com>; NEFS 11 Tom Lyons <tomrlyons@hotmail.com>; Puggy <charles.felch@yahoo.com>

Subject: NEFS 11 fish available<o:p></o:p>

<o:p> </o:p>

All,<o:p></o:p>

NEFS 11 has the following available:<o:p></o:p>

<o:p> </o:p>

Package 1:  $ 500.00<o:p></o:p>

gb cod east<o:p></o:p>

1<o:p></o:p>

gb cod west<o:p></o:p>

5<o:p></o:p>

gom cod<o:p></o:p>

148<o:p></o:p>

gb haddock east<o:p></o:p>

1<o:p></o:p>

gb haddock west<o:p></o:p>

2<o:p></o:p>

gom haddock<o:p></o:p>

12<o:p></o:p>

white hake<o:p></o:p>

4<o:p></o:p>

pollock<o:p></o:p>

162<o:p></o:p>

redfish<o:p></o:p>

25<o:p></o:p>

<o:p> </o:p>

Package 2: $ 5,225.00<o:p></o:p>

gom cod<o:p></o:p>

916<o:p></o:p>

gom winter fl<o:p></o:p>

498<o:p></o:p>

<o:p> </o:p>

gom haddock<o:p></o:p>

284<o:p></o:p>

white hake<o:p></o:p>

505<o:p></o:p>

dab<o:p></o:p>

1,293<o:p></o:p>

pollock<o:p></o:p>

812<o:p></o:p>

redfish<o:p></o:p>

1,910<o:p></o:p>

witch fl<o:p></o:p>

352<o:p></o:p>

cc/gom yellowtail<o:p></o:p>

306<o:p></o:p>

<o:p></o:p>

Package 3:  $ 44,150.00<o:p></o:p>

gb cod east<o:p></o:p>

5<o:p></o:p>

gb cod west<o:p></o:p>

17<o:p></o:p>

gom cod<o:p></o:p>

5,000<o:p></o:p>

gom winter fl<o:p></o:p>

2,900<o:p></o:p>

gb haddock east<o:p></o:p>

836<o:p></o:p>

gb haddock west<o:p></o:p>

2,118<o:p></o:p>

gom haddock<o:p></o:p>

18,000<o:p></o:p>

white hake<o:p></o:p>

8,842<o:p></o:p>

dab<o:p></o:p>

8,650<o:p></o:p>

pollock<o:p></o:p>

78,000<o:p></o:p>

redfish<o:p></o:p>

35,923<o:p></o:p>

witch fl<o:p></o:p>

3,250<o:p></o:p>

cc/gom yellowtail<o:p></o:p>

2,250<o:p></o:p>

<o:p> </o:p>

Package 4:  $ 43,135.00<o:p></o:p>

GOM cod          6,900<o:p></o:p>

dabs                3,800<o:p></o:p>

witch fl             4,000<o:p></o:p>

cc/gom yt         5,100<o:p></o:p>

<o:p> </o:p>

GB West Cod  - 3,251 lbs libe weight = $ 6,500.00<o:p></o:p>

<o:p></o:p>

-- <o:p></o:p>

Daniel Salerno<o:p></o:p>

NEFS 5 & NEFS 11<o:p></o:p>

401-932-0070<o:p></o:p>

401-633-6539 (fax)<o:p></o:p>

I am not an expert with HTML, is there a way to capture and append the Package price to its corresponding Fish-Weight values?

My relevant code is:

package_regex = re.compile(r'package(.*)(?=\n)', re.IGNORECASE)
with open(file_path) as in_f:
    for line in in_f:
        for match in package_regex.finditer(in_f.read()):
            price, stuff = match.groups()
            print("price:", price)
            print("stuff:", stuff)

with open(file_path) as in_f:
    msg = email.message_from_file(in_f)             #type: <class 'email.message.Messgae'>

html_msg = msg.get_payload(1)                       #type: <class 'email.message.Message'>

body = html_msg.get_payload(decode=True)            #type: <class 'bytes'> or type: 'int'

html = body.decode()                                #type: <class 'str'>
for line in html:
    if ("Package" in line):
        print("line:", line)

tables = bs4.BeautifulSoup(html).find_all("table")  #type: <class 'bs4.element.ResultSet'>
data = []
for table in tables:
    for row in table.find_all("tr"):
        data.append([cell.text.strip() for cell in row.find_all("td")])

Body:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

tables = soup.find_all(lambda tag: tag.name=='table') # and tag.has_attr('id') and tag['id']=="Table1")

chunks = soup.find_all('p',  {'class' : "MsoNormal"})

for line in chunks:
    if 'Package' in line.text:
        print line.text
        for table in tables:
            for row in table.find_all("tr"):
                print [cell.text.strip() for cell in row.find_all("td")]

output:

Package 1:  $ 500.00
[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
[u'gb cod east', u'', u'1']
[u'gb cod west', u'', u'5']
[u'gom cod', u'', u'148']
[u'gb haddock east', u'', u'1']
[u'gb haddock west', u'', u'2']
[u'gom haddock', u'', u'12']
[u'white hake', u'', u'4']
[u'pollock', u'', u'162']
[u'redfish', u'', u'25']
[u'gom cod', u'', u'916']
[u'gom winter fl', u'', u'498']
[u'gom haddock', u'', u'284']
[u'white hake', u'', u'505']
[u'dab', u'', u'1,293']
[u'pollock', u'', u'812']
[u'redfish', u'', u'1,910']
[u'witch fl', u'', u'352']
[u'cc/gom yellowtail', u'', u'306']
[u'gb cod east', u'', u'', u'5']
[u'gb cod west', u'', u'', u'17']
[u'gom cod', u'', u'', u'5,000']
[u'gom winter fl', u'', u'', u'2,900']
[u'gb haddock east', u'', u'', u'836']
[u'gb haddock west', u'', u'', u'2,118']
[u'gom haddock', u'', u'', u'18,000']
[u'white hake', u'', u'', u'8,842']
[u'dab', u'', u'', u'8,650']
[u'pollock', u'', u'', u'78,000']
[u'redfish', u'', u'', u'35,923']
[u'witch fl', u'', u'', u'3,250']
[u'cc/gom yellowtail', u'', u'', u'2,250']
Package 2: $ 5,225.00
[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
[u'gb cod east', u'', u'1']
[u'gb cod west', u'', u'5']
[u'gom cod', u'', u'148']
[u'gb haddock east', u'', u'1']
[u'gb haddock west', u'', u'2']
[u'gom haddock', u'', u'12']
[u'white hake', u'', u'4']
[u'pollock', u'', u'162']
[u'redfish', u'', u'25']
[u'gom cod', u'', u'916']
[u'gom winter fl', u'', u'498']
[u'gom haddock', u'', u'284']
[u'white hake', u'', u'505']
[u'dab', u'', u'1,293']
[u'pollock', u'', u'812']
[u'redfish', u'', u'1,910']
[u'witch fl', u'', u'352']
[u'cc/gom yellowtail', u'', u'306']
[u'gb cod east', u'', u'', u'5']
[u'gb cod west', u'', u'', u'17']
[u'gom cod', u'', u'', u'5,000']
[u'gom winter fl', u'', u'', u'2,900']
[u'gb haddock east', u'', u'', u'836']
[u'gb haddock west', u'', u'', u'2,118']
[u'gom haddock', u'', u'', u'18,000']
[u'white hake', u'', u'', u'8,842']
[u'dab', u'', u'', u'8,650']
[u'pollock', u'', u'', u'78,000']
[u'redfish', u'', u'', u'35,923']
[u'witch fl', u'', u'', u'3,250']
[u'cc/gom yellowtail', u'', u'', u'2,250']
Package 3:  $ 44,150.00
[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
[u'gb cod east', u'', u'1']
[u'gb cod west', u'', u'5']
[u'gom cod', u'', u'148']
[u'gb haddock east', u'', u'1']
[u'gb haddock west', u'', u'2']
[u'gom haddock', u'', u'12']
[u'white hake', u'', u'4']
[u'pollock', u'', u'162']
[u'redfish', u'', u'25']
[u'gom cod', u'', u'916']
[u'gom winter fl', u'', u'498']
[u'gom haddock', u'', u'284']
[u'white hake', u'', u'505']
[u'dab', u'', u'1,293']
[u'pollock', u'', u'812']
[u'redfish', u'', u'1,910']
[u'witch fl', u'', u'352']
[u'cc/gom yellowtail', u'', u'306']
[u'gb cod east', u'', u'', u'5']
[u'gb cod west', u'', u'', u'17']
[u'gom cod', u'', u'', u'5,000']
[u'gom winter fl', u'', u'', u'2,900']
[u'gb haddock east', u'', u'', u'836']
[u'gb haddock west', u'', u'', u'2,118']
[u'gom haddock', u'', u'', u'18,000']
[u'white hake', u'', u'', u'8,842']
[u'dab', u'', u'', u'8,650']
[u'pollock', u'', u'', u'78,000']
[u'redfish', u'', u'', u'35,923']
[u'witch fl', u'', u'', u'3,250']
[u'cc/gom yellowtail', u'', u'', u'2,250']
Package 4:  $ 43,135.00
[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']
[u'gb cod east', u'', u'1']
[u'gb cod west', u'', u'5']
[u'gom cod', u'', u'148']
[u'gb haddock east', u'', u'1']
[u'gb haddock west', u'', u'2']
[u'gom haddock', u'', u'12']
[u'white hake', u'', u'4']
[u'pollock', u'', u'162']
[u'redfish', u'', u'25']
[u'gom cod', u'', u'916']
[u'gom winter fl', u'', u'498']
[u'gom haddock', u'', u'284']
[u'white hake', u'', u'505']
[u'dab', u'', u'1,293']
[u'pollock', u'', u'812']
[u'redfish', u'', u'1,910']
[u'witch fl', u'', u'352']
[u'cc/gom yellowtail', u'', u'306']
[u'gb cod east', u'', u'', u'5']
[u'gb cod west', u'', u'', u'17']
[u'gom cod', u'', u'', u'5,000']
[u'gom winter fl', u'', u'', u'2,900']
[u'gb haddock east', u'', u'', u'836']
[u'gb haddock west', u'', u'', u'2,118']
[u'gom haddock', u'', u'', u'18,000']
[u'white hake', u'', u'', u'8,842']
[u'dab', u'', u'', u'8,650']
[u'pollock', u'', u'', u'78,000']
[u'redfish', u'', u'', u'35,923']
[u'witch fl', u'', u'', u'3,250']
[u'cc/gom yellowtail', u'', u'', u'2,250']

Unfortunately there is some redundant, non-correlated repetition in each iteration with

[u'Subject: FW: NEFS 11 fish available']
[u'From: Claire Fitz-Gerald']
[u'Date: 6/2/2016 5:55 PM']

which may be circumvented if desired.


来源: stackexchange

问:
bash sed/awk/something for printing lines from match till eof except first line
Well task should be easy i guess but i failed to find the answer.

I need to find some regex in file and print all lines from first match till the end of file but the first found one.

To find and print sed/awk do the trick:

```<code>awk '/regex/,0'
sed '/regex/,$p'
</code>```

But i feel pretty silly that i can't exclude first matching line from output.

Any tips? Pretty sure that shouldn't be hard. I'm just lacking of knowledge.

PS I need exactly to:

find line matching regex

print all lines from this regex to the end of file

exclude first line

in one action.

Excluding line after only find-n-print action leads to more complicated solution

Example

```<code>$ cat file
11 1st Cookie
12 2nd Cookie
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

Find and print:

```<code>$ awk '/Dinner/,0' file
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

What i want to get:

```<code>14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

答:
try:

```<code>awk '/Dinner/{a=1;next} a'   Input_file
</code>```

Looking for string Dinner here, if yes then make a variable named as value 1, putting next will skip all further statements and to avoid printing that specific line which has dinner string in it. Then mentioning a means checking if a is NOT NULL then not mentioned any action here so by default print of the current line will happen.

ContentLicense: CC BY-SA 3.0

Body:
Well task should be easy i guess but i failed to find the answer.

I need to find some regex in file and print all lines from first match till the end of file but the first found one.

To find and print sed/awk do the trick:

awk '/regex/,0'
sed '/regex/,$p'

But i feel pretty silly that i can't exclude first matching line from output.

Any tips? Pretty sure that shouldn't be hard. I'm just lacking of knowledge.

PS I need exactly to:

find line matching regex

print all lines from this regex to the end of file

exclude first line

in one action.

Excluding line after only find-n-print action leads to more complicated solution

Example

$ cat file
11 1st Cookie
12 2nd Cookie
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

Find and print:

$ awk '/Dinner/,0' file
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

What i want to get:

14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

Body:
try:

awk '/Dinner/{a=1;next} a'   Input_file

Looking for string Dinner here, if yes then make a variable named as value 1, putting next will skip all further statements and to avoid printing that specific line which has dinner string in it. Then mentioning a means checking if a is NOT NULL then not mentioned any action here so by default print of the current line will happen.


问:
Changing the hash but not moving the page using jquery ui tabs
I added the following code to change the hash to the tab name:

```<code>$("#tabs > ul").tabs({
select: function(event, ui){
window.location.hash = ui.tab.hash;
}
} );
</code>```

This works fine in FF3 but in IE7 it moves down the page (depending on the tab selected anywhere from somewhere near the top of the page all the way down to the very end of the page).

I tried changing it to:

```<code>$("#tabs > ul").tabs();
$("#tabs > ul").bind("tabsshow", function(event, ui) {
window.location = ui.tab.hash;
})
</code>```

This leads to identical behavior in both IE7 and FF3, which moves the page down to the top of the selected tab.

I would like the tab to be changed, the hash to be updated, but the page not moved at all, which is how it works in FF3 in my first example, but not in IE7.

Thanks.

Notes: JQuery 1.3.1 / JQuery-UI 1.6rc6

答:
What Chris suggested worked for me, had no clue even a div could link via the #. So my solution is quite simple, in the show: event handler, I do the following, it's not perfect in that back button won't be in history, but that's another job for BBQ history plugin. All my divs simply have id="tab-cars", id="tab-trucks"... strip out the 'tab-' part and put it into the url hash.</p>

```<code>var name = ui.panel.id.substr(4);
location.hash = '#'+name;
</code>```

OwnerDisplayName: Rob

ContentLicense: CC BY-SA 2.5

Body:
I added the following code to change the hash to the tab name:

$("#tabs > ul").tabs({
select: function(event, ui){
window.location.hash = ui.tab.hash;
}
} );

This works fine in FF3 but in IE7 it moves down the page (depending on the tab selected anywhere from somewhere near the top of the page all the way down to the very end of the page).

I tried changing it to:

$("#tabs > ul").tabs();
$("#tabs > ul").bind("tabsshow", function(event, ui) {
window.location = ui.tab.hash;
})

This leads to identical behavior in both IE7 and FF3, which moves the page down to the top of the selected tab.

I would like the tab to be changed, the hash to be updated, but the page not moved at all, which is how it works in FF3 in my first example, but not in IE7.

Thanks.

Notes: JQuery 1.3.1 / JQuery-UI 1.6rc6

Body:
What Chris suggested worked for me, had no clue even a div could link via the #. So my solution is quite simple, in the show: event handler, I do the following, it's not perfect in that back button won't be in history, but that's another job for BBQ history plugin. All my divs simply have id="tab-cars", id="tab-trucks"... strip out the 'tab-' part and put it into the url hash.

var name = ui.panel.id.substr(4);
location.hash = '#'+name;


问:
How can I change the function of the service now incident update action?
Which ui action can I edit to change the behavior of updating an incident? I have looked through the ui actions and I can not find one for the update.

UPDATE: I was able to find the ui action for updating the incident. However when I try to edit it none of my changes are implemented. I just added an alert to it and nothing happened.

答: Great question! The "Update" UI action can be disabled by creating a new UI Action, and un-checking the "Show Update" button on the UI Action form. You can then simply name your new UI Action "Update", and you're good to go!


问:
How do I assign embedded interface to object in golang
I am attempting to assign an array of structs of type Baz to an array of interfaces of type Bar embedded in a second struct of type Foo. I have not been able to find the exact information here or elsewhere googling. I have provided a minimum working example.

I get the following error:

$ go run main.go

./main.go:38: cannot use baz (type []*Baz) as type []Bar in argument to NewFoo

My apologies if my code is not idiomatic go and also if I have not confirmed exactly to standards for posting questions, this is my first post.

```<code>package main

import (
    "fmt"
)
type Foo struct {
    b []Bar
}

type Baz struct {
    a, b int
}

type Bar interface {
    Multiply() int
}

func (baz *Baz) Multiply() int{
    return baz.a * baz.b
}

func NewFoo(bar []Bar) *Foo{
    return &Foo{b: bar}
}
func NewBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = &Baz{a: 1, b: 2}
    bazes[1] = &Baz{a: 3, b: 4}
    return bazes
}

func main() {

    baz := NewBaz()
    foo := NewFoo(baz)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}
</code>```

UPDATE: I approved the duplicate vote after further reading and understanding the suggested related posts. Thank you to those who pointed me in that direction. For future interested readers, my final implementation consistent with my use case is as follows:

```<code>package main

import (
    "fmt"
)

type Foo struct {
    b []Bar
}

type Baz struct {
    a, b int
}

type Bar interface { //
    Multiply() int
}

func (baz *Baz) Multiply() int {
    return baz.a * baz.b
}

func NewFoo(bar []*Baz) *Foo{
    f := &Foo{}
    f.b = make([]Bar, 2)
    fmt.Println("len(bar) ", len(bar), "len(f.b)", len(f.b) )
    for i, _ := range f.b {
        f.b[i] = bar[i]

    }
    return f
}

func MakeBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = NewBaz(1, 2)
    bazes[1] = NewBaz(3, 4)
    return bazes
}

func NewBaz(aa, bb int) *Baz {
    return &Baz{a: aa, b: bb}
}

func main() {
    baz := MakeBaz()
    foo := NewFoo(baz)
    fmt.Printf("%v\n", foo)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}
</code>```

答:
There's a couple of different ways to do this, but the most straightforward is to embed type Baz with Bar. Baz can now multiply() and has two fields (a, b). Your code would look something like this:

```<code>package main

import (
    "fmt"
)

type Foo struct {
    b []*Baz
}

type Baz struct {
    Bar
    a, b int
}

type Bar interface {
    Multiply() int
}

func (baz *Baz) Multiply() int {
    return baz.a * baz.b
}

func NewFoo(bar []*Baz) *Foo {
    return &Foo{b: bar}
}
func NewBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = &Baz{a: 1, b: 2}
    bazes[1] = &Baz{a: 3, b: 4}
    return bazes
}

func main() {
    baz := NewBaz()
    foo := NewFoo(baz)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}
</code>```

GoPlay here:
https://play.golang.org/p/lia0ZS81TO

Great first question, by the way.

Body:
I am attempting to assign an array of structs of type Baz to an array of interfaces of type Bar embedded in a second struct of type Foo. I have not been able to find the exact information here or elsewhere googling. I have provided a minimum working example.

I get the following error:

$ go run main.go

./main.go:38: cannot use baz (type []*Baz) as type []Bar in argument to NewFoo

My apologies if my code is not idiomatic go and also if I have not confirmed exactly to standards for posting questions, this is my first post.

package main

import (
    "fmt"
)
type Foo struct {
    b []Bar
}

type Baz struct {
    a, b int
}

type Bar interface {
    Multiply() int
}

func (baz *Baz) Multiply() int{
    return baz.a * baz.b
}

func NewFoo(bar []Bar) *Foo{
    return &Foo{b: bar}
}
func NewBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = &Baz{a: 1, b: 2}
    bazes[1] = &Baz{a: 3, b: 4}
    return bazes
}

func main() {

    baz := NewBaz()
    foo := NewFoo(baz)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}

UPDATE: I approved the duplicate vote after further reading and understanding the suggested related posts. Thank you to those who pointed me in that direction. For future interested readers, my final implementation consistent with my use case is as follows:

package main

import (
    "fmt"
)

type Foo struct {
    b []Bar
}

type Baz struct {
    a, b int
}

type Bar interface { //
    Multiply() int
}

func (baz *Baz) Multiply() int {
    return baz.a * baz.b
}

func NewFoo(bar []*Baz) *Foo{
    f := &Foo{}
    f.b = make([]Bar, 2)
    fmt.Println("len(bar) ", len(bar), "len(f.b)", len(f.b) )
    for i, _ := range f.b {
        f.b[i] = bar[i]

    }
    return f
}

func MakeBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = NewBaz(1, 2)
    bazes[1] = NewBaz(3, 4)
    return bazes
}

func NewBaz(aa, bb int) *Baz {
    return &Baz{a: aa, b: bb}
}

func main() {
    baz := MakeBaz()
    foo := NewFoo(baz)
    fmt.Printf("%v\n", foo)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}

Body:
There's a couple of different ways to do this, but the most straightforward is to embed type Baz with Bar. Baz can now multiply() and has two fields (a, b). Your code would look something like this:

package main

import (
    "fmt"
)

type Foo struct {
    b []*Baz
}

type Baz struct {
    Bar
    a, b int
}

type Bar interface {
    Multiply() int
}

func (baz *Baz) Multiply() int {
    return baz.a * baz.b
}

func NewFoo(bar []*Baz) *Foo {
    return &Foo{b: bar}
}
func NewBaz() []*Baz {
    bazes := make([]*Baz, 2)
    bazes[0] = &Baz{a: 1, b: 2}
    bazes[1] = &Baz{a: 3, b: 4}
    return bazes
}

func main() {
    baz := NewBaz()
    foo := NewFoo(baz)
    for _, f := range foo.b {
        fmt.Println("Foo.Multiply ", f.Multiply())
    }
}

GoPlay here:
https://play.golang.org/p/lia0ZS81TO

Great first question, by the way.


问:
How to perform a join based on intervals with dplyr?
I have a data frame containing two columns: a grouping variable and a interval period over which the grouping variable holds. I have another data frame with a date column and a value column. How can I join these two tables together somewhat efficiently with dplyr+tidyverse functions?

```<code>library(dplyr)
library(lubridate)
ty <- data_frame(date = mdy(paste(1, 1 + seq(20), 2017, sep = "/")),
                 y = c(rnorm(7), rnorm(7, mean = 2), rnorm(6, mean = -1)))
gy <- data_frame(period = interval(mdy(c("01/01/2017", "01/08/2017", "01/15/2017")),
                                   mdy(c("01/07/2017", "01/14/2017", "01/20/2017"))),
                          batch = c(1, 2, 3))
</code>```

I want to build the table that is equivalent to:

```<code>ty %>% mutate(batch = c(rep(1, 7), rep(2, 7), rep(3, 6)))
</code>```

Ideally, this should work reasonably quickly on data sets of up to 1,000,000 rows. Better still if it works on 100,000,000 :).

答:
This is the best I could come up with so far:

```<code>ty$batch <- unlist(lapply(ty$date, function(d) gy$batch[which(d %within% gy$period)]), recursive = FALSE, use.names = FALSE)
</code>```

But it doesn't seem very fast.

Body:
I have a data frame containing two columns: a grouping variable and a interval period over which the grouping variable holds. I have another data frame with a date column and a value column. How can I join these two tables together somewhat efficiently with dplyr+tidyverse functions?

library(dplyr)
library(lubridate)
ty <- data_frame(date = mdy(paste(1, 1 + seq(20), 2017, sep = "/")),
                 y = c(rnorm(7), rnorm(7, mean = 2), rnorm(6, mean = -1)))
gy <- data_frame(period = interval(mdy(c("01/01/2017", "01/08/2017", "01/15/2017")),
                                   mdy(c("01/07/2017", "01/14/2017", "01/20/2017"))),
                          batch = c(1, 2, 3))

I want to build the table that is equivalent to:

ty %>% mutate(batch = c(rep(1, 7), rep(2, 7), rep(3, 6)))

Ideally, this should work reasonably quickly on data sets of up to 1,000,000 rows. Better still if it works on 100,000,000 :).

Body:
This is the best I could come up with so far:

ty$batch <- unlist(lapply(ty$date, function(d) gy$batch[which(d %within% gy$period)]), recursive = FALSE, use.names = FALSE)

But it doesn't seem very fast.


问:
How to create python bytes object from long hex string?
I have a long sequence of hex digits in a string, such as

000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44

only much longer, several kilobytes.  Is there a builtin way to convert this to a bytes object in python 2.6/3?

答:
Try the binascii module</p>

```<code>from binascii import unhexlify
b = unhexlify(myhexstr)
</code>```

OwnerDisplayName: recursive

Body:
Try the binascii module

from binascii import unhexlify
b = unhexlify(myhexstr)


问:
Center a flex item when its siblings have different widths
I know flexbox offers a great solution for centering items. But I run into an issue when I have 3 items and I'd like the center (2nd) item to be centered with respect to the window, regardless of the size of the other 2 items.

In my pen you can see the second item "Client Index" is off-center because the content on the right is larger than the content on the left.  How can I force it to center itself?

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex">
  <span style="font-size:12px;">small</span>
  <span style="font-size:20px;">Client Index</span>
  <span style="font-size:18px;">Lots of content that moves the center</span>
</div></code>```

My Codepen

答:
Use nested flex containers and auto margins.

.flex-container {
  display: flex;
}

.flex-item {
  flex: 1;
  display: flex;
  justify-content: center;
}

.flex-item:first-child>span {
  margin-right: auto;
}

.flex-item:last-child>span {
  margin-left: auto;
}

/* non-essential */
.flex-item {
  align-items: center;
  border: 1px solid #ccc;
  background-color: lightgreen;
  height: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
  <div class="flex-item"><span>short</span></div>
  <div class="flex-item"><span>medium</span></div>
  <div class="flex-item"><span>lonnnnnnnnnnnnnnnnnnnng</span></div>
</div></code>```

Here's how it works:

The top-level div is a flex container.

Each child div is now a flex item.

Each item is given flex: 1 in order to distribute container space equally.

Now the items are consuming all space in the row and are equal width.

Make each item a (nested) flex container and add justify-content: center.

Now each span element is a centered flex item.

Use flex auto margins to shift the outer spans left and right.

You could also forgo justify-content and use auto margins exclusively.

But justify-content can work here because auto margins always have priority. From the spec:

8.1. Aligning with auto
  margins

Prior to alignment via justify-content and align-self, any
  positive free space is distributed to auto margins in that dimension.

Body:
I know flexbox offers a great solution for centering items. But I run into an issue when I have 3 items and I'd like the center (2nd) item to be centered with respect to the window, regardless of the size of the other 2 items.

In my pen you can see the second item "Client Index" is off-center because the content on the right is larger than the content on the left.  How can I force it to center itself?

.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

  small
  Client Index
  Lots of content that moves the center

My Codepen

Body:
Use nested flex containers and auto margins.

.flex-container {
  display: flex;
}

.flex-item {
  flex: 1;
  display: flex;
  justify-content: center;
}

.flex-item:first-child>span {
  margin-right: auto;
}

.flex-item:last-child>span {
  margin-left: auto;
}

/* non-essential */
.flex-item {
  align-items: center;
  border: 1px solid #ccc;
  background-color: lightgreen;
  height: 40px;
}

<div class="flex-container">
  <div class="flex-item"><span>short</span></div>
  <div class="flex-item"><span>medium</span></div>
  <div class="flex-item"><span>lonnnnnnnnnnnnnnnnnnnng</span></div>
</div>

Here's how it works:

The top-level div is a flex container.

Each child div is now a flex item.

Each item is given flex: 1 in order to distribute container space equally.

Now the items are consuming all space in the row and are equal width.

Make each item a (nested) flex container and add justify-content: center.

Now each span element is a centered flex item.

Use flex auto margins to shift the outer spans left and right.

You could also forgo justify-content and use auto margins exclusively.

But justify-content can work here because auto margins always have priority. From the spec:

8.1. Aligning with auto
  margins

Prior to alignment via justify-content and align-self, any
  positive free space is distributed to auto margins in that dimension.


问:
start thread one by one without using join() in java
am new to thread in java i have a little idea abou thread, lets say i have 10 thread and i start it one by one like this

```<code>public class BaseRunnable implements Runnable {
    String ThreadNo;
    public  BaseRunnable(String ThreadNo) {
        // TODO Auto-generated constructor stub
        this.ThreadNo=ThreadNo;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

        for(int i=0;i<50;i++)
        {
             System.out.println("Thread no "+ThreadNo+"  Running with index > "+i);
        }
    }
}
</code>```

And in main Methord

```<code>BaseRunnable runnable=new BaseRunnable("1");//run on main thread
BaseRunnable runnableTwo=new BaseRunnable("2");//run on main thread
BaseRunnable runnable3=new BaseRunnable("3");//run on main thread
BaseRunnable runnable4=new BaseRunnable("4");//run on main thread
BaseRunnable runnabl5=new BaseRunnable("5");//run on main thread
BaseRunnable runnable6=new BaseRunnable("6");//run on main thread
BaseRunnable runnable7=new BaseRunnable("7");//run on main thread
BaseRunnable runnable8=new BaseRunnable("8");//run on main thread

Thread one=new Thread(runnable);
Thread two=new Thread(runnableTwo);
Thread thr3=new Thread(runnable3);
Thread thr4=new Thread(runnable4);
Thread thr5=new Thread(runnabl5);
Thread thr6=new Thread(runnable6);
Thread thr7=new Thread(runnable7);
Thread thr8=new Thread(runnable8);

one.start();
two.start();
thr3.start();
thr4.start();
thr5.start();
thr6.start();
thr7.start();
thr8.start();
</code>```

I know if I use join() I can run thready one by one (one.start(); one.join();)

I try another way using synchronized that made run one thread one by one but it was not in order, So any Expert help me to active this like Thread one first,Thread 2 etc without join()

Please consider this as a question by a beginner, please help

答:
You can achieve your goal in this way:</p>

```<code>        List<BaseRunnable> list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            list.add(new BaseRunnable(Integer.toString(i)));
        }

        for (BaseRunnable baseRunnable : list) {
            Thread thread = new Thread(baseRunnable);
            thread.start();
            while (thread.isAlive()) {
                Thread.sleep(10);
            }
        }
</code>```

Body:
am new to thread in java i have a little idea abou thread, lets say i have 10 thread and i start it one by one like this

public class BaseRunnable implements Runnable {
    String ThreadNo;
    public  BaseRunnable(String ThreadNo) {
        // TODO Auto-generated constructor stub
        this.ThreadNo=ThreadNo;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

        for(int i=0;i<50;i++)
        {
             System.out.println("Thread no "+ThreadNo+"  Running with index > "+i);
        }
    }
}

And in main Methord

BaseRunnable runnable=new BaseRunnable("1");//run on main thread
BaseRunnable runnableTwo=new BaseRunnable("2");//run on main thread
BaseRunnable runnable3=new BaseRunnable("3");//run on main thread
BaseRunnable runnable4=new BaseRunnable("4");//run on main thread
BaseRunnable runnabl5=new BaseRunnable("5");//run on main thread
BaseRunnable runnable6=new BaseRunnable("6");//run on main thread
BaseRunnable runnable7=new BaseRunnable("7");//run on main thread
BaseRunnable runnable8=new BaseRunnable("8");//run on main thread

Thread one=new Thread(runnable);
Thread two=new Thread(runnableTwo);
Thread thr3=new Thread(runnable3);
Thread thr4=new Thread(runnable4);
Thread thr5=new Thread(runnabl5);
Thread thr6=new Thread(runnable6);
Thread thr7=new Thread(runnable7);
Thread thr8=new Thread(runnable8);

one.start();
two.start();
thr3.start();
thr4.start();
thr5.start();
thr6.start();
thr7.start();
thr8.start();

I know if I use join() I can run thready one by one (one.start(); one.join();)

I try another way using synchronized that made run one thread one by one but it was not in order, So any Expert help me to active this like Thread one first,Thread 2 etc without join()

Please consider this as a question by a beginner, please help

Body:
You can achieve your goal in this way:

        List<BaseRunnable> list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            list.add(new BaseRunnable(Integer.toString(i)));
        }

        for (BaseRunnable baseRunnable : list) {
            Thread thread = new Thread(baseRunnable);
            thread.start();
            while (thread.isAlive()) {
                Thread.sleep(10);
            }
        }


问:
Is there any way to combine client-side and server-side Google API authentication?
Currently I am implementing an Ionic application that the front-end is on the mobile devices and the back-end is on the server. (So there is a connection latency between the device and the server) And my application is using the Google services (like Gmail, calendar, etc) by connecting to the Google API.

Currently the architecture is:

Device <==> Server <==> Google API

This is using the OAuth 2.0 server-side authentication. It works but the connection latency is way too long and feels like going back to the time when we have the dial-up internet connection.

I tried to use the OAuth 2.0 client-side authentication, which is:

Device <==> Google API

This is faster but it has 2 problems:

Even though Ionic packaged the front-end code into an application, I still have concerns that the rule "Everything in the front-end is visible to everyone" stays. (Did not find an evidence to prove or disapprove this hypothesis)

Google API OAuth 2.0 only issues flows to the client-side authentication, and flows expire very often, I don't want the user to grant the permission again and again.

So, I was wondering if it is possible to do the following:

Use the server-side authentication to store keys/credentials (I'm using Django as the back-end, which is Python) and the front-end gets keys/credentials from the server and proceed Google service using JavaScript codes.

答:
I know this is late to the party, but I'm going through this now. I think there are 2 ways to set this up, but neither are perfect.

Use server-side flow to authorize all the scopes you'll need on either the server or the client. When the token is obtained, pass it to your client. The down side is that the client now has a token that has access to more APIs than needed.

Create seperate authorization flows for both the client and server. This would mean the user has 2 authorization prompts, which is no good. The good thing about this approach is you could ensure the client has limited scopes, but the server could still handle the larger tasks (moving Drive files, sending emails, etc.)

In my case, the client would just need read access to the Contacts API, whereas the server needs full Drive access.

If anyone finds a combination approach, where only 1 authorization is needed, but the client and server have seperate scopes, that'd be the ideal situation.


问:
how i convert a bool to a Unityengine.Cursorlockmode
I have a small script to hide and put a cursor visible and I miss an error that specifically is this

error CS0029: Cannot implicitly convert type bool' toUnityEngine.CursorLockMode'

and this is the code

```<code>    using UnityEngine;
using System.Collections;

public class yea : MonoBehaviour {
    bool isLocked;
    void Start () {
        SetCursorLock(true);
    }

    void SetCursorLock(bool isLocked)
    {
        this.isLocked = isLocked;
        Cursor.lockState = isLocked;
        Cursor.visible = !isLocked;
    }

    void Update () {
        if (Input.GetKeyDown(KeyCode.I))
        {
            SetCursorLock(!isLocked);
        }

        if (Input.GetKeyDown(KeyCode.H))
        {
            SetCursorLock(isLocked);
        }
    }
}
</code>```

答:
You should use CursorLockMode instead. You can use CursorLockMode.Locked for locking the cursor. More information is available at
https://docs.unity3d.com/ScriptReference/CursorLockMode.html

Code example:

```<code> void SetCursorLock(bool isLocked)
 {
     if(isLocked)
        Cursor.lockState = CursorLockMode.Locked;
     else
        Cursor.lockState = CursorLockMode.None;

     Cursor.visible = !isLocked;
 }
</code>```

Body:
I have a small script to hide and put a cursor visible and I miss an error that specifically is this

error CS0029: Cannot implicitly convert type bool' toUnityEngine.CursorLockMode'

and this is the code

    using UnityEngine;
using System.Collections;

public class yea : MonoBehaviour {
    bool isLocked;
    void Start () {
        SetCursorLock(true);
    }

    void SetCursorLock(bool isLocked)
    {
        this.isLocked = isLocked;
        Cursor.lockState = isLocked;
        Cursor.visible = !isLocked;
    }

    void Update () {
        if (Input.GetKeyDown(KeyCode.I))
        {
            SetCursorLock(!isLocked);
        }

        if (Input.GetKeyDown(KeyCode.H))
        {
            SetCursorLock(isLocked);
        }
    }
}

Body:
You should use CursorLockMode instead. You can use CursorLockMode.Locked for locking the cursor. More information is available at
https://docs.unity3d.com/ScriptReference/CursorLockMode.html

Code example:

 void SetCursorLock(bool isLocked)
 {
     if(isLocked)
        Cursor.lockState = CursorLockMode.Locked;
     else
        Cursor.lockState = CursorLockMode.None;

     Cursor.visible = !isLocked;
 }


问:
Making a Shopify app public
I'm commissioning a developer to build a shopify app in ruby, and it will be private as just used for a clients project. However if I choose to use the bulk of this for a public app at some point is there any major technical headache in taking an app that was initially made private to be public, or is it just a case of changing a few settings? I'm just trying to plan this right!</p>

答: It would be trivial to make it public. I do that all the time, and it takes mere seconds to swap a pair of API keys and the URL. So you are good to go there.</p>

Title: Making a Shopify app public


问:
jquery how to fill select option in my form
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:

```<code><form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
        <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
        </select>
<input type="submit" value="GO GO GO"/>
</form>
<script src="/add-information/aa.js"></script>
</code>```

In this little code i receive a json with data from my database:

```<code>        var data = JSON.parse(response);
        console.log(data);
</code>```

in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:

```<code>var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?
</code>```

help me please, how i can fill select with data from 'data'?

THE SOLUTION BY ADEON IS:

var data = JSON.parse(response);
        console.log(data);

```<code>    var select = document.getElementById('activity_2');

    for (var i = 0; i < data.data.length; i++) {
    select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
        }
</code>```

答:
Assuming data is an array, you could iterate over it and apply it to the DOM like so.

```<code>var optionString = '';
var data = ['John', 'Josh'];

data.forEach(function(dataItem, index){
  optionString += '<option value="' + index + '">' + dataItem + '</option>';
});

$('#activity_2').append(optionString);
</code>```

Here is a working jsfiddle:
https://jsfiddle.net/9ke5fzqo/

Body:
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:

<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
        <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
        </select>
<input type="submit" value="GO GO GO"/>
</form>

In this little code i receive a json with data from my database:

        var data = JSON.parse(response);
        console.log(data);

in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:

var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?

help me please, how i can fill select with data from 'data'?

THE SOLUTION BY ADEON IS:

var data = JSON.parse(response);
        console.log(data);

    var select = document.getElementById('activity_2');

    for (var i = 0; i < data.data.length; i++) {
    select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
        }

Body:
Assuming data is an array, you could iterate over it and apply it to the DOM like so.

var optionString = '';
var data = ['John', 'Josh'];

data.forEach(function(dataItem, index){
  optionString += '<option value="' + index + '">' + dataItem + '</option>';
});

$('#activity_2').append(optionString);

Here is a working jsfiddle:
https://jsfiddle.net/9ke5fzqo/


问:
How to create a sub array from another array in Java?
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

```<code>methodName(object array, int start, int end)
</code>```

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

```<code>import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}
</code>```

答:
The code is correct so I'm guessing that you are using an older JDK.  The javadoc for that method says it has been there since 1.6.  At the command line type:

```<code>java -version
</code>```

I'm guessing that you are not running 1.6

Body:
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

methodName(object array, int start, int end)

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}

Body:
The code is correct so I'm guessing that you are using an older JDK.  The javadoc for that method says it has been there since 1.6.  At the command line type:

java -version

I'm guessing that you are not running 1.6


问:
Is it possible to list installed certificates on Firefox?
I need to get/list all certificates installed on Mozilla Firefox. I would like to know if is possible to manager it with Selenium webdriver.

I've found this answer and the file where the certificates are stored in:

%appdata%/Mozilla/Firefox/<user.profile>/cert8.db
```

But I can't parse this file format. So, is possible to get all certificates installed on Firefox using Selenium?

答:
You can use the Mozilla's certutil tool to read the database. Beware that if you run certutil in the command prompt you will be running a Windows certutil, not Mozilla's.

To run Mozilla's certutil you will need to download Network Security Services (NSS) from their repository, here:

https://ftp.mozilla.org/pub/security/nss/releases/

But NSS package requires NSPR dll's to run properly. Not sure why from NSPR v4.6.2 ahead all packages are only source packages, without the required dll's, so go straight to the v4.6.1 link and download the missing dll's zipped.

http://ftp.mozilla.org/pub/nspr/releases/v4.6.1/

Once you put certutil.exe and dll's together in the same folder run the following command:

```<code>certutil.exe -L -d %appdata%\Mozilla\Firefox\Profiles\<profile_folder_name_here>
</code>```

Where:

-L: lists all certificates

-d: Specify the database directory containing the certificate and key database files

For additional certutil commands see here:

https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil

A Python script example is like this:

```<code>import subprocess
import os

ff_prof_path = '{}\\Mozilla\\Firefox\\Profiles\\'.format(os.environ['APPDATA'])
ff_prof_path = '{}{}'.format(ff_prof_path, os.listdir(ff_prof_path)[0])
result = subprocess.run('certutil -L -d {}'.format(ff_prof_path), stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))
</code>```

Body:
I need to get/list all certificates installed on Mozilla Firefox. I would like to know if is possible to manager it with Selenium webdriver.

I've found this answer and the file where the certificates are stored in:

%appdata%/Mozilla/Firefox/<user.profile>/cert8.db

But I can't parse this file format. So, is possible to get all certificates installed on Firefox using Selenium?

Body:
You can use the Mozilla's certutil tool to read the database. Beware that if you run certutil in the command prompt you will be running a Windows certutil, not Mozilla's.

To run Mozilla's certutil you will need to download Network Security Services (NSS) from their repository, here:

https://ftp.mozilla.org/pub/security/nss/releases/

But NSS package requires NSPR dll's to run properly. Not sure why from NSPR v4.6.2 ahead all packages are only source packages, without the required dll's, so go straight to the v4.6.1 link and download the missing dll's zipped.

http://ftp.mozilla.org/pub/nspr/releases/v4.6.1/

Once you put certutil.exe and dll's together in the same folder run the following command:

certutil.exe -L -d %appdata%\Mozilla\Firefox\Profiles\<profile_folder_name_here>

Where:

-L: lists all certificates

-d: Specify the database directory containing the certificate and key database files

For additional certutil commands see here:

https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil

A Python script example is like this:

import subprocess
import os

ff_prof_path = '{}\\Mozilla\\Firefox\\Profiles\\'.format(os.environ['APPDATA'])
ff_prof_path = '{}{}'.format(ff_prof_path, os.listdir(ff_prof_path)[0])
result = subprocess.run('certutil -L -d {}'.format(ff_prof_path), stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))


答:
You should use add method which accepts as parameter a new Option.

The constructor of Option looks like this: new Option(text,value).

var array=[{
            "text":"text1",
            "value":"value1"
          },{
            "text":"text2",
            "value":"value2"
          }];
var select = document.getElementById('activity_2');
array.forEach(function(item){
  select.add(new Option(item.text,item.value));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="activity_2" name="activity_2"></code>```

Title: jquery how to fill select option in my form

Body:
You should use add method which accepts as parameter a new Option.

The constructor of Option looks like this: new Option(text,value).

var array=[{
            "text":"text1",
            "value":"value1"
          },{
            "text":"text2",
            "value":"value2"
          }];
var select = document.getElementById('activity_2');
array.forEach(function(item){
  select.add(new Option(item.text,item.value));
});

<select id="activity_2" name="activity_2">


问:
Recent comment for joomla 3.5
After a lot of struggle, upgraded my joomla 1.5 to 3.5. But the old site had a recent comment section which was actually not working with SEF url.
After upgrade, I can not find any such module by searching two days in google. So I am here as the last option.

Can anyone help me by suggesting any way to create a code for this? It should work with SEF and url rewrite.

答: you need to modify router.php to make your extension compatible with SEF URLs</p>

Title: Recent comment for joomla 3.5


问:
Why does my code fail on this SIMPLE exercise?
I am doing a coding exercise:

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example

For sequence = [1, 3, 2, 1], the output should be
false;

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2], the output should be
true;

You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

.

So I wrote this code:

```<code>def almostIncreasingSequence(sequence):
    first_list, second_list = [x for x in sequence], [x for x in sequence]
    for i in range(len(sequence)-1):
        if sequence[i] >= sequence[i+1]:
            first_list.remove(sequence[i])
            second_list.remove(sequence[i+1])
            break

    if first_list == sorted(set(first_list)) or second_list == sorted(set(second_list)):
        return True
    else:
        return False
</code>```

The code passes 13/15 tests.

Below are the 2 inputs that my code fails on:

```<code>[1, 2, 3, 4, 3, 6]

[3, 5, 67, 98, 3]
</code>```

Both inputs should return True but my code returns False. Any thoughts?

答:
Take your first list, [1, 2, 3, 4, 3, 6]. Once you run the for loop over first_list and second_list, the values of those variables are:

```<code>In [9]: first_list
Out[9]: [1, 2, 3, 3, 6]

In [10]: second_list
Out[10]: [1, 2, 4, 3, 6]
</code>```

The first part of the if is False because:

```<code>In [12]: sorted(set(first_list))
Out[12]: [1, 2, 3, 6]
</code>```

By putting the list into a set, you've lost one of the 3's.

The second part of the if is False because second_list is not sorted.

So, both parts of the if statement are False, and your function returns False.

Body:
I am doing a coding exercise:

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example

For sequence = [1, 3, 2, 1], the output should be
false;

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2], the output should be
true;

You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

.

So I wrote this code:

def almostIncreasingSequence(sequence):
    first_list, second_list = [x for x in sequence], [x for x in sequence]
    for i in range(len(sequence)-1):
        if sequence[i] >= sequence[i+1]:
            first_list.remove(sequence[i])
            second_list.remove(sequence[i+1])
            break

    if first_list == sorted(set(first_list)) or second_list == sorted(set(second_list)):
        return True
    else:
        return False

The code passes 13/15 tests.

Below are the 2 inputs that my code fails on:

[1, 2, 3, 4, 3, 6]

[3, 5, 67, 98, 3]

Both inputs should return True but my code returns False. Any thoughts?

Body:
Take your first list, [1, 2, 3, 4, 3, 6]. Once you run the for loop over first_list and second_list, the values of those variables are:

In [9]: first_list
Out[9]: [1, 2, 3, 3, 6]

In [10]: second_list
Out[10]: [1, 2, 4, 3, 6]

The first part of the if is False because:

In [12]: sorted(set(first_list))
Out[12]: [1, 2, 3, 6]

By putting the list into a set, you've lost one of the 3's.

The second part of the if is False because second_list is not sorted.

So, both parts of the if statement are False, and your function returns False.


问:
Converting into date-time format in pandas?
I need help converting into python/pandas date time format. For example, my times are saved like the following line:

```<code>2017-01-01 05:30:24.468911+00:00
.....
2017-05-05 01:51:31.351718+00:00
</code>```

and I want to know the simplest way to convert this into date time format for essentially performing operations with time (like what is the range in days of my dataset to split up my dataset into chunks by time, what's the time difference from one time to another)? I don't mind losing some of the significance for the times if that makes things easier. Thank you so much!

答:
Timestamp will convert it for you.

```<code>>>> pd.Timestamp('2017-01-01 05:30:24.468911+00:00')
Timestamp('2017-01-01 05:30:24.468911+0000', tz='UTC')
</code>```

Let's say you have a dataframe that includes your timestamp column (let's call it stamp).  You can use apply on that column together with Timestamp:

```<code>df = pd.DataFrame(
    {'stamp': ['2017-01-01 05:30:24.468911+00:00',
               '2017-05-05 01:51:31.351718+00:00']})
>>> df
    stamp
0   2017-01-01 05:30:24.468911+00:00
1   2017-05-05 01:51:31.351718+00:00

>>> df['stamp'].apply(pd.Timestamp)
0   2017-01-01 05:30:24.468911+00:00
1   2017-05-05 01:51:31.351718+00:00
Name: stamp, dtype: datetime64[ns, UTC]
</code>```

You could also use Timeseries:

```<code>>>> pd.TimeSeries(df.stamp)
0    2017-01-01 05:30:24.468911+00:00
1    2017-05-05 01:51:31.351718+00:00
Name: stamp, dtype: object
</code>```

Once you have a Timestamp object, it is pretty efficient to manipulate.  You can just difference their values, for example.

You may also want to have a look at this SO answer which discusses timezone unaware values to aware.

Body:
I need help converting into python/pandas date time format. For example, my times are saved like the following line:

2017-01-01 05:30:24.468911+00:00
.....
2017-05-05 01:51:31.351718+00:00

and I want to know the simplest way to convert this into date time format for essentially performing operations with time (like what is the range in days of my dataset to split up my dataset into chunks by time, what's the time difference from one time to another)? I don't mind losing some of the significance for the times if that makes things easier. Thank you so much!

Body:
Timestamp will convert it for you.

>>> pd.Timestamp('2017-01-01 05:30:24.468911+00:00')
Timestamp('2017-01-01 05:30:24.468911+0000', tz='UTC')

Let's say you have a dataframe that includes your timestamp column (let's call it stamp).  You can use apply on that column together with Timestamp:

df = pd.DataFrame(
    {'stamp': ['2017-01-01 05:30:24.468911+00:00',
               '2017-05-05 01:51:31.351718+00:00']})
>>> df
    stamp
0   2017-01-01 05:30:24.468911+00:00
1   2017-05-05 01:51:31.351718+00:00

>>> df['stamp'].apply(pd.Timestamp)
0   2017-01-01 05:30:24.468911+00:00
1   2017-05-05 01:51:31.351718+00:00
Name: stamp, dtype: datetime64[ns, UTC]

You could also use Timeseries:

>>> pd.TimeSeries(df.stamp)
0    2017-01-01 05:30:24.468911+00:00
1    2017-05-05 01:51:31.351718+00:00
Name: stamp, dtype: object

Once you have a Timestamp object, it is pretty efficient to manipulate.  You can just difference their values, for example.

You may also want to have a look at this SO answer which discusses timezone unaware values to aware.


问:
Why all the Dlls are not loaded in drop down
I have a function like this

```<code> public void SetOperationDropDown()
        {
            cmbOperations.DataSource = PluginManager.GetAllPlugins();

            if(cmbOperations.Items.Count > 0)
            {
                cmbOperations.SelectedItem = cmbOperations.Items[0];
            }
        }
</code>```

This function should get the name of all dlls

```<code>public class PluginManager
{

    /// <summary>
    /// This function gets the name of the plugins and return that in a List<string>.
    /// </summary>
    /// <param name="args"></param>
    /// <returns></returns>
public static List<string> GetAllPlugins()
{

    DirectoryInfo objDirectoryInfo = new DirectoryInfo("Plugins");
    FileInfo[] args = objDirectoryInfo.GetFiles("*.dll");

    List<string> assemblyNames = new List<string>();
    Assembly[] oAssemblies = new Assembly[args.Length];

    for(int assemblyCount = 0;assemblyCount < args.Length;assemblyCount++)
    {
        string executablePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

        oAssemblies[assemblyCount] = Assembly.LoadFile(executablePath.Remove(0,6) + "\\Plugins\\" + args[assemblyCount].Name);

        try
        {
            foreach(Type oType in oAssemblies[assemblyCount].GetTypes())
            {
                // Check whether class is inheriting from IMFDBAnalyserPlugin.
                if(oType.GetInterface("IMFDBAnalyserPlugin") == typeof(IMFDBAnalyserPlugin))
                {
                    assemblyNames.Add(args[assemblyCount].Name.Substring(args[assemblyCount].Name.LastIndexOf("\\") + 1));
                }
            }
        }
        catch(Exception ex)
        {
            EventLog log = new EventLog("Application");
            log.Source = "MFDBAnalyser";
            log.WriteEntry(ex.Message);
        }
    }

    // Passing data one application domain to another.
    AppDomain.CurrentDomain.SetData("AssemblyNames", assemblyNames.ToArray());
    return assemblyNames;
}
</code>```

and should be populated in the drop down when returned here

```<code>        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.

  string assemblyName = Convert.ToString(cmbOperations.SelectedValue);
    Assembly assembly = Assembly.LoadFrom(assemblyName);

    int fileExtensionPos = assemblyName.LastIndexOf(".");
    string fileName = assemblyName.Substring(0, fileExtensionPos);

    Type localType = assembly.GetType(fileName + "." + fileName);
</code>```

But it is not getting every dlls created from this way

```<code> Type localType = assembly.GetType(fileName + "." + fileName);
</code>```

I need to load the complete list of dlls in the drop down.

Where I am going wrong???

答:
Do you know where it doesn't work? Does the "args" variable contain anything? I suspect your problem is the way you build paths. You should be using the Path class, not string operations.

To get the current executable directory:

```<code>string executablePath = Path.GetDirectoryName(Application.ExecutablePath);
</code>```

You should use that to build your DirectoryInfo at the beginning of the GetAllPlugins() method too.
To build a path with a subfolder:

```<code>string pluginPath = Path.Combine(executablePath, "Plugin");
</code>```

To get all files in the plugin subdirectory that have the dll extension:

```<code>string[] pluginFiles = Directory.GetFiles(pluginPath, "*.dll");
</code>```

Note that the filenames returned contain the whole path. You don't need to append anything:

```<code>foreach (string fileName in pluginFiles)
{
    Assembly assembly = Assembly.LoadFrom(fileName);
    List<Type> types = assembly.GetTypes().ToList();
    foreach (Type type in types.FindAll(t => t.GetInterface("IMFDBAnalyserPlugin") != null)
    {
        ...
    }
}
</code>```

should work.

Also, don't use substring, if you want the file names, with or without extension, you should use Path.GetFileName or Path.GetFileNameWithoutExtension.

And use this method to instantiate your plugin:
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

Body:
I have a function like this

 public void SetOperationDropDown()
        {
            cmbOperations.DataSource = PluginManager.GetAllPlugins();

            if(cmbOperations.Items.Count > 0)
            {
                cmbOperations.SelectedItem = cmbOperations.Items[0];
            }
        }

This function should get the name of all dlls

public class PluginManager
{

    ///
    /// This function gets the name of the plugins and return that in a List<string>.
    ///
    /// <param name="args"></param>
    /// <returns></returns>
public static List<string> GetAllPlugins()
{

    DirectoryInfo objDirectoryInfo = new DirectoryInfo("Plugins");
    FileInfo[] args = objDirectoryInfo.GetFiles("*.dll");

    List<string> assemblyNames = new List<string>();
    Assembly[] oAssemblies = new Assembly[args.Length];

    for(int assemblyCount = 0;assemblyCount < args.Length;assemblyCount++)
    {
        string executablePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

        oAssemblies[assemblyCount] = Assembly.LoadFile(executablePath.Remove(0,6) + "\\Plugins\\" + args[assemblyCount].Name);

        try
        {
            foreach(Type oType in oAssemblies[assemblyCount].GetTypes())
            {
                // Check whether class is inheriting from IMFDBAnalyserPlugin.
                if(oType.GetInterface("IMFDBAnalyserPlugin") == typeof(IMFDBAnalyserPlugin))
                {
                    assemblyNames.Add(args[assemblyCount].Name.Substring(args[assemblyCount].Name.LastIndexOf("\\") + 1));
                }
            }
        }
        catch(Exception ex)
        {
            EventLog log = new EventLog("Application");
            log.Source = "MFDBAnalyser";
            log.WriteEntry(ex.Message);
        }
    }

    // Passing data one application domain to another.
    AppDomain.CurrentDomain.SetData("AssemblyNames", assemblyNames.ToArray());
    return assemblyNames;
}

and should be populated in the drop down when returned here

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.

  string assemblyName = Convert.ToString(cmbOperations.SelectedValue);
    Assembly assembly = Assembly.LoadFrom(assemblyName);

    int fileExtensionPos = assemblyName.LastIndexOf(".");
    string fileName = assemblyName.Substring(0, fileExtensionPos);

    Type localType = assembly.GetType(fileName + "." + fileName);

But it is not getting every dlls created from this way

 Type localType = assembly.GetType(fileName + "." + fileName);

I need to load the complete list of dlls in the drop down.

Where I am going wrong???

Body:
Do you know where it doesn't work? Does the "args" variable contain anything? I suspect your problem is the way you build paths. You should be using the Path class, not string operations.

To get the current executable directory:

string executablePath = Path.GetDirectoryName(Application.ExecutablePath);

You should use that to build your DirectoryInfo at the beginning of the GetAllPlugins() method too.
To build a path with a subfolder:

string pluginPath = Path.Combine(executablePath, "Plugin");

To get all files in the plugin subdirectory that have the dll extension:

string[] pluginFiles = Directory.GetFiles(pluginPath, "*.dll");

Note that the filenames returned contain the whole path. You don't need to append anything:

foreach (string fileName in pluginFiles)
{
    Assembly assembly = Assembly.LoadFrom(fileName);
    List<Type> types = assembly.GetTypes().ToList();
    foreach (Type type in types.FindAll(t => t.GetInterface("IMFDBAnalyserPlugin") != null)
    {
        ...
    }
}

should work.

Also, don't use substring, if you want the file names, with or without extension, you should use Path.GetFileName or Path.GetFileNameWithoutExtension.

And use this method to instantiate your plugin:
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx


问:
Display coach marks view when user launches app for the first time Swift 3
I need to launch a coach marks/tutorial view over a tableview when the user launches the app for the first time. The coach marks will never display again, unless the user deletes and reinstalls the app.

I scoured the internet, but was unable to find a simple solution. Oh, I'm fairly new to Swift, so please be gentle. :)

EDIT:
Here is the what I used. Works great!

```<code>  override func viewDidAppear(_ animated: Bool) {
        if !UserDefaults.standard.bool(forKey: "isSecondTime") {
            let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
            if launchedBefore  {
                print("Not the first launch.")
            } else {
                let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CoachMarksViewController")
                self.present(VC, animated: true, completion: nil)
                print("This the first launch.")
                UserDefaults.standard.set(true, forKey: "isSecondTime")
            }

        }
}
</code>```

答:
You should use this little launches manager :)

```<code>enum AppLaunchManager {

    // MARK: - Private Attributes
    private static let launchesCountKey = "LaunchesCount"

    // MARK: Public Enum Methods
    static func launchesCount() -> Int {
        guard let launched = UserDefaults.standard.value(forKey: launchesCountKey) as? Int else {
            return 0
        }
        return launched
    }

    static func registerLaunch() {
        UserDefaults.standard.setValue(launchesCount() + 1, forKey: launchesCountKey)
    }

    static func isFirstLaunch() -> Bool {
        return launchesCount() <= 1
    }
}
</code>```

And in AppDelegate:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    AppLaunchManager.registerLaunch()
    return true
}
</code>```

Then, whenever you need just use:

```<code>if AppLaunchManager.isFirstLaunch() {
    /* do whatever you need */
}
</code>```

Body:
I need to launch a coach marks/tutorial view over a tableview when the user launches the app for the first time. The coach marks will never display again, unless the user deletes and reinstalls the app.

I scoured the internet, but was unable to find a simple solution. Oh, I'm fairly new to Swift, so please be gentle. :)

EDIT:
Here is the what I used. Works great!

  override func viewDidAppear(_ animated: Bool) {
        if !UserDefaults.standard.bool(forKey: "isSecondTime") {
            let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
            if launchedBefore  {
                print("Not the first launch.")
            } else {
                let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CoachMarksViewController")
                self.present(VC, animated: true, completion: nil)
                print("This the first launch.")
                UserDefaults.standard.set(true, forKey: "isSecondTime")
            }

        }
}

Body:
You should use this little launches manager :)

enum AppLaunchManager {

    // MARK: - Private Attributes
    private static let launchesCountKey = "LaunchesCount"

    // MARK: Public Enum Methods
    static func launchesCount() -> Int {
        guard let launched = UserDefaults.standard.value(forKey: launchesCountKey) as? Int else {
            return 0
        }
        return launched
    }

    static func registerLaunch() {
        UserDefaults.standard.setValue(launchesCount() + 1, forKey: launchesCountKey)
    }

    static func isFirstLaunch() -> Bool {
        return launchesCount() <= 1
    }
}

And in AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    AppLaunchManager.registerLaunch()
    return true
}

Then, whenever you need just use:

if AppLaunchManager.isFirstLaunch() {
    /* do whatever you need */
}


问:
How to build .lib files using Code::Blocks IDE
I have a C project which I would like to build as a static library and not as a executable.

My high level environment is:

IDE: Code::Blocks 16.01

Operating System: Windows 7

Compiler: MinGW    (GCC port for Windows)

As a build target option, I select static library (instead of executable) and select build.

Seems to work fine. Problem is, the output is a .a file (which I understand is the Unix/Linux format) and not the windows format of .lib.

Any hints on where I can look to solve this?

答: Its all good dont worry you built a static library MinGW gives .a files on windows too </p>


问:
Spring Integration is consuming more memory all the time
We have a Spring Boot app, with a Spring Integration context, consuming from ActiveMQ queues.

Without messages in the queues it's consuming more and more memory, and after several hours we always run out of memory.

It doesnt seem to do anything, but memory consumed ( heap ) is increasing constantly at a small pace.

How can we avoid this or at least profile this ?

答:
Are you sure that your code is not producing memory leaks?
If you connect to your app via Java VisualVM and see a picture like this:

It's 100% that you have the exactly memory leak and this is not Spring or Java problem ;).

I can advise you read this useful articles how to debug such problems and after that investigate your app:

https://www.toptal.com/java/hunting-memory-leaks-in-java

https://www.dynatrace.com/resources/ebooks/javabook/memory-leaks/

https://dzone.com/articles/memory-leak-andjava-code

https://blogs.sourceallies.com/2011/07/debugging-memory-leaks-with-visualvm/

http://blog.rejeev.com/2009/04/analyzing-memory-leak-in-java.html


问:
OneSignal dont send notification to specific device
I want send notification to specific user, i can get the id but when i try to send a notification to these id doesn't work.
In android does not send either success or error notification, and ios send a "index.html null" notification.

The notifications arrive the same device from where I send them, none arrives at the device where I want to send them.

this is app.component.js:

```<code>let notificationOpenedCallback = function(jsonData) {
        let alert =alertCtrl.create({
          title: jsonData.notification.payload.title,
          subTitle: jsonData.notification.payload.body,
          buttons: ['OK']
        });
        alert.present();
        console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
      };

      window["plugins"].OneSignal
        .startInit("05d411f4-45da-4101-92a5-4a60e5c9fd03", "49543248748")
        .handleNotificationOpened(notificationOpenedCallback)
        .endInit();
    });
</code>```

and with this code i send de notification

```<code>window['plugins'].OneSignal.getIds(function(ids) {
        let notificationObj = { contents: {"en": "Han hecho un nuevo pedido"},
                                heading: { "en": "Domi-Trustik" },
                                include_player_ids: [this.idadmin]
                          };
    window['plugins'].OneSignal.postNotification(notificationObj,
    function(successResponse) {

      console.log("Notification Post Success:", successResponse);
      alert("enviado:" + JSON.stringify(successResponse));
    },
    function (failedResponse) {
      console.log("Notification Post Failed: ", failedResponse);
      alert("error" + JSON.stringify(failedResponse));
    }
    );
   });
</code>```

Is in Ionic 2

答:
Its de same error of my other onesignal question, the plugin its no work fine for some functions so its better use native ionic version:</p>

```<code>import { OneSignal } from '@ionic-native/onesignal';

constructor(public one: OneSignal)

this.one.getIds().then((ids) => {

                let notificationObj = {
                                        include_player_ids: [this.idadmin],
                                        contents: {en: "Han hecho un nuevo pedido"}};

                      window['plugins'].OneSignal.postNotification(notificationObj,
                      function(successResponse) {

                      console.log("Notification Post Success:", successResponse);
                      alert("enviado:" + JSON.stringify(successResponse));
                      },
                      function (failedResponse) {
                      console.log("Notification Post Failed: ", failedResponse);
                      alert("error" + JSON.stringify(failedResponse));
                      }
                      );

            });
</code>```

Body:
I want send notification to specific user, i can get the id but when i try to send a notification to these id doesn't work.
In android does not send either success or error notification, and ios send a "index.html null" notification.

The notifications arrive the same device from where I send them, none arrives at the device where I want to send them.

this is app.component.js:

let notificationOpenedCallback = function(jsonData) {
        let alert =alertCtrl.create({
          title: jsonData.notification.payload.title,
          subTitle: jsonData.notification.payload.body,
          buttons: ['OK']
        });
        alert.present();
        console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
      };

      window["plugins"].OneSignal
        .startInit("05d411f4-45da-4101-92a5-4a60e5c9fd03", "49543248748")
        .handleNotificationOpened(notificationOpenedCallback)
        .endInit();
    });

and with this code i send de notification

window['plugins'].OneSignal.getIds(function(ids) {
        let notificationObj = { contents: {"en": "Han hecho un nuevo pedido"},
                                heading: { "en": "Domi-Trustik" },
                                include_player_ids: [this.idadmin]
                          };
    window['plugins'].OneSignal.postNotification(notificationObj,
    function(successResponse) {

      console.log("Notification Post Success:", successResponse);
      alert("enviado:" + JSON.stringify(successResponse));
    },
    function (failedResponse) {
      console.log("Notification Post Failed: ", failedResponse);
      alert("error" + JSON.stringify(failedResponse));
    }
    );
   });

Is in Ionic 2

Body:
Its de same error of my other onesignal question, the plugin its no work fine for some functions so its better use native ionic version:

import { OneSignal } from '@ionic-native/onesignal';

constructor(public one: OneSignal)

this.one.getIds().then((ids) => {

                let notificationObj = {
                                        include_player_ids: [this.idadmin],
                                        contents: {en: "Han hecho un nuevo pedido"}};

                      window['plugins'].OneSignal.postNotification(notificationObj,
                      function(successResponse) {

                      console.log("Notification Post Success:", successResponse);
                      alert("enviado:" + JSON.stringify(successResponse));
                      },
                      function (failedResponse) {
                      console.log("Notification Post Failed: ", failedResponse);
                      alert("error" + JSON.stringify(failedResponse));
                      }
                      );

            });


问:
Rails 3 adding fields to a table
ok i am a noob and i want to know how to add fields to a migration in rails 3, additionally i am using Typus and would like to know if i need to add these fields manually or can i just regenerate the typus and it will just pick the new fields up?

Thanks in advance

Robbie

答:
Migrations are used to add fields to the database, not tell Rails about fields.

Rails will actually inspect the table for its fields, so if you have an existing table, you can create a model called spy.rb and it will know about all fields in spies

To use migrations, run rails generate migration AddScreenshotColumns. Then that file can become:

```<code>class AddScreenshotColumnsToTemplate < ActiveRecord::Migration
  def self.up
    add_column :templates, :screenshot_file_name,    :string
  end

  def self.down
    remove_column :templates, :screenshot_file_name
  end
end
</code>```

Title: Rails 3 adding fields to a table

Body:
Migrations are used to add fields to the database, not tell Rails about fields.

Rails will actually inspect the table for its fields, so if you have an existing table, you can create a model called spy.rb and it will know about all fields in spies

To use migrations, run rails generate migration AddScreenshotColumns. Then that file can become:

class AddScreenshotColumnsToTemplate < ActiveRecord::Migration
  def self.up
    add_column :templates, :screenshot_file_name,    :string
  end

  def self.down
    remove_column :templates, :screenshot_file_name
  end
end


问:
Vue.js - Element UI - Dynamic rules validation form
I'm using vue-js2.3 and element-ui.

I would like to define the validation rules of my form dynamically

Example

https://jsfiddle.net/cgL6y9kq/

Problem

The required is not dynamically defined by phoneMandatory

Questions

How can I change the attribute on an existing rule dynamically?
How can I add or remove rules dynamically ?

答:
You have your rules property in the component's data method. This means it will not updated based on changes to other data properties.

You should use a computed property for rules instead:

```<code>computed: {
  rules() {
    return {
      phone: [{
        required: this.phoneMandatory,
        message: 'Please input phone',
        trigger: 'blur'
      }]
    }
  }
},
</code>```

Now, when this.phoneMandatory updates, so will the component's rules property.

Here's a working fiddle.

Body:
You have your rules property in the component's data method. This means it will not updated based on changes to other data properties.

You should use a computed property for rules instead:

computed: {
  rules() {
    return {
      phone: [{
        required: this.phoneMandatory,
        message: 'Please input phone',
        trigger: 'blur'
      }]
    }
  }
},

Now, when this.phoneMandatory updates, so will the component's rules property.

Here's a working fiddle.