问:
add new entry at the bottom of table in SQL Server 2008
```<code>SqlCommand cmd = new SqlCommand("insert into Table Name(Column1,Column2,Column3,) values('" @+value1+,@+value2+,@+value3+ "')", con);
cmd.ExecuteNonQuery();
</code>```

above code is simple format of my db query,when i try to insert record into db the record went to at the top of table instead of bottom,i want to save new entry at bottom not top or middle.

答:
In SQL Server or any SQL database whenever you insert a new record, it is being inserted at the end or the end of the table. If What you are expecting by inserting the record at the beginning is to get the record as the first one while retrieving the same, then you can try ordering them in the descending order - Which is recommended.

Another way of achieving the same is if you have a sequence column in the table then insert the new record with the sequence as the current minimum sequence -1. Something like this.

Create the table with the Sequence column as decrement by 1

```<code>create table MyTable
(
    SeqNo int identity(1000,-1),
    Data1 VARCHAR(50)
)
</code>```

As per the above design, the first record begin inserted into the table will have the SeqNo 1000 and for each record being inserted next will have SeqNo decremented by 1. Like the 2nd one will have SeqNo 999, 3rd one 998 and so on.

But What I recommend is you go with the order by Desc approach if all
  you need is to get the latest record first on your search

Body:
SqlCommand cmd = new SqlCommand("insert into Table Name(Column1,Column2,Column3,) values('" @+value1+,@+value2+,@+value3+ "')", con);
cmd.ExecuteNonQuery();

above code is simple format of my db query,when i try to insert record into db the record went to at the top of table instead of bottom,i want to save new entry at bottom not top or middle.

Body:
In SQL Server or any SQL database whenever you insert a new record, it is being inserted at the end or the end of the table. If What you are expecting by inserting the record at the beginning is to get the record as the first one while retrieving the same, then you can try ordering them in the descending order - Which is recommended.

Another way of achieving the same is if you have a sequence column in the table then insert the new record with the sequence as the current minimum sequence -1. Something like this.

Create the table with the Sequence column as decrement by 1

create table MyTable
(
    SeqNo int identity(1000,-1),
    Data1 VARCHAR(50)
)

As per the above design, the first record begin inserted into the table will have the SeqNo 1000 and for each record being inserted next will have SeqNo decremented by 1. Like the 2nd one will have SeqNo 999, 3rd one 998 and so on.

But What I recommend is you go with the order by Desc approach if all
  you need is to get the latest record first on your search


来源: stackexchange

问:
The import android.app.WallpaperManager cannot be resolved
I can't imagine why it won't let me import this?</p>

答:
Have you made sure that you're targetting a high enough SDK version? The WallpaperManager has only been included since API Level 5. This means your manifest.xml you should have </p>

```<code><uses-sdk android:minSdkVersion="5" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Have you made sure that you're targetting a high enough SDK version? The WallpaperManager has only been included since API Level 5. This means your manifest.xml you should have

<uses-sdk android:minSdkVersion="5" />


问:
Difference in days between two dates one of which is user's input
I am writing an 'age to seconds' converter, but I keep getting various errors.

```<code>#

!/usr/bin/env python3
# -*- coding: utf-8 -*-
#This program converts your age to seconds
from datetime import datetime

print ('Welcome to a simple age to seconds converter. ')

def get_date():
    print ('Please enter the year of your birth in the format YYYY, MM, DD:')
    date_of_birth = str(input())
    converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
    date_now = datetime.strftime("%Y-%m-%d")
    total_seconds = ((date_now - converted_date).days)*86400
    return ('You have lived for:', total_seconds, 'seconds.')

print (get_date())
if __name__ == "__main__":
    main()
</code>```

I think this is the most correct version of the program, but I keep getting an error TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'.

Does anyone know how I can correct that? And also how to count seconds to the precise moment of inputting the date to now?
Thanks in advance

答:
date_now should bedatetime.now(). strftime("%Y-%m-%d") is called on an existing datetime instance and returns a string.

```<code>date_of_birth = input()
converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
date_now = datetime.now()
total_seconds = (date_now - converted_date).days * 24 * 60 * 60
# day: 24 h * 60 min * 60 sec = 86400 != 8640000
print('You have lived for:', total_seconds, 'seconds.')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing an 'age to seconds' converter, but I keep getting various errors.

#

!/usr/bin/env python3
# -*- coding: utf-8 -*-
#This program converts your age to seconds
from datetime import datetime

print ('Welcome to a simple age to seconds converter. ')

def get_date():
    print ('Please enter the year of your birth in the format YYYY, MM, DD:')
    date_of_birth = str(input())
    converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
    date_now = datetime.strftime("%Y-%m-%d")
    total_seconds = ((date_now - converted_date).days)*86400
    return ('You have lived for:', total_seconds, 'seconds.')

print (get_date())
if __name__ == "__main__":
    main()

I think this is the most correct version of the program, but I keep getting an error TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'.

Does anyone know how I can correct that? And also how to count seconds to the precise moment of inputting the date to now?
Thanks in advance

Body:
date_now should bedatetime.now(). strftime("%Y-%m-%d") is called on an existing datetime instance and returns a string.

date_of_birth = input()
converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
date_now = datetime.now()
total_seconds = (date_now - converted_date).days * 24 * 60 * 60
# day: 24 h * 60 min * 60 sec = 86400 != 8640000
print('You have lived for:', total_seconds, 'seconds.')


问:
how to enable button when text field is empty
    this is my code but the problem is the button start enable after the user start to typing
the second prob is i want to change his color too

```<code>     override func viewDidLoad() {
             handleTextField()
        fullname.delegate = self
        username.delegate = self
        email.delegate = self
        password.delegate = self
    }

        func handleTextField(){
                fullname.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                username.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                email.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                password.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
            }
            @objc func textFieldDidChange(){
                guard let username = username.text, !username.isEmpty, let email = email.text, !email.isEmpty, let fullname = fullname.text, !fullname.isEmpty, let password = password.text, !password.isEmpty else {
                    signupBtn.setTitleColor(UIColor.lightText, for: UIControlState.normal)
                    signupBtn.isEnabled = false
                    return
                }
                signupBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
                signupBtn.isEnabled = true
            }
</code>```

答:
You should implement UITextFieldDelegate, like this:

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        fullname.delegate = self
        username.delegate = self
        email.delegate = self
        password.delegate = self

        signupBtn.isEnabled = false
    }

    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
        if reason == .committed {
            //textFieldDidChange()
        }
    }

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == username, let text = textField.text, !text.isEmpty { // your are typing the 2nd textfield
        if let text = fullname.text, !text.isEmpty { // and the 1st textfield filled
            signupBtn.isEnabled = true
            signupBtn.setTitleColor(.green, for: .normal)
        }
    }
    return true
}

    func textFieldDidChange() {
        guard let username = username.text, !username.isEmpty, let email = email.text, !email.isEmpty, let fullname = fullname.text, !fullname.isEmpty, let password = password.text, !password.isEmpty else {
            signupBtn.setTitleColor(UIColor.lightText, for: UIControlState.normal)
            signupBtn.isEnabled = false
            return
        }
        signupBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
        signupBtn.isEnabled = true
    }
</code>```

Body:
    this is my code but the problem is the button start enable after the user start to typing
the second prob is i want to change his color too

     override func viewDidLoad() {
             handleTextField()
        fullname.delegate = self
        username.delegate = self
        email.delegate = self
        password.delegate = self
    }

        func handleTextField(){
                fullname.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                username.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                email.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                password.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
            }
            @objc func textFieldDidChange(){
                guard let username = username.text, !username.isEmpty, let email = email.text, !email.isEmpty, let fullname = fullname.text, !fullname.isEmpty, let password = password.text, !password.isEmpty else {
                    signupBtn.setTitleColor(UIColor.lightText, for: UIControlState.normal)
                    signupBtn.isEnabled = false
                    return
                }
                signupBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
                signupBtn.isEnabled = true
            }

Body:
You should implement UITextFieldDelegate, like this:

override func viewDidLoad() {
        super.viewDidLoad()
        fullname.delegate = self
        username.delegate = self
        email.delegate = self
        password.delegate = self

        signupBtn.isEnabled = false
    }

    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
        if reason == .committed {
            //textFieldDidChange()
        }
    }

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == username, let text = textField.text, !text.isEmpty { // your are typing the 2nd textfield
        if let text = fullname.text, !text.isEmpty { // and the 1st textfield filled
            signupBtn.isEnabled = true
            signupBtn.setTitleColor(.green, for: .normal)
        }
    }
    return true
}

    func textFieldDidChange() {
        guard let username = username.text, !username.isEmpty, let email = email.text, !email.isEmpty, let fullname = fullname.text, !fullname.isEmpty, let password = password.text, !password.isEmpty else {
            signupBtn.setTitleColor(UIColor.lightText, for: UIControlState.normal)
            signupBtn.isEnabled = false
            return
        }
        signupBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
        signupBtn.isEnabled = true
    }


问:
"Paste" string variable in excel VBA instead of the contents of clipboard?
I have a string variable that contains an HTML table in excel VBA. I know that when this table is stored in the clipboard and I invoke .PasteSpecial, Excel does some nifty preprocessing and fills the cells out in the current sheet the same way as they appear in the table.

However, if I simply set the .Value of a cell/range to the string variable, no such preprocessing takes place and the entire string, HTML tags and all, are dumped into the cell. I want the former result, but I cannot use the clipboard because it is being used by this application elsewhere and there is no guarantee I would not overwrite critical data. It is also being used asynchronously so I cannot simply save the current contents of the clipboard, use the clipboard, and then restore the previous contents of the clipboard.

So, is there any way to get the "pasting preprocessing" to occur when setting the value for a range with a formatted string?

答:
This is just a comment (stackeoverflow doesn't let me comment the propper way yet).

You probably could do it the way you want using some API.

A long time ago I played with it (looking for some way to cheat MS Word) and I remember that you could store any content to the clipboard, as long as you enter the right id of the content type (like pure text, formated text, html, etc). After storing the content, you must use the respective API function to paste, again, the right type of content.

I didn't make progress as fast as I expected, and I was short of time, so I abandoned the idea. If you would like to give it a chance, look up MSDN for the API calls (I don't have it here right now, otherwise I would give you right away).

EDIT: I found the code. All the code below should be kept in a module:

```<code>' Clipboard functions:
Private Declare Function OpenClipboard Lib "USER32" (ByVal hWnd As Long) As Long
Private Declare Function CloseClipboard Lib "USER32" () As Long
Private Declare Function GetClipboardData Lib "USER32" (ByVal wFormat As Long) As Long
Private Declare Function IsClipboardFormatAvailable Lib "USER32" (ByVal wFormat As Long) As Long
Private Declare Function RegisterClipboardFormat Lib "USER32" Alias "RegisterClipboardFormatA" (ByVal lpString As String) As Long
' Memory functions:
Private Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function GlobalSize Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)

Public Function GetClipboardIDForCustomFormat(ByVal sName As String) As Long
Dim wFormat As Long
    wFormat = RegisterClipboardFormat(sName & Chr$(0))
    If (wFormat > &HC000&) Then
        GetClipboardIDForCustomFormat = wFormat
    End If
End Function

Public Function GetClipboardDataAsString(ByVal lFormatID As Long) As String
'Public Function GetClipboardDataAsString(ByVal hWndOwner As Long, ByVal lFormatID As Long) As String
Dim bData() As Byte
Dim hMem As Long
Dim lSize As Long
Dim lPtr As Long

    ' Open the clipboard for access:
    If (OpenClipboard(0&)) Then
'    If (OpenClipboard(hWndOwner)) Then
        ' Check if this data format is available:
        If (IsClipboardFormatAvailable(lFormatID) <> 0) Then
            ' Get the memory handle to the data:
            hMem = GetClipboardData(lFormatID)
            If (hMem <> 0) Then
                ' Get the size of this memory block:
                lSize = GlobalSize(hMem)
                If (lSize > 0) Then
                    ' Get a pointer to the memory:
                    lPtr = GlobalLock(hMem)
                    If (lPtr <> 0) Then
                        ' Resize the byte array to hold the data:
                        ReDim bData(0 To lSize - 1) As Byte
                        ' Copy from the pointer into the array:
                        CopyMemory bData(0), ByVal lPtr, lSize
                        ' Unlock the memory block:
                        GlobalUnlock hMem

                        ' Now return the data as a string:
                        GetClipboardDataAsString = StrConv(bData, vbUnicode)

                    End If
                End If
            End If
        End If
        CloseClipboard
    End If
End Function
</code>```

Body:
This is just a comment (stackeoverflow doesn't let me comment the propper way yet).

You probably could do it the way you want using some API.

A long time ago I played with it (looking for some way to cheat MS Word) and I remember that you could store any content to the clipboard, as long as you enter the right id of the content type (like pure text, formated text, html, etc). After storing the content, you must use the respective API function to paste, again, the right type of content.

I didn't make progress as fast as I expected, and I was short of time, so I abandoned the idea. If you would like to give it a chance, look up MSDN for the API calls (I don't have it here right now, otherwise I would give you right away).

EDIT: I found the code. All the code below should be kept in a module:

' Clipboard functions:
Private Declare Function OpenClipboard Lib "USER32" (ByVal hWnd As Long) As Long
Private Declare Function CloseClipboard Lib "USER32" () As Long
Private Declare Function GetClipboardData Lib "USER32" (ByVal wFormat As Long) As Long
Private Declare Function IsClipboardFormatAvailable Lib "USER32" (ByVal wFormat As Long) As Long
Private Declare Function RegisterClipboardFormat Lib "USER32" Alias "RegisterClipboardFormatA" (ByVal lpString As String) As Long
' Memory functions:
Private Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function GlobalSize Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)

Public Function GetClipboardIDForCustomFormat(ByVal sName As String) As Long
Dim wFormat As Long
    wFormat = RegisterClipboardFormat(sName & Chr$(0))
    If (wFormat > &HC000&) Then
        GetClipboardIDForCustomFormat = wFormat
    End If
End Function

Public Function GetClipboardDataAsString(ByVal lFormatID As Long) As String
'Public Function GetClipboardDataAsString(ByVal hWndOwner As Long, ByVal lFormatID As Long) As String
Dim bData() As Byte
Dim hMem As Long
Dim lSize As Long
Dim lPtr As Long

    ' Open the clipboard for access:
    If (OpenClipboard(0&)) Then
'    If (OpenClipboard(hWndOwner)) Then
        ' Check if this data format is available:
        If (IsClipboardFormatAvailable(lFormatID) <> 0) Then
            ' Get the memory handle to the data:
            hMem = GetClipboardData(lFormatID)
            If (hMem <> 0) Then
                ' Get the size of this memory block:
                lSize = GlobalSize(hMem)
                If (lSize > 0) Then
                    ' Get a pointer to the memory:
                    lPtr = GlobalLock(hMem)
                    If (lPtr <> 0) Then
                        ' Resize the byte array to hold the data:
                        ReDim bData(0 To lSize - 1) As Byte
                        ' Copy from the pointer into the array:
                        CopyMemory bData(0), ByVal lPtr, lSize
                        ' Unlock the memory block:
                        GlobalUnlock hMem

                        ' Now return the data as a string:
                        GetClipboardDataAsString = StrConv(bData, vbUnicode)

                    End If
                End If
            End If
        End If
        CloseClipboard
    End If
End Function


问:
Python: character "\u200b" not recognized after freezing with py2app
We work with Sharepoint at my job, and sometimes the character "\u200b", a zero-width character,  gets into our filenames and documents after copying something from Sharepoint.

I made an app with Python 3 and PyQt5 that monitors the clipboard, shows its contents using repr(), and displays a system notification if that character is found in the clipboard contents.

It works fine under Windows, works fine under El Capitan before freezing, but after freezing with py2app, my program shows "?" instead of "\u200b", and so the notification is not shown.  I'm testing in a virtual machine (VirtualBox), if that changes anything.

Is there any way to fix this with py2app, should I be using another freezing program, or should I change my code?

EDIT: I have a text file written in Japanese and I just noticed the same thing happens: before freezing, the Japanese characters are displayed correctly in my app, but after freezing they get converted to "?".

Thread that monitors the clipboard:

```<code>recent_value = ""
while True:
    tmp_value = pyperclip.paste()
    if tmp_value != recent_value:
        recent_value = tmp_value
        self.clip.emit(recent_value)
    time.sleep(0.1)
</code>```

Validation in the app:

```<code>@QtCore.pyqtSlot(str)
def clipboard_slot(self, value):
    real_value = repr(value)[1:][:-1]

    # validation
    if "\\u200b" in real_value:
        self.tray_icon.showMessage("Warning", "Invalid character detected in clipboard contents.")
</code>```

答:
I think you can use unicode string.

"\u200b" must be u"\u200b"

```<code> if u"\\u200b" in real_value:
            self.tray_icon.showMessage("Warning", "Invalid character detected in clipboard contents.")
</code>```

Body:
We work with Sharepoint at my job, and sometimes the character "\u200b", a zero-width character,  gets into our filenames and documents after copying something from Sharepoint.

I made an app with Python 3 and PyQt5 that monitors the clipboard, shows its contents using repr(), and displays a system notification if that character is found in the clipboard contents.

It works fine under Windows, works fine under El Capitan before freezing, but after freezing with py2app, my program shows "?" instead of "\u200b", and so the notification is not shown.  I'm testing in a virtual machine (VirtualBox), if that changes anything.

Is there any way to fix this with py2app, should I be using another freezing program, or should I change my code?

EDIT: I have a text file written in Japanese and I just noticed the same thing happens: before freezing, the Japanese characters are displayed correctly in my app, but after freezing they get converted to "?".

Thread that monitors the clipboard:

recent_value = ""
while True:
    tmp_value = pyperclip.paste()
    if tmp_value != recent_value:
        recent_value = tmp_value
        self.clip.emit(recent_value)
    time.sleep(0.1)

Validation in the app:

@QtCore.pyqtSlot(str)
def clipboard_slot(self, value):
    real_value = repr(value)[1:][:-1]

    # validation
    if "\\u200b" in real_value:
        self.tray_icon.showMessage("Warning", "Invalid character detected in clipboard contents.")

Body:
I think you can use unicode string.

"\u200b" must be u"\u200b"

 if u"\\u200b" in real_value:
            self.tray_icon.showMessage("Warning", "Invalid character detected in clipboard contents.")


问:
Php check if my date from db is today echo with today and if tomorrow then echo tomorrow
How to make a check if datetime from my db is today and then echo with "today" and if my datetime is tomorrow echo with tomorrow. I want to make this for a date reminder for fullcalendar.

My Php code is not working or is messed:

```<code>$reminder = date('d-M-Y',strtotime(date("d-m-Y", strtotime($row['start'])) . " +0 days"));
$tomorrow = strtotime("+1 day");
$tomorrow = getdate($tomorrow);

if($reminder = "0 Days") {
    echo "Today";
} else if($reminder = "1 Days" ) {
    echo "Tomorrow";
} else {
    echo (strtotime($reminder) - strtotime(date('d-M-Y'))) / (60 * 60 * 24).' Days';
}
</code>```

答:
```<code><?php

$date='14-Nov-2017';
$time = strtotime($date);
$formatDate = date('Y-m-d',$time);
echo $formatDate;
$today=date("Y-m-d");

if($formatDate==date("Y-m-d")){
    echo "TODAY";
}
else if ($formatDate==date('Y-m-d', strtotime($today. ' +1 days'))){
    echo 'TOMORROW';
}
else{
    echo "Another day";
}
</code>```

This code get's the date you output , and compares it with todays date , tomorrows date otherwise just echos another date. Tested and it works also.

Body:
How to make a check if datetime from my db is today and then echo with "today" and if my datetime is tomorrow echo with tomorrow. I want to make this for a date reminder for fullcalendar.

My Php code is not working or is messed:

$reminder = date('d-M-Y',strtotime(date("d-m-Y", strtotime($row['start'])) . " +0 days"));
$tomorrow = strtotime("+1 day");
$tomorrow = getdate($tomorrow);

if($reminder = "0 Days") {
    echo "Today";
} else if($reminder = "1 Days" ) {
    echo "Tomorrow";
} else {
    echo (strtotime($reminder) - strtotime(date('d-M-Y'))) / (60 * 60 * 24).' Days';
}

Body:
<?php

$date='14-Nov-2017';
$time = strtotime($date);
$formatDate = date('Y-m-d',$time);
echo $formatDate;
$today=date("Y-m-d");

if($formatDate==date("Y-m-d")){
    echo "TODAY";
}
else if ($formatDate==date('Y-m-d', strtotime($today. ' +1 days'))){
    echo 'TOMORROW';
}
else{
    echo "Another day";
}

This code get's the date you output , and compares it with todays date , tomorrows date otherwise just echos another date. Tested and it works also.


问:
How to do that Mongodb aggregation in golang
I have a MongoDB collection like this:

```<code>{ "_id" : ObjectId("5a017ee061313781045889ea"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }
{ "_id" : ObjectId("5a017f7b61313781045889eb"),  "device_id" : "1111",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : ObjectId("5a017fdd61313781045889ec"),  "device_id" : "12222",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : ObjectId("5a017ff561313781045889ed"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:42:13.658Z") }
</code>```

I want to distinct it by "device_id" AND sort it by "pubtime".

I know that Golang could use pipe to do it. But I don't know how to do it. What I tried:

```<code>o1 := bson.M{"_id": bson.M{"device_id": "$device_id"}}

o2 := bson.M{"pubtime": bson.M{"$last": "$pubtime"}}
o3 := bson.M{"$group": []bson.M{o1, o2}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
_ = pipe.All(&result)
fmt.Println(result)
</code>```

The result is empty.

It is ok in MongoDB:

```<code>db.collections.aggregate({"$group":
                        {"_id":{"device_id":"$device_id"},
                        "pubtime":{"$last": "$pubtime"} ,
                       "value":{"$last": "$value"} ,
                        }});
</code>```

答:
You're not checking the errors, that's your main problem. Pipe.All() returns an error which you gracefully discard. Don't do that.

```<code>var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)
</code>```

This will print:

```<code>[] a group's fields must be specified in an object
</code>```

The error says it all. The value of $group must be e.g. a bson.M value, and not a slice of bson.M:

```<code>o3 := bson.M{"$group": bson.M{
    "_id":     bson.M{"device_id": "$device_id"},
    "pubtime": bson.M{"$last": "$pubtime"},
}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)
</code>```

Now the output will be:

[map[_id:map[device_id:12222] pubtime:2017-11-07 10:41:49.452 +0100 CET] map[_id:map[device_id:1111] pubtime:2017-11-07 10:40:11.204 +0100 CET] map[_id:map[device_id:1232213] pubtime:2017-11-07 10:42:13.658 +0100 CET]] <nil>

So it works.

And to make the results sorted by pubtime, use $sort. Here's the final code:

```<code>pipe := c.Pipe([]bson.M{
    {
        "$group": bson.M{
            "_id":     bson.M{"device_id": "$device_id"},
            "pubtime": bson.M{"$last": "$pubtime"},
        },
    },
    {"$sort": bson.M{"pubtime": 1}},
})
var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)
</code>```

If you want the results sorted in descending order, then use:

```<code>{"$sort": bson.M{"pubtime": -1}}
</code>```

Also note that when grouping, if the group _id is a single field, you don't need to wrap it into an object, you can simply use $device_id as the group id:

```<code>"$group": bson.M{
    "_id":     "$device_id",
    "pubtime": bson.M{"$last": "$pubtime"},
},
</code>```

Body:
I have a MongoDB collection like this:

{ "_id" : ObjectId("5a017ee061313781045889ea"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }
{ "_id" : ObjectId("5a017f7b61313781045889eb"),  "device_id" : "1111",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : ObjectId("5a017fdd61313781045889ec"),  "device_id" : "12222",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : ObjectId("5a017ff561313781045889ed"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:42:13.658Z") }

I want to distinct it by "device_id" AND sort it by "pubtime".

I know that Golang could use pipe to do it. But I don't know how to do it. What I tried:

o1 := bson.M{"_id": bson.M{"device_id": "$device_id"}}

o2 := bson.M{"pubtime": bson.M{"$last": "$pubtime"}}
o3 := bson.M{"$group": []bson.M{o1, o2}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
_ = pipe.All(&result)
fmt.Println(result)

The result is empty.

It is ok in MongoDB:

db.collections.aggregate({"$group":
                        {"_id":{"device_id":"$device_id"},
                        "pubtime":{"$last": "$pubtime"} ,
                       "value":{"$last": "$value"} ,
                        }});

Body:
You're not checking the errors, that's your main problem. Pipe.All() returns an error which you gracefully discard. Don't do that.

var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)

This will print:

[] a group's fields must be specified in an object

The error says it all. The value of $group must be e.g. a bson.M value, and not a slice of bson.M:

o3 := bson.M{"$group": bson.M{
    "_id":     bson.M{"device_id": "$device_id"},
    "pubtime": bson.M{"$last": "$pubtime"},
}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)

Now the output will be:

[map[_id:map[device_id:12222] pubtime:2017-11-07 10:41:49.452 +0100 CET] map[_id:map[device_id:1111] pubtime:2017-11-07 10:40:11.204 +0100 CET] map[_id:map[device_id:1232213] pubtime:2017-11-07 10:42:13.658 +0100 CET]] <nil>

So it works.

And to make the results sorted by pubtime, use $sort. Here's the final code:

pipe := c.Pipe([]bson.M{
    {
        "$group": bson.M{
            "_id":     bson.M{"device_id": "$device_id"},
            "pubtime": bson.M{"$last": "$pubtime"},
        },
    },
    {"$sort": bson.M{"pubtime": 1}},
})
var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)

If you want the results sorted in descending order, then use:

{"$sort": bson.M{"pubtime": -1}}

Also note that when grouping, if the group _id is a single field, you don't need to wrap it into an object, you can simply use $device_id as the group id:

"$group": bson.M{
    "_id":     "$device_id",
    "pubtime": bson.M{"$last": "$pubtime"},
},


问:
What is the propper way to use Python emcee in Julia
I want to use Python's emcee in Julia, so after a little research I found PyCall, then according to their documentation I had to use

```<code>using PyCall
@pyimport emcee
</code>```

But I got this error

ERROR: PyError (ccall(@pysym(:PyImport_ImportModule), PyPtr, (Cstring,), name)

The Python package emcee could not be found by pyimport. Usually this means
that you did not install emcee in the Python version being used by PyCall.
PyCall is currently configured to use the Julia-specific Python distribution
installed by the Conda.jl package.  To install the emcee module, you can
use pyimport_conda("emcee", PKG), where PKG is the Anaconda
package the contains the module emcee, or alternatively you can use the
Conda package directly (via using Conda followed by Conda.add etcetera).

Alternatively, if you want to use a different Python distribution on your
system, such as a system-wide Python (as opposed to the Julia-specific Python),
you can re-configure PyCall with that Python.   As explained in the PyCall
documentation, set ENV["PYTHON"] to the path/name of the python executable
you want to use, run Pkg.build("PyCall"), and re-launch Julia.

)
ImportError('No module named emcee',)

So I found the directory where emcee is installed (/Users/Angel/anaconda/lib/python2.7) and I ran the command:

```<code>pyimport_conda("emcee","/Users/Angel/anaconda/lib/python2.7")
</code>```

But I still get errors, this time

PackageNotFoundError: Packages missing in current channels:

/users/angel/anaconda/lib/python2.7

We have searched for the packages in the following channels:

https://repo.continuum.io/pkgs/main/osx-64

https://repo.continuum.io/pkgs/main/noarch

https://repo.continuum.io/pkgs/free/osx-64

https://repo.continuum.io/pkgs/free/noarch

https://repo.continuum.io/pkgs/r/osx-64

https://repo.continuum.io/pkgs/r/noarch

https://repo.continuum.io/pkgs/pro/osx-64

https://repo.continuum.io/pkgs/pro/noarch

https://conda.anaconda.org/anaconda-fusion/osx-64

https://conda.anaconda.org/anaconda-fusion/noarch

So, what I'm doing wrong?

答:
Do pip install <pkg> with the Python distribution used by Julia.
Not all python packages can be installed using conda. For Windows/Linux/Mac x32,x64 check here: https://docs.anaconda.com/anaconda/packages/pkg-docs
@pyimport emcee worked for me with no errors

Body:
I want to use Python's emcee in Julia, so after a little research I found PyCall, then according to their documentation I had to use

using PyCall
@pyimport emcee

But I got this error

ERROR: PyError (ccall(@pysym(:PyImport_ImportModule), PyPtr, (Cstring,), name)

The Python package emcee could not be found by pyimport. Usually this means
that you did not install emcee in the Python version being used by PyCall.
PyCall is currently configured to use the Julia-specific Python distribution
installed by the Conda.jl package.  To install the emcee module, you can
use pyimport_conda("emcee", PKG), where PKG is the Anaconda
package the contains the module emcee, or alternatively you can use the
Conda package directly (via using Conda followed by Conda.add etcetera).

Alternatively, if you want to use a different Python distribution on your
system, such as a system-wide Python (as opposed to the Julia-specific Python),
you can re-configure PyCall with that Python.   As explained in the PyCall
documentation, set ENV["PYTHON"] to the path/name of the python executable
you want to use, run Pkg.build("PyCall"), and re-launch Julia.

)
ImportError('No module named emcee',)

So I found the directory where emcee is installed (/Users/Angel/anaconda/lib/python2.7) and I ran the command:

pyimport_conda("emcee","/Users/Angel/anaconda/lib/python2.7")

But I still get errors, this time

PackageNotFoundError: Packages missing in current channels:

/users/angel/anaconda/lib/python2.7

We have searched for the packages in the following channels:

https://repo.continuum.io/pkgs/main/osx-64

https://repo.continuum.io/pkgs/main/noarch

https://repo.continuum.io/pkgs/free/osx-64

https://repo.continuum.io/pkgs/free/noarch

https://repo.continuum.io/pkgs/r/osx-64

https://repo.continuum.io/pkgs/r/noarch

https://repo.continuum.io/pkgs/pro/osx-64

https://repo.continuum.io/pkgs/pro/noarch

https://conda.anaconda.org/anaconda-fusion/osx-64

https://conda.anaconda.org/anaconda-fusion/noarch

So, what I'm doing wrong?


问:
How to merge one XML file with data into one big text file using XSLT
My XML looks like this:

```<code><NewDataSet>
  <Table>
    <Column1>"Date = "2017/11/10", ImageType = "A", Doctype = "ABC", DOCTYPE_DESCR = "ABC data file", Total = "2"</Column1>
  </Table>
  <Table>
    <Column1>"Date = "2017/11/10", ImageType = "b", Doctype = "DEF", DOCTYPE_DESCR = "DEF chart file", Total = "2"</Column1>
  </Table>
  <Table>
    <Column1>"Date = "2017/11/10", ImageType = "C", Doctype = "HIJ", DOCTYPE_DESCR = "HIJ PDF ", Total = "2"</Column1>
  </Table>
  <Table>
    <Column1>"Date = "2017/11/10", ImageType = "d", Doctype = "KLM", DOCTYPE_DESCR = "KLM file.", Total = "1"</Column1>
  </Table>
</NewDataSet>
</code>```

Here's my desired output text file. Currently, my program is outputting individual text files rather than one single text files with the multiple results. Any help is greatly appreciated.

```<code>"Date = "2017/11/10", ImageType = "A", Doctype = "ABC", DOCTYPE_DESCR = "ABC data file", Total = "2"
"Date = "2017/11/10", ImageType = "B", Doctype = "DEF", DOCTYPE_DESCR = "DEF chart file", Total = "2"
"Date = "2017/11/10", ImageType = "C", Doctype = "HIJ", DOCTYPE_DESCR = "HIJ PDF", Total = "2"
"Date = "2017/11/10", ImageType = "D", Doctype = "KLM", DOCTYPE_DESCR = "KLM file", Total = "1"
</code>```

Here's my XSLT

```<code>  <?xml version="1.0"?>
  <xsl:stylesheet version="1.0"    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="text" indent="yes"/>
    <!--match the root node-->
    <xsl:template match="NewDataSet">
    </xsl:element>
    </xsl:template>
    </xsl:stylesheet>
</code>```

答:
If using XSLT 2.0 is an option, you can employ method xsl:result-document:

```<code><xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="NewDataSet">
        <xsl:result-document method="text" href="NewDataSet.txt">
            <xsl:for-each select="/NewDataSet/Table/Column1">
                <xsl:copy-of select="."/>
                <xsl:text>
</xsl:text>
            </xsl:for-each>
        </xsl:result-document>
    </xsl:template>
</xsl:stylesheet>
</code>```

https://www.w3.org/TR/xslt20/#element-result-document

Body:
My XML looks like this:

<NewDataSet>

    <Column1>"Date = "2017/11/10", ImageType = "A", Doctype = "ABC", DOCTYPE_DESCR = "ABC data file", Total = "2"</Column1>

    <Column1>"Date = "2017/11/10", ImageType = "b", Doctype = "DEF", DOCTYPE_DESCR = "DEF chart file", Total = "2"</Column1>

    <Column1>"Date = "2017/11/10", ImageType = "C", Doctype = "HIJ", DOCTYPE_DESCR = "HIJ PDF ", Total = "2"</Column1>

    <Column1>"Date = "2017/11/10", ImageType = "d", Doctype = "KLM", DOCTYPE_DESCR = "KLM file.", Total = "1"</Column1>

</NewDataSet>

Here's my desired output text file. Currently, my program is outputting individual text files rather than one single text files with the multiple results. Any help is greatly appreciated.

"Date = "2017/11/10", ImageType = "A", Doctype = "ABC", DOCTYPE_DESCR = "ABC data file", Total = "2"
"Date = "2017/11/10", ImageType = "B", Doctype = "DEF", DOCTYPE_DESCR = "DEF chart file", Total = "2"
"Date = "2017/11/10", ImageType = "C", Doctype = "HIJ", DOCTYPE_DESCR = "HIJ PDF", Total = "2"
"Date = "2017/11/10", ImageType = "D", Doctype = "KLM", DOCTYPE_DESCR = "KLM file", Total = "1"

Here's my XSLT

  <?xml version="1.0"?>
  <xsl:stylesheet version="1.0"    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="text" indent="yes"/>

    <xsl:template match="NewDataSet">
    </xsl:element>
    </xsl:template>
    </xsl:stylesheet>

Body:
If using XSLT 2.0 is an option, you can employ method xsl:result-document:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="NewDataSet">
        <xsl:result-document method="text" href="NewDataSet.txt">
            <xsl:for-each select="/NewDataSet/Table/Column1">
                <xsl:copy-of select="."/>
                <xsl:text>&#xa;</xsl:text>
            </xsl:for-each>
        </xsl:result-document>
    </xsl:template>
</xsl:stylesheet>

https://www.w3.org/TR/xslt20/#element-result-document


问:
Loading isAuthenticated correctly in file
I am trying to use passport with passport-local in my express app:

In my main app I load it the following:

```<code>const session = require('express-session')
const passport = require('passport')
// configure passport
// require('./config/passport')(passport)
const auth = require('./routes/auth')
const index = require('./routes/index')

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())

app.use(session({
  secret: 'super-mega-hyper-secret',
  resave: false,
  saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())
</code>```

My passport.js config file looks pretty typical:

```<code>const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const serviceAuth = require('../service/auth')

  passport.serializeUser((user, done) => {
    done(null, user.id)
  })

  passport.deserializeUser(async (id, done) => {
    const user = await serviceAuth.findById(id)
    done(null, user)
  })

  passport.use('local', new LocalStrategy({
    usernameField: 'username',
  }, async(username, password, done) => {
    const user = await serviceAuth.signin(username, password)
    done(null, user)
  }))
</code>```

Within my routes I would like to steer which routes need authentication:

```<code>const express = require('express')

const router = express.Router()
const utils = require('../util/utils')

router.get('/', utils.isLogged(), (req, res) => {
  res.render('dashboard')
})

module.exports = router
</code>```

In the utils/utils.js folder I have the middleware to steer, which user  is authenticated.

```<code>const passportConfig = require('../config/passport')

function isLogged(req, res, next) {
  const auth = this.passportConfig.isAuthenticated()
  if (req.auth) {
    next()
  } else {
    res.redirect('/')
  }
}

module.exports = {
  isLogged,
}
</code>```

However, here I get the following error:

```<code>  const auth = this.passportConfig.isAuthenticated()
                                  ^

TypeError: Cannot read property 'isAuthenticated' of undefined
</code>```

Any suggestions how to load passport properly in my utils/utils.js folder?

I appreciate your replies!

Update

Please find the following github repo, which shows the minimum viable example.

答:
In your isLogged() function, this keyword refers to the function itself, hence this.passportConfig is undefined. What you should do is just using:

```<code>const auth = passportConfig.isAuthenticated();
</code>```

without this keyword.

Body:
I am trying to use passport with passport-local in my express app:

In my main app I load it the following:

const session = require('express-session')
const passport = require('passport')
// configure passport
// require('./config/passport')(passport)
const auth = require('./routes/auth')
const index = require('./routes/index')

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())

app.use(session({
  secret: 'super-mega-hyper-secret',
  resave: false,
  saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())

My passport.js config file looks pretty typical:

const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const serviceAuth = require('../service/auth')

  passport.serializeUser((user, done) => {
    done(null, user.id)
  })

  passport.deserializeUser(async (id, done) => {
    const user = await serviceAuth.findById(id)
    done(null, user)
  })

  passport.use('local', new LocalStrategy({
    usernameField: 'username',
  }, async(username, password, done) => {
    const user = await serviceAuth.signin(username, password)
    done(null, user)
  }))

Within my routes I would like to steer which routes need authentication:

const express = require('express')

const router = express.Router()
const utils = require('../util/utils')

router.get('/', utils.isLogged(), (req, res) => {
  res.render('dashboard')
})

module.exports = router

In the utils/utils.js folder I have the middleware to steer, which user  is authenticated.

const passportConfig = require('../config/passport')

function isLogged(req, res, next) {
  const auth = this.passportConfig.isAuthenticated()
  if (req.auth) {
    next()
  } else {
    res.redirect('/')
  }
}

module.exports = {
  isLogged,
}

However, here I get the following error:

  const auth = this.passportConfig.isAuthenticated()
                                  ^

TypeError: Cannot read property 'isAuthenticated' of undefined

Any suggestions how to load passport properly in my utils/utils.js folder?

I appreciate your replies!

Update

Please find the following github repo, which shows the minimum viable example.

Body:
In your isLogged() function, this keyword refers to the function itself, hence this.passportConfig is undefined. What you should do is just using:

const auth = passportConfig.isAuthenticated();

without this keyword.


问:
nanoGallery2 - How to change Thumbnail icon
i'm using a nanoGallery2 and I did like to customize a thumbnail icon, on the documentation theres:

All icons used in the gallery can be customized. By default, an icon
  font is used. Example: replace the default album icon with a red one
  from Font Awesome:

```<code> icons.thumbnailAlbum: '<i style="color:#e00;" class="fa fa-search-plus"></i>'
</code>```

But im trying to use the comment icon, like this:

```<code>icons: { thumbnailCustomTool1 : '<i class="fa fa-comment" aria-hidden="true"></i>'}
</code>```

or

```<code>icons: { thumbnailCustomTool1 : '<i class="fa fa-comment"></i>'}
</code>```

or

```<code>icons: { thumbnailCustomTool1 : '<i class="icon-comment"></i>'}
</code>```

or

```<code>icons: { thumbnailCustomTool1 : '<i class="nGY2Icon icon-comment"></i>'}
</code>```

and does not work :(

but some icons works well.. like..

```<code>icons: { thumbnailCustomTool1 : '<i class="nGY2Icon icon-star"></i>'}
</code>```

What is the right way to change icons?

Thanks guys

答:
nanogallery2 is using a custom font, based on some icons from font awesome.

To use icons from another icon font, did you include the corresponding font in your HTML page?

For font awesome:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

Here's a full working sample on CodePen: https://codepen.io/Kris-B/pen/EWmqdd

Body:
i'm using a nanoGallery2 and I did like to customize a thumbnail icon, on the documentation theres:

All icons used in the gallery can be customized. By default, an icon
  font is used. Example: replace the default album icon with a red one
  from Font Awesome:

 icons.thumbnailAlbum: ''

But im trying to use the comment icon, like this:

icons: { thumbnailCustomTool1 : ''}

or

icons: { thumbnailCustomTool1 : ''}

or

icons: { thumbnailCustomTool1 : ''}

or

icons: { thumbnailCustomTool1 : ''}

and does not work :(

but some icons works well.. like..

icons: { thumbnailCustomTool1 : ''}

What is the right way to change icons?

Thanks guys


问:
Rails post external link on form and display it clickable
This is probably simple but I can't figure out how to do it.

I simply want to be able to enter an external link in a form and then show it in the view. It should be clickable and open in a new tab.

I am using formtastic.

I tried:

form:

```<code><%= semantic_form_for @poll do |f| %>
<%= f.input :link %>

<% end %>
</code>```

view:

```<code><p><%= link_to @poll.link %></p>
</code>```

I tried to enter https://www.google.com in the form.

Doing this it shows a clickable link https://www.google.com on view but when I click nothing happens.

Any suggestion?

答:
basically you need use target: :_blank with link as example: -

```<code><li><%= link_to "My Link", @poll.link, target: :_blank %></li>
</code>```

Body:
This is probably simple but I can't figure out how to do it.

I simply want to be able to enter an external link in a form and then show it in the view. It should be clickable and open in a new tab.

I am using formtastic.

I tried:

form:

<%= semantic_form_for @poll do |f| %>
<%= f.input :link %>

<% end %>

view:

<%= link_to @poll.link %>

I tried to enter https://www.google.com in the form.

Doing this it shows a clickable link https://www.google.com on view but when I click nothing happens.

Any suggestion?

Body:
basically you need use target: :_blank with link as example: -

<li><%= link_to "My Link", @poll.link, target: :_blank %></li>


问:
Groovy get current methods annotation
I created a java interface for my annotation. I am now writing a geb spock test and I would like to print the annotation values so it shows in the gradle report. Is this possible? Here is my test case and let me know if I am doing this wrong</p>

```<code>class Checkout extends GebReportingSpec {

    @TestCase(someID="12345")
    def "A checkout 3-D script"() {
        // My test steps.....
    }
}
</code>```

答:
spockframework (version "spock-core-1.1-groovy-2.4") is provides way of accessing annotation:</p>

```<code>package com.test.integration.spec

import com.test.integration.annotation.Scenario
import com.test.integration.annotation.TestCase

import spock.lang.Specification

@Scenario("AnnotationSpec")
class AnnotationSpec extends Specification {

    String scenario
    String test_case

    def setup() {
        scenario = specificationContext.currentSpec.getAnnotation(Scenario).value()
        test_case = specificationContext.currentFeature.featureMethod.getAnnotation(TestCase).value()
    }

    @TestCase("case-001")
    def 'spock provides way of accessing annotation'(){

        expect:
        "AnnotationSpec" == scenario
        "case-001" == test_case
    }

}
</code>```

Title: Groovy get current methods annotation

Body:
I created a java interface for my annotation. I am now writing a geb spock test and I would like to print the annotation values so it shows in the gradle report. Is this possible? Here is my test case and let me know if I am doing this wrong

class Checkout extends GebReportingSpec {

    @TestCase(someID="12345")
    def "A checkout 3-D script"() {
        // My test steps.....
    }
}

Body:
spockframework (version "spock-core-1.1-groovy-2.4") is provides way of accessing annotation:

package com.test.integration.spec

import com.test.integration.annotation.Scenario
import com.test.integration.annotation.TestCase

import spock.lang.Specification

@Scenario("AnnotationSpec")
class AnnotationSpec extends Specification {

    String scenario
    String test_case

    def setup() {
        scenario = specificationContext.currentSpec.getAnnotation(Scenario).value()
        test_case = specificationContext.currentFeature.featureMethod.getAnnotation(TestCase).value()
    }

    @TestCase("case-001")
    def 'spock provides way of accessing annotation'(){

        expect:
        "AnnotationSpec" == scenario
        "case-001" == test_case
    }

}


问:
Div element cannot be nested inside element label
I have searched in google this message:

element div cannot be nested inside label element. But I can't find anything.

This is my html:

```<code> <div class="email-logo">
     <label>
         <div class="email-logo-image">
              <img src='/Beheer/Document/Download?documentID=@(Html.GebruikerContext().Klant.LogoID)' />
         </div>
         <div class="email-logo-button">
              @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
              <span>eigen logo</span>
        </div>
     </label>
 </div>
</code>```

So my question is:

How to correct this?

Thank you

答:
Not sure why you need the divs, if you don’t try this.

```<code><div class="email-logo">
 <label>
     <img src='/Beheer/Document/Download?documentID=@(Html.GebruikerContext().Klant.LogoID)'class="email-logo-image" />
     <span class="email-logo-button">
          @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
          <span>eigen logo</span>
    </span>
 </label>
<\div>
</code>```

You also had a typo which was likely making your html error. ( No > to close label)

Body:
I have searched in google this message:

element div cannot be nested inside label element. But I can't find anything.

This is my html:

              @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
              eigen logo

So my question is:

How to correct this?

Thank you

Body:
Not sure why you need the divs, if you don’t try this.

<div class="email-logo">
 <label>
     <img src='/Beheer/Document/Download?documentID=@(Html.GebruikerContext().Klant.LogoID)'class="email-logo-image" />
     <span class="email-logo-button">
          @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
          <span>eigen logo</span>
    </span>
 </label>
<\div>

You also had a typo which was likely making your html error. ( No > to close label)


问:
Creating a custom bootstrap / bootloader in C#
We've decided to create a custom bootstrapper for our deployment solution. We are currently re-writing and re-designing our deployment strategy for all of our products. Sadly, none of us are deployment experts.

Here's what we have so far:

A. The MSI packages will be authored in InstallShield. We will use whatever feature Installshield offers (IIS integration, COM registration, Registry, etc). The dialog's created by InstallShield will not be used (that is what the bootstrapper is for). The MSIs will be installed silently.

B. Whenever we need to write CA's for stuff that InstallShield can't handle, we will be writing them in managed code (C#) using DTF. We will be creating a "Custom Action Framework" that will "standardize" how we use custom actions.

C. We will create a custom bootstrapper (the "setup.exe") in C# to "handle" the installation.

We have decided to go with a multiple MSI approach and use MSI transaction to "chain" the installation from the boostrapper (inspired from Office 2007 installer)

The boostrapper that we are envisioning to create is inspired from Visual Studio's and SQL Server's bootstrapper. The boostrapper will be responsible for the following:

Prerequisite installation: Each application require a pre-requisite. These pre-requisites are listed in an XML file placed on the same folder as the MSI (inspired from Office 2007 installer) along with other metadata. Depending on current state of the system, the boostrapper will decide which pre-requisite to be installed or not.

Feature selection: We are planning to structure the "internal" MSI's feature in such a way that it will not be appropriate to be displayed right away to the end-user. We will have feature labeled as "Core_Files", or "Vista_Only" or "64bit_Only". Depending on the metadata on the XML file (on item 1) and the target system, the bootstrapper will be responsible in "populating" a "feature tree" that the user can customize (also inspired from Office 2007 bootstrapper).

Pre-installation Checks: The bootstrapper will be responsible in checking if the system is ready to receive the installation. For instance, if a machine needs to reboot prior to installation or if the user needs to manually install a service pack, patch or a windows component. Anything that needs to be done that needs user intervention should be displayed here. Think of it as a check list (a listbox) with checks and exes. (Inspired from SQL server's bootstrapper). The "rules" will be written in C#.

Application Configuration: For application that needs to be "configured" prior to installation. These "parameters" (user configuration) will be passed to the respective MSI via MSI Properties.

Actual Installation: The bootstrapper will then perform the installation. Proper "transaction" should be observed when necessary. All "products" that should be grouped together shall be displayed as one product in Add/Remove Programs (by messing with the ARP entries). Also, proper progress shall be reported by each MSI being installed.

-- That's what we have so far.

I think there are a couple of out-of-the-box solutions for creating a custom bootstrapper like dotNetInstaller and BMG. We've look into it but it's not as flexible as we've hoped. There's also BURN but we're not sure if it's ready for primetime.

So here we are... we've decided to create our own custom bootstrapper.

Question:

Are we crazy? Shouldn't we be creating our own bootstrapper? Which ideas listed above are not realistic? Is there a better approach?

Any input regarding our situation will be greatly appreciated. Also, if you have any questions, please don't hesitate to ask.

答:
I would go for Burn anyway or some already existing solution.

I'm sure that after some time you'll face new problems that you can't now really imagine.
If you face them, that means that Burn's developers have already faced them and probably got them solved. If not, Burn has a large community that will fix the potential bug faster than you.

Focus on the software you're developing, not on writing installer/bootstrapper.

If I were in your shoes, I would give a burn a try. I'd get me a couple of days and see if it meets my requirements.


问:
How to click on Div and Redirect on others page particular Div
I want to point the div on other page particular  Div  i try both
ways

```<code>   <div class="B_and_A" onClick="document.location='/discovers/page2#who_me';">

and

<a href='/discovers/page2#who_me'
<div class="B_and_A">
    </div>
</a>
</code>```

But its just redirect on other page but on on particular Div of others Page
Actually Its Give me this On Magento

ERROR::

jquery.js:3123 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin  from accessing a cross-origin frame.

答:
your div lacks an anchor.

page1

```<code><a href='/discovers/page2#who_me'></a>
</code>```

page2

```<code><div id="who_me" class="B_and_A">
</div>
</code>```

Body:
I want to point the div on other page particular  Div  i try both
ways

and

<a href='/discovers/page2#who_me'

But its just redirect on other page but on on particular Div of others Page
Actually Its Give me this On Magento

ERROR::

jquery.js:3123 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin  from accessing a cross-origin frame.

Body:
your div lacks an anchor.

page1

<a href='/discovers/page2#who_me'></a>

page2

<div id="who_me" class="B_and_A">
</div>


问:
Equivalent of Datetime2 of mysql in mssql
what is the equivalent of Datetime2 of mysql in mssql ?</p>

答:
MySQL 5.7 has fractional seconds support for TIME, DATETIME, and
  TIMESTAMP values, with up to microseconds (6 digits) precision:
  https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html

Datetime2
  Precision, scale    0 to 7 digits, with an accuracy of 100ns. The default
  precision is 7 digits https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime2-transact-sql

Datetime2 is a term used in MS SQL Server. A MS SQL Server column defined as datetime2(6) is the equivalent to a MySQL 5.7 datetime or timestamp column.


问:
NLTK words vs word_tokenize
I'm exploring some of NLTK's corpora and came across the following behaviour: word_tokenize() and words produce different sets of words().

Here is an example using webtext:

```<code>from nltk.corpus import webtext
</code>```

When I run the following,

```<code>len(set(word_tokenize(webtext.raw('wine.txt'))))
</code>```

I get: 3488

When I run the following,

```<code>len(set(webtext.words('wine.txt')))
</code>```

I get: 3414

All I can find in the documentation is that word_tokenize is a list of punctuation and words. But it also says words is a list of punctuation and words. I'm wondering, what's going on here? Why are they different?

I've already tried looking at the set differences.

```<code>U = set(word_tokenize(webtext.raw('wine.txt')))
V = set(webtext.words('wine.txt'))

tok_not_in_words = U.difference(V) # in tokenize but not in words
words_not_in_tok = V.difference(U) # in words but not in tokenize
</code>```

All I can see is that word_tokenize contains hyphenated words and words splits the hyphenated words.

Any help is appreciated. Thank you!

答:
First lets take a look at the count the tokens from both approach and see the most_common words:

```<code>>>> import nltk
>>> from nltk import word_tokenize
>>> from nltk.corpus import webtext

>>> counts_from_wordtok = Counter(word_tokenize(webtext.raw('wine.txt')))
>>> counts_from_wordtok.most_common(10)
[(u'.', 2824), (u',', 1550), (u'a', 821), (u'and', 786), (u'the', 706), (u'***', 608), (u'-', 518), (u'of', 482), (u'but', 474), (u'I', 390)]

>>> counts_from_words = Counter(webtext.words('wine.txt'))
>>> counts_from_words.most_common(10)
[(u'.', 2772), (u',', 1536), (u'-', 832), (u'a', 821), (u'and', 787), (u'the', 706), (u'***', 498), (u'of', 482), (u'but', 474), (u'I', 392)]

>>> len(word_tokenize(webtext.raw('wine.txt')))
31140
>>> len(webtext.words('wine.txt'))
31350
</code>```

Something smells fishy...

Lets take a closer look of how webtext interface comes about, it uses the LazyCorpusLoader at https://github.com/nltk/nltk/blob/develop/nltk/corpus/init.py#L235

```<code>webtext = LazyCorpusLoader(
    'webtext', PlaintextCorpusReader, r'(?!README|\.).*\.txt', encoding='ISO-8859-2')
</code>```

If we look at how PlaintextCorpusReader is loading the corpus and tokenizing https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L41

```<code>class PlaintextCorpusReader(CorpusReader):
    CorpusView = StreamBackedCorpusView

    def __init__(self, root, fileids,
                 word_tokenizer=WordPunctTokenizer(),
                 sent_tokenizer=nltk.data.LazyLoader(
                     'tokenizers/punkt/english.pickle'),
                 para_block_reader=read_blankline_block,
                 encoding='utf8'):
</code>```

Ah ha! It's using the WordPunctTokenizer instead of the default modified TreebankTokenizer

The WordPunctTokenizer is a simplistic tokenizer found at https://github.com/nltk/nltk/blob/develop/nltk/tokenize/regexp.py#L171

The word_tokenize() function is a modified TreebankTokenizer unique to NLTK https://github.com/nltk/nltk/blob/develop/nltk/tokenize/init.py#L97

If we look at what's webtext.words() calling, we follow https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L81

```<code>def words(self, fileids=None):
    """
    :return: the given file(s) as a list of words
        and punctuation symbols.
    :rtype: list(str)
    """
    return concat([self.CorpusView(path, self._read_word_block, encoding=enc)
                   for (path, enc, fileid)
                   in self.abspaths(fileids, True, True)])
</code>```

to reach _read_word_block() at https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L119 :

```<code>def _read_word_block(self, stream):
    words = []
    for i in range(20): # Read 20 lines at a time.
        words.extend(self._word_tokenizer.tokenize(stream.readline()))
    return words
</code>```

It's reading the file line by line!

So if we load the webtext corpus and use the WordPunctTokenizer we get the same number:

```<code>>>> from nltk.corpus import webtext
>>> from nltk.tokenize import WordPunctTokenizer
>>> wpt = WordPunctTokenizer()
>>> len(wpt.tokenize(webtext.raw('wine.txt')))
31350
>>> len(webtext.words('wine.txt'))
31350
</code>```

More mysteries

You can also create a new webtext corpus object by specifying the tokenizer object e.g.

```<code>>>> from nltk.tokenize import _treebank_word_tokenizer
>>> from nltk.corpus import LazyCorpusLoader, PlaintextCorpusReader
>>> from nltk.corpus import webtext

# LazyCorpusLoader expects a tokenizer object,
# but word_tokenize() is a function, so we have to
# import the tokenizer object that word_tokenize wraps around
>>> webtext2 = LazyCorpusLoader('webtext', PlaintextCorpusReader, r'(?!README|\.).*\.txt', encoding='ISO-8859-2', word_tokenizer=_treebank_word_tokenizer)

>>> len(webtext2.words('wine.txt'))
28385

>>> len(word_tokenize(webtext2.raw('wine.txt')))
31140

>>> list(webtext2.words('wine.txt'))[:100]
[u'Lovely', u'delicate', u',', u'fragrant', u'Rhone', u'wine.', u'Polished', u'leather', u'and', u'strawberries.', u'Perhaps', u'a', u'bit', u'dilute', u',', u'but', u'good', u'for', u'drinking', u'now.', u'***', u'Liquorice', u',', u'cherry', u'fruit.', u'Simple', u'and', u'coarse', u'at', u'the', u'finish.', u'**', u'Thin', u'and', u'completely', u'uninspiring.', u'*', u'Rough.', u'No', u'Stars', u'Big', u',', u'fat', u',', u'textured', u'Chardonnay', u'-', u'nuts', u'and', u'butterscotch.', u'A', u'slightly', u'odd', u'metallic/cardboard', u'finish', u',', u'but', u'probably', u'***', u'A', u'blind', u'tasting', u',', u'other', u'than', u'the', u'fizz', u',', u'which', u'included', u'five', u'vintages', u'of', u'Cote', u'Rotie', u'Brune', u'et', u'Blonde', u'from', u'Guigal', u'.', u'Surprisingly', u'young', u'feeling', u'and', u'drinking', u'well', u',', u'but', u'without', u'any', u'great', u'complexity.', u'A', u'good', u'***', u'Charming', u',', u'violet-fragranced', u'nose.']

>>> word_tokenize(webtext2.raw('wine.txt'))[:100]
[u'Lovely', u'delicate', u',', u'fragrant', u'Rhone', u'wine', u'.', u'Polished', u'leather', u'and', u'strawberries', u'.', u'Perhaps', u'a', u'bit', u'dilute', u',', u'but', u'good', u'for', u'drinking', u'now', u'.', u'***', u'Liquorice', u',', u'cherry', u'fruit', u'.', u'Simple', u'and', u'coarse', u'at', u'the', u'finish', u'.', u'**', u'Thin', u'and', u'completely', u'uninspiring', u'.', u'*', u'Rough', u'.', u'No', u'Stars', u'Big', u',', u'fat', u',', u'textured', u'Chardonnay', u'-', u'nuts', u'and', u'butterscotch', u'.', u'A', u'slightly', u'odd', u'metallic/cardboard', u'finish', u',', u'but', u'probably', u'***', u'A', u'blind', u'tasting', u',', u'other', u'than', u'the', u'fizz', u',', u'which', u'included', u'five', u'vintages', u'of', u'Cote', u'Rotie', u'Brune', u'et', u'Blonde', u'from', u'Guigal', u'.', u'Surprisingly', u'young', u'feeling', u'and', u'drinking', u'well', u',', u'but', u'without', u'any', u'great']
</code>```

That's because word_tokenize does a sent_tokenize before actually tokenizing sentences into words: https://github.com/nltk/nltk/blob/develop/nltk/tokenize/init.py#L113

But the PlaintextCorpusReader. _read_word_block() doesn't do sent_tokenize beforehand, https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L119

Let's do a recount with sentence tokenization first:

```<code>>>> len(word_tokenize(webtext2.raw('wine.txt')))
31140

>>> sum(len(tokenized_sent) for tokenized_sent in webtext2.sents('wine.txt'))
31140
</code>```

Note: The sent_tokenizer of PlaintextCorpusReader uses the sent_tokenizer=nltk.data.LazyLoader('tokenizers/punkt/english.pickle') which is the same object shared with the nltk.sent_tokenize() function.

Voila!

Why is it that words() don't do sentence tokenization first?

I think it's because it was originally using the WordPunctTokenizer that doesn't need the string to be sentence tokenized first, whereas the TreebankWordTokenizer requires the string to be tokenized first.

Why is it that in the age of "deep learning" and "machine learning", we are still using regex based tokenizers and everything else in NLP are largely based on these tokens?

I have no ideas... But there are alternatives, e.g. http://gmb.let.rug.nl/elephant/about.php

Title: NLTK words vs word_tokenize

Body:
I'm exploring some of NLTK's corpora and came across the following behaviour: word_tokenize() and words produce different sets of words().

Here is an example using webtext:

from nltk.corpus import webtext

When I run the following,

len(set(word_tokenize(webtext.raw('wine.txt'))))

I get: 3488

When I run the following,

len(set(webtext.words('wine.txt')))

I get: 3414

All I can find in the documentation is that word_tokenize is a list of punctuation and words. But it also says words is a list of punctuation and words. I'm wondering, what's going on here? Why are they different?

I've already tried looking at the set differences.

U = set(word_tokenize(webtext.raw('wine.txt')))
V = set(webtext.words('wine.txt'))

tok_not_in_words = U.difference(V) # in tokenize but not in words
words_not_in_tok = V.difference(U) # in words but not in tokenize

All I can see is that word_tokenize contains hyphenated words and words splits the hyphenated words.

Any help is appreciated. Thank you!

Body:
First lets take a look at the count the tokens from both approach and see the most_common words:

>>> import nltk
>>> from nltk import word_tokenize
>>> from nltk.corpus import webtext

>>> counts_from_wordtok = Counter(word_tokenize(webtext.raw('wine.txt')))
>>> counts_from_wordtok.most_common(10)
[(u'.', 2824), (u',', 1550), (u'a', 821), (u'and', 786), (u'the', 706), (u'***', 608), (u'-', 518), (u'of', 482), (u'but', 474), (u'I', 390)]

>>> counts_from_words = Counter(webtext.words('wine.txt'))
>>> counts_from_words.most_common(10)
[(u'.', 2772), (u',', 1536), (u'-', 832), (u'a', 821), (u'and', 787), (u'the', 706), (u'***', 498), (u'of', 482), (u'but', 474), (u'I', 392)]

>>> len(word_tokenize(webtext.raw('wine.txt')))
31140
>>> len(webtext.words('wine.txt'))
31350

Something smells fishy...

Lets take a closer look of how webtext interface comes about, it uses the LazyCorpusLoader at https://github.com/nltk/nltk/blob/develop/nltk/corpus/init.py#L235

webtext = LazyCorpusLoader(
    'webtext', PlaintextCorpusReader, r'(?!README|\.).*\.txt', encoding='ISO-8859-2')

If we look at how PlaintextCorpusReader is loading the corpus and tokenizing https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L41

class PlaintextCorpusReader(CorpusReader):
    CorpusView = StreamBackedCorpusView

    def __init__(self, root, fileids,
                 word_tokenizer=WordPunctTokenizer(),
                 sent_tokenizer=nltk.data.LazyLoader(
                     'tokenizers/punkt/english.pickle'),
                 para_block_reader=read_blankline_block,
                 encoding='utf8'):

Ah ha! It's using the WordPunctTokenizer instead of the default modified TreebankTokenizer

The WordPunctTokenizer is a simplistic tokenizer found at https://github.com/nltk/nltk/blob/develop/nltk/tokenize/regexp.py#L171

The word_tokenize() function is a modified TreebankTokenizer unique to NLTK https://github.com/nltk/nltk/blob/develop/nltk/tokenize/init.py#L97

If we look at what's webtext.words() calling, we follow https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L81

def words(self, fileids=None):
    """
    :return: the given file(s) as a list of words
        and punctuation symbols.
    :rtype: list(str)
    """
    return concat([self.CorpusView(path, self._read_word_block, encoding=enc)
                   for (path, enc, fileid)
                   in self.abspaths(fileids, True, True)])

to reach _read_word_block() at https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L119 :

def _read_word_block(self, stream):
    words = []
    for i in range(20): # Read 20 lines at a time.
        words.extend(self._word_tokenizer.tokenize(stream.readline()))
    return words

It's reading the file line by line!

So if we load the webtext corpus and use the WordPunctTokenizer we get the same number:

>>> from nltk.corpus import webtext
>>> from nltk.tokenize import WordPunctTokenizer
>>> wpt = WordPunctTokenizer()
>>> len(wpt.tokenize(webtext.raw('wine.txt')))
31350
>>> len(webtext.words('wine.txt'))
31350

More mysteries

You can also create a new webtext corpus object by specifying the tokenizer object e.g.

>>> from nltk.tokenize import _treebank_word_tokenizer
>>> from nltk.corpus import LazyCorpusLoader, PlaintextCorpusReader
>>> from nltk.corpus import webtext

# LazyCorpusLoader expects a tokenizer object,
# but word_tokenize() is a function, so we have to
# import the tokenizer object that word_tokenize wraps around
>>> webtext2 = LazyCorpusLoader('webtext', PlaintextCorpusReader, r'(?!README|\.).*\.txt', encoding='ISO-8859-2', word_tokenizer=_treebank_word_tokenizer)

>>> len(webtext2.words('wine.txt'))
28385

>>> len(word_tokenize(webtext2.raw('wine.txt')))
31140

>>> list(webtext2.words('wine.txt'))[:100]
[u'Lovely', u'delicate', u',', u'fragrant', u'Rhone', u'wine.', u'Polished', u'leather', u'and', u'strawberries.', u'Perhaps', u'a', u'bit', u'dilute', u',', u'but', u'good', u'for', u'drinking', u'now.', u'***', u'Liquorice', u',', u'cherry', u'fruit.', u'Simple', u'and', u'coarse', u'at', u'the', u'finish.', u'**', u'Thin', u'and', u'completely', u'uninspiring.', u'*', u'Rough.', u'No', u'Stars', u'Big', u',', u'fat', u',', u'textured', u'Chardonnay', u'-', u'nuts', u'and', u'butterscotch.', u'A', u'slightly', u'odd', u'metallic/cardboard', u'finish', u',', u'but', u'probably', u'***', u'A', u'blind', u'tasting', u',', u'other', u'than', u'the', u'fizz', u',', u'which', u'included', u'five', u'vintages', u'of', u'Cote', u'Rotie', u'Brune', u'et', u'Blonde', u'from', u'Guigal', u'.', u'Surprisingly', u'young', u'feeling', u'and', u'drinking', u'well', u',', u'but', u'without', u'any', u'great', u'complexity.', u'A', u'good', u'***', u'Charming', u',', u'violet-fragranced', u'nose.']

>>> word_tokenize(webtext2.raw('wine.txt'))[:100]
[u'Lovely', u'delicate', u',', u'fragrant', u'Rhone', u'wine', u'.', u'Polished', u'leather', u'and', u'strawberries', u'.', u'Perhaps', u'a', u'bit', u'dilute', u',', u'but', u'good', u'for', u'drinking', u'now', u'.', u'***', u'Liquorice', u',', u'cherry', u'fruit', u'.', u'Simple', u'and', u'coarse', u'at', u'the', u'finish', u'.', u'**', u'Thin', u'and', u'completely', u'uninspiring', u'.', u'*', u'Rough', u'.', u'No', u'Stars', u'Big', u',', u'fat', u',', u'textured', u'Chardonnay', u'-', u'nuts', u'and', u'butterscotch', u'.', u'A', u'slightly', u'odd', u'metallic/cardboard', u'finish', u',', u'but', u'probably', u'***', u'A', u'blind', u'tasting', u',', u'other', u'than', u'the', u'fizz', u',', u'which', u'included', u'five', u'vintages', u'of', u'Cote', u'Rotie', u'Brune', u'et', u'Blonde', u'from', u'Guigal', u'.', u'Surprisingly', u'young', u'feeling', u'and', u'drinking', u'well', u',', u'but', u'without', u'any', u'great']

That's because word_tokenize does a sent_tokenize before actually tokenizing sentences into words: https://github.com/nltk/nltk/blob/develop/nltk/tokenize/init.py#L113

But the PlaintextCorpusReader. _read_word_block() doesn't do sent_tokenize beforehand, https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/plaintext.py#L119

Let's do a recount with sentence tokenization first:

>>> len(word_tokenize(webtext2.raw('wine.txt')))
31140

>>> sum(len(tokenized_sent) for tokenized_sent in webtext2.sents('wine.txt'))
31140

Note: The sent_tokenizer of PlaintextCorpusReader uses the sent_tokenizer=nltk.data.LazyLoader('tokenizers/punkt/english.pickle') which is the same object shared with the nltk.sent_tokenize() function.

Voila!

Why is it that words() don't do sentence tokenization first?

I think it's because it was originally using the WordPunctTokenizer that doesn't need the string to be sentence tokenized first, whereas the TreebankWordTokenizer requires the string to be tokenized first.

Why is it that in the age of "deep learning" and "machine learning", we are still using regex based tokenizers and everything else in NLP are largely based on these tokens?

I have no ideas... But there are alternatives, e.g. http://gmb.let.rug.nl/elephant/about.php


问:
Extending Aero Glass in F# (PInvoke)
I'm working on a F# console application. In the properties I set the output type of application to Windows Application to hide the console. I also created a form to run in its place. Currently I only have a simple form with no controls. To make the form I added referances to System.Windows.Forms and System.Drawing and opened them along with System.Runtime.InteropServices.

The part that I don't know how to do is extending the aero-glass. There are loads of exaples on how to do it in C#. For example, here is the API call and MARGINS structure:

```<code>[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
    public int cxLeftWidth;
    public int cxRightWidth;
    public int cyTopHeight;
    public int cyBottomHeight;
}
[DllImport("dwmapi.dll")]
pubic static extend int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
</code>```

The API call from Form_Load event:

```<code>MARGINS margins = new MARGINS();
margins.cxLeftWidth = 0;
margins.cxRightWidth = 100;
margins.cyTopHeight = 0;
margins.cyBottomHeight = 0;
int result = DwmExtendFrameIntoClientArea(this.Handle, ref margins);
</code>```

This is what I've got so far in F#:

The API call and MARGINS structure:

```<code>[<StructLayout(LayoutKind.Sequential)>]
type MARGINS =
    struct
        val cxLeftWidth : int
        val cxRightWidth : int
        val cyTopHeight : int
        val cyBottomHeigh t: int
        new(left, right, top, bottom) = { cxLeftWidth = left; cxRightWidth = right; cyTopHeight = top; cyBottomHeigh = bottom } (*Is there any other way to do this?*)
    end
[<DllImport("dwmapi.dll")>]
extend int DwmExtendFrameIntoClientArea(IntPtr hWnd, (*I need help here*))
</code>```

The API call from Form_Load event:

```<code>let margins = new MARGINS(0, 100, 0, 0); (*Is there any other way to do this?*)
let result : int = DwmExtendFrameIntoClientArea(this.Handle, (*I need help here*))
</code>```

I have been searching around but I can't find anything about using ref parameters like this in F#. I know this would be a lot easier to write in C# but the code behind the form will be easier to write int F# because it's a functional programing language and the whole program I'm writing is orientated around functions. I know this is purely decorative but please help.

答:
In general, extern (AKA P/Invoke or platform invoke) definitions in F# use C-like syntax (and note that it's extern, not extend):

```<code>[<DllImport("dwmapi.dll")>]
extern int DwmExtendFrameIntoClientArea(nativeint hWnd, MARGINS& pMarInset)
</code>```

This can then be used as follows:

```<code>let mutable margin = ...
let result = DwmExtendFrameIntoClientArea(this.Handle, &margin)
</code>```

Note that the way that you have defined MARGINS is not quite analogous to the C# definition.  The various val definitions are not mutable, and are actually properties rather than fields (though they're backed by fields, so it's probably not a big deal).  If you want them to be mutable fields, you can add the mutable keyword after val for each field:

```<code>[<Struct; StructLayout(LayoutKind.Sequential)>]
type MARGINS =
  val mutable cxLeftWidth : int
  val mutable cxRightWidth : int
  val mutable cyTopHeight : int
  val mutable cyBottomHeight: int
</code>```

(I've also used the Struct attribute instead of struct ... end, but that's just for brevity).  You can initialize this like you do in C#, or using F#'s named arguments:

```<code>let mutable margin = MARGINS(cxRightWidth = 100)
</code>```

Title: Extending Aero Glass in F# (PInvoke)

Body:
I'm working on a F# console application. In the properties I set the output type of application to Windows Application to hide the console. I also created a form to run in its place. Currently I only have a simple form with no controls. To make the form I added referances to System.Windows.Forms and System.Drawing and opened them along with System.Runtime.InteropServices.

The part that I don't know how to do is extending the aero-glass. There are loads of exaples on how to do it in C#. For example, here is the API call and MARGINS structure:

[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
    public int cxLeftWidth;
    public int cxRightWidth;
    public int cyTopHeight;
    public int cyBottomHeight;
}
[DllImport("dwmapi.dll")]
pubic static extend int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);

The API call from Form_Load event:

MARGINS margins = new MARGINS();
margins.cxLeftWidth = 0;
margins.cxRightWidth = 100;
margins.cyTopHeight = 0;
margins.cyBottomHeight = 0;
int result = DwmExtendFrameIntoClientArea(this.Handle, ref margins);

This is what I've got so far in F#:

The API call and MARGINS structure:

[<StructLayout(LayoutKind.Sequential)>]
type MARGINS =
    struct
        val cxLeftWidth : int
        val cxRightWidth : int
        val cyTopHeight : int
        val cyBottomHeigh t: int
        new(left, right, top, bottom) = { cxLeftWidth = left; cxRightWidth = right; cyTopHeight = top; cyBottomHeigh = bottom } (*Is there any other way to do this?*)
    end
[<DllImport("dwmapi.dll")>]
extend int DwmExtendFrameIntoClientArea(IntPtr hWnd, (*I need help here*))

The API call from Form_Load event:

let margins = new MARGINS(0, 100, 0, 0); (*Is there any other way to do this?*)
let result : int = DwmExtendFrameIntoClientArea(this.Handle, (*I need help here*))

I have been searching around but I can't find anything about using ref parameters like this in F#. I know this would be a lot easier to write in C# but the code behind the form will be easier to write int F# because it's a functional programing language and the whole program I'm writing is orientated around functions. I know this is purely decorative but please help.

Body:
In general, extern (AKA P/Invoke or platform invoke) definitions in F# use C-like syntax (and note that it's extern, not extend):

[<DllImport("dwmapi.dll")>]
extern int DwmExtendFrameIntoClientArea(nativeint hWnd, MARGINS& pMarInset)

This can then be used as follows:

let mutable margin = ...
let result = DwmExtendFrameIntoClientArea(this.Handle, &margin)

Note that the way that you have defined MARGINS is not quite analogous to the C# definition.  The various val definitions are not mutable, and are actually properties rather than fields (though they're backed by fields, so it's probably not a big deal).  If you want them to be mutable fields, you can add the mutable keyword after val for each field:

[<Struct; StructLayout(LayoutKind.Sequential)>]
type MARGINS =
  val mutable cxLeftWidth : int
  val mutable cxRightWidth : int
  val mutable cyTopHeight : int
  val mutable cyBottomHeight: int

(I've also used the Struct attribute instead of struct ... end, but that's just for brevity).  You can initialize this like you do in C#, or using F#'s named arguments:

let mutable margin = MARGINS(cxRightWidth = 100)


问:
How to stop a goroutine
I have a goroutine that calls a method, and passes returned value on a channel:

```<code>ch := make(chan int, 100)
go func(){
    for {
        ch <- do_stuff()
    }
}()
</code>```

How do I stop such a goroutine?

答:
Generally, you could create a channel and receive a stop signal in the goroutine.

There two way to create channel in this example.

channel

context. In the example I will demo context.WithCancel

The first demo, use channel:

```<code>package main

import "fmt"
import "time"

func do_stuff() int {
    return 1
}

func main() {

    ch := make(chan int, 100)
    done := make(chan struct{})
    go func() {
        for {
            select {
            case ch <- do_stuff():
            case <-done:
                close(ch)
                return
            }
            time.Sleep(100 * time.Millisecond)
        }
    }()

    go func() {
        time.Sleep(3 * time.Second)
        done <- struct{}{}
    }()

    for i := range ch {
        fmt.Println("receive value: ", i)
    }

    fmt.Println("finish")
}
</code>```

The second demo, use context:

```<code>package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    forever := make(chan struct{})
    ctx, cancel := context.WithCancel(context.Background())

    go func(ctx context.Context) {
        for {
            select {
            case <-ctx.Done():  // if cancel() execute
                forever <- struct{}{}
                return
            default:
                fmt.Println("for loop")
            }

            time.Sleep(500 * time.Millisecond)
        }
    }(ctx)

    go func() {
        time.Sleep(3 * time.Second)
        cancel()
    }()

    <-forever
    fmt.Println("finish")
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to stop a goroutine

Body:
I have a goroutine that calls a method, and passes returned value on a channel:

ch := make(chan int, 100)
go func(){
    for {
        ch <- do_stuff()
    }
}()

How do I stop such a goroutine?

Body:
Generally, you could create a channel and receive a stop signal in the goroutine.

There two way to create channel in this example.

channel

context. In the example I will demo context.WithCancel

The first demo, use channel:

package main

import "fmt"
import "time"

func do_stuff() int {
    return 1
}

func main() {

    ch := make(chan int, 100)
    done := make(chan struct{})
    go func() {
        for {
            select {
            case ch <- do_stuff():
            case <-done:
                close(ch)
                return
            }
            time.Sleep(100 * time.Millisecond)
        }
    }()

    go func() {
        time.Sleep(3 * time.Second)
        done <- struct{}{}
    }()

    for i := range ch {
        fmt.Println("receive value: ", i)
    }

    fmt.Println("finish")
}

The second demo, use context:

package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    forever := make(chan struct{})
    ctx, cancel := context.WithCancel(context.Background())

    go func(ctx context.Context) {
        for {
            select {
            case <-ctx.Done():  // if cancel() execute
                forever <- struct{}{}
                return
            default:
                fmt.Println("for loop")
            }

            time.Sleep(500 * time.Millisecond)
        }
    }(ctx)

    go func() {
        time.Sleep(3 * time.Second)
        cancel()
    }()

    <-forever
    fmt.Println("finish")
}


问:
Play several videos using AVPlayer in a view
I have an UIView which contains some some texts and views. in each view I need to play a video with AVPlayer , but my problem is only the first view shows the video :

Here is my code :

```<code>func playVideo(name:String , onView:UIView) {

    let path = Bundle.main.path(forResource: name, ofType: "mp4")
    let videoURL = URL(fileURLWithPath: path!)
    let player = AVPlayer(url: videoURL)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = onView.frame
    playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    onView.layer.addSublayer(playerLayer)
    player.play()

}
</code>```

Using the function :

```<code>override func viewDidLoad() {
        super.viewDidLoad()

//ScrollView
    scrollView.contentSize = menuView.frame.size
    scrollView.addSubview(menuView)

//Play videos
 playVideo(name: "pizza", onView: videoView1)
 playVideo(name: "salad", onView: videoView2)
 playVideo(name: "fries", onView: videoView3)
}
</code>```

when I run the app video only play in videoView1 , any suggestion why this happens ?
 I also put my code in viewWillAppear , viewDidLayoutSubviews

答: I just found an alternative solution , I replaced UIView with UIContainerView and then link them with Embed to other view controller and play video in each view controller. Now it works perfectly as I expected.

Body:
I have an UIView which contains some some texts and views. in each view I need to play a video with AVPlayer , but my problem is only the first view shows the video :

Here is my code :

func playVideo(name:String , onView:UIView) {

    let path = Bundle.main.path(forResource: name, ofType: "mp4")
    let videoURL = URL(fileURLWithPath: path!)
    let player = AVPlayer(url: videoURL)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = onView.frame
    playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    onView.layer.addSublayer(playerLayer)
    player.play()

}

Using the function :

override func viewDidLoad() {
        super.viewDidLoad()

//ScrollView
    scrollView.contentSize = menuView.frame.size
    scrollView.addSubview(menuView)

//Play videos
 playVideo(name: "pizza", onView: videoView1)
 playVideo(name: "salad", onView: videoView2)
 playVideo(name: "fries", onView: videoView3)
}

when I run the app video only play in videoView1 , any suggestion why this happens ?
 I also put my code in viewWillAppear , viewDidLayoutSubviews


问:
Microsoft SQL Server, increasing price by percentage, rounded up
let's say I have a table called products_tbl, and a price column called price. I need a script to update the prices by 3% rounded up, so if the result of a cell is 41.3, it has to become 42.
Is it possible?</p>

答:
Use This</p>

```<code>UPDATE products_tbl
set price = floor(price+(price*0.03))
</code>```

Body:
Use This

UPDATE products_tbl
set price = floor(price+(price*0.03))


问:
Disable back button in GWT
Is there a way to disable the Back button in a browser (basically clearing the History token stack) in GWT? Once I browse to a certain page in my application I want to make sure that the user can't use the back button to go back, but only be able to use links on the page to navigate the site. </p>

答:
```<code>Window.addWindowClosingHandler(new ClosingHandler() {
    @Override
    public void onWindowClosing(ClosingEvent event) {
        event.setMessage("My program");
    }
});
</code>```

That is not a fool proof solution.  In fire fox I can press the back button and the onWindowClosing method is never invoked. The reason is that I have used History.newItem() and since history exists the back button or backspace buttons simply navigate through the browser history.

So....fix that :)

Title: Disable back button in GWT

Body:
Window.addWindowClosingHandler(new ClosingHandler() {
    @Override
    public void onWindowClosing(ClosingEvent event) {
        event.setMessage("My program");
    }
});

That is not a fool proof solution.  In fire fox I can press the back button and the onWindowClosing method is never invoked. The reason is that I have used History.newItem() and since history exists the back button or backspace buttons simply navigate through the browser history.

So....fix that :)