问:
Swift - iOS - Dates and times in different format
I am working for an application written in swift and i want to manipulate dates and times

```<code>let timestamp = NSDateFormatter.localizedStringFromDate(
    NSDate(),
    dateStyle: .ShortStyle,
    timeStyle: .ShortStyle
)
</code>```

returns

```<code>2/12/15, 11:27 PM
</code>```

if I want date and time in a different format, for example the date in a European format like dd/mm/yy and the hours in the 24h format without AM and PM. Is there some function that i can use or i have to use N Strings to reorder the various elements?

答:
```<code>let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
            //usDateFormat now contains an optional string "MM/dd/yyyy"

let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
            //gbDateFormat now contains an optional string "dd/MM/yyyy"

let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE"))
            //geDateFormat now contains an optional string "dd.MM.yyyy"
</code>```

<p>You can use it in following way to get the current format from device: </p>

```<code>let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)
</code>```

Body:
I am working for an application written in swift and i want to manipulate dates and times

let timestamp = NSDateFormatter.localizedStringFromDate(
    NSDate(),
    dateStyle: .ShortStyle,
    timeStyle: .ShortStyle
)

returns

2/12/15, 11:27 PM

if I want date and time in a different format, for example the date in a European format like dd/mm/yy and the hours in the 24h format without AM and PM. Is there some function that i can use or i have to use N Strings to reorder the various elements?

Body:
let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
            //usDateFormat now contains an optional string "MM/dd/yyyy"

let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
            //gbDateFormat now contains an optional string "dd/MM/yyyy"

let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE"))
            //geDateFormat now contains an optional string "dd.MM.yyyy"

You can use it in following way to get the current format from device:

let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)


来源: stackexchange

问:
.NET PDF Viewing component to allow searching/highlighting multiple words
I'm looking for a component which allows to highlight specific words inside PDF document. It will be used for searching.

Some components highlight when you perform a search, but they highlight only the text currently being searched. I need more advanced functionality for showing multiple search words.

Eventually, it will look like searching for multiple words simultaneously.

Possible solution would be conversion to plain text and highlighting in RichTextBox, but I need to retain actual document formatting.

Any suggestions?

Thanks!

答:
I don't know of any out-of-the-box solutions for something like that.

The only thing I'm aware of that might work for this is embedded reader/acrobat with a custom plugin that would handle the multiple searches & highlighting.

IIRC, publishing acrobat plugins is easy, but to "reader enable" plugins requires that Adobe sign them for you, which involves some $$$.

Decidedly non-trivial.

"Retaining the actual formatting" isn't really possible.  There is no formatting within PDF to retain.  There's coordinates, glyphs, lines, and images (and stuff).  No such thing as a word, or a paragraph, alignment, etc.  It's all 'draw this shape there'.  Most glyphs map to characters, but not all.  Some lines look like glyphs, but are straight line art.

It's possible to recreate the formatting information from coordinates and characters, but it's hard, and there's lots of things that can go wrong.

The PDF tag really needs a FAQ that would cover things like this.

ContentLicense: CC BY-SA 2.5


问:
Change Background of Items on Long Press
I want to change the background of Card View on Long Press and I have visited so many forum but no one gave the proper answer.

So, How to change the background of list/card/recycler view just like the long press on navigation view items ??

答:
I guess, you are trying to implement Ripple Effect on CardView. To achieve that, add the following attributes to your CardView in xml:

```<code>android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
</code>```

Hope this helps. Source.

ContentLicense: CC BY-SA 3.0

Body:
I guess, you are trying to implement Ripple Effect on CardView. To achieve that, add the following attributes to your CardView in xml:

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

Hope this helps. Source.


问:
Coloring R input and output differently using knitr
I would like to have my input R code printed/displayed on a light grey background and the output on a white background. So for example if my .Rnw file contains this chunk:

```<code><<>>=
t.test(zinc~sex, data = zinc.df)
@
</code>```

I would like the input to be rendered with a light grey background:

> t.test(zinc~sex, data = zinc.df)

and the output to be rendered on a white background, e.g.

Welch Two Sample t-test

data: zinc by sex

t = -15.08, df = 2678, p-value < 2.2e-16

(Output deliberately truncated but you get the idea). It seems like I might be able to do this with knitr themes, but I can't quite see it. Like many, I'm not keen to start fiddling with the listings package.

答:
If your working with Rnw and Latex only, you can use the background option of the chunks. However, you will need to write your chunk twice.

(1) with echo=TRUE, eval=FALSE and background='white'

```<code><<echo=TRUE, eval=FALSE, background='white'>>=
@
</code>```

(2) with echo=FALSE, eval=TRUE and background='yellow'

```<code><<echo=FALSE, eval=TRUE, background='yellow'>>=
@
</code>```

Body:
I would like to have my input R code printed/displayed on a light grey background and the output on a white background. So for example if my .Rnw file contains this chunk:

<<>>=
t.test(zinc~sex, data = zinc.df)
@

I would like the input to be rendered with a light grey background:

> t.test(zinc~sex, data = zinc.df)

and the output to be rendered on a white background, e.g.

Welch Two Sample t-test

data: zinc by sex

t = -15.08, df = 2678, p-value < 2.2e-16

(Output deliberately truncated but you get the idea). It seems like I might be able to do this with knitr themes, but I can't quite see it. Like many, I'm not keen to start fiddling with the listings package.

Body:
If your working with Rnw and Latex only, you can use the background option of the chunks. However, you will need to write your chunk twice.

(1) with echo=TRUE, eval=FALSE and background='white'

<<echo=TRUE, eval=FALSE, background='white'>>=
@

(2) with echo=FALSE, eval=TRUE and background='yellow'

<<echo=FALSE, eval=TRUE, background='yellow'>>=
@


问:
Copying selective columns data till data in column 1 ends
I am currently using the following code to copy paste data from File- "Source" to File-"Destination". It is selecting the rows till data ends in Column-1.
However, currently all the columns from A to AE are selected, but instead I want selective columns like A,F,K,AA to be selected.
I understand that the code in "wb.ActiveSheet.Range("A2:AE" & N).Copy" needs to be changed but not sure of the syntax.
Can anyone help me with this? Appreciate the help in advance.

```<code>Dim wb As Workbook
Set wb = ActiveWorkbook

Dim N As Long
Dim LastRow As Long
N = Cells(2, 1).End(xlDown).Row
wb.ActiveSheet.Range("A2:AE" & N).Copy

Set y = Workbooks.Open("C:\Desktop\Destination.xlsx")

y.Activate
y.Sheets("Data").Select
y.Sheets("Data").Activate

For Each Cell In y.Sheets("Data").Columns(1).Cells
     If Len(Cell) = 0 Then Cell.Select: Exit For
Next Cell
Selection.PasteSpecial Paste:=xlPasteValues
Application.DisplayAlerts = False
ActiveWorkbook.Close True
Application.DisplayAlerts = True
Application.CutCopyMode = False
</code>```

答:
You can use the Application.Union to combine ranges from different columns (from row 2 until N).

Also, instead of looping through your y.Sheets("Data").Columns(1).Cells to find the empty Cell, you can just use  LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1.

I added 2 With wb.Sheets("Sheet1") to fully qualify all variables and Range nested underneath.

Code

```<code>Option Explicit

Sub CopyColumns()

Dim wb      As Workbook
Dim Y       As Workbook
Dim N       As Long
Dim LastRow As Long
Dim CopyRng As range

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Set wb = ActiveWorkbook

' you need to specify the sheet, otherwise it will take the Active Sheet
With wb.Sheets("Sheet1") ' <-- modify to your sheet's name
    N = .Cells(.Rows.Count, "A").End(xlUp).Row ' <-- get last row from Column "A", skips blank cells in te middle
    ' set the range to Columns A, F, K, AA
    Set CopyRng = Application.Union(.Range("A2:A" & N), .Range("F2:F" & N), .Range("K2:K" & N), .Range("AA2:AA" & N))
End With

Set Y = Workbooks.Open("C:\Desktop\Destination.xlsx")
With Y.Sheets("Data")
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 '<-- get first empty row at Column A to paste at
    CopyRng.Copy
    .Range("A" & LastRow).PasteSpecial xlPasteValues
End With
Y.Close True

Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.CutCopyMode = False

End Sub
</code>```

Body:
I am currently using the following code to copy paste data from File- "Source" to File-"Destination". It is selecting the rows till data ends in Column-1.
However, currently all the columns from A to AE are selected, but instead I want selective columns like A,F,K,AA to be selected.
I understand that the code in "wb.ActiveSheet.Range("A2:AE" & N).Copy" needs to be changed but not sure of the syntax.
Can anyone help me with this? Appreciate the help in advance.

Dim wb As Workbook
Set wb = ActiveWorkbook

Dim N As Long
Dim LastRow As Long
N = Cells(2, 1).End(xlDown).Row
wb.ActiveSheet.Range("A2:AE" & N).Copy

Set y = Workbooks.Open("C:\Desktop\Destination.xlsx")

y.Activate
y.Sheets("Data").Select
y.Sheets("Data").Activate

For Each Cell In y.Sheets("Data").Columns(1).Cells
     If Len(Cell) = 0 Then Cell.Select: Exit For
Next Cell
Selection.PasteSpecial Paste:=xlPasteValues
Application.DisplayAlerts = False
ActiveWorkbook.Close True
Application.DisplayAlerts = True
Application.CutCopyMode = False

Body:
You can use the Application.Union to combine ranges from different columns (from row 2 until N).

Also, instead of looping through your y.Sheets("Data").Columns(1).Cells to find the empty Cell, you can just use  LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1.

I added 2 With wb.Sheets("Sheet1") to fully qualify all variables and Range nested underneath.

Code

Option Explicit

Sub CopyColumns()

Dim wb      As Workbook
Dim Y       As Workbook
Dim N       As Long
Dim LastRow As Long
Dim CopyRng As range

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Set wb = ActiveWorkbook

' you need to specify the sheet, otherwise it will take the Active Sheet
With wb.Sheets("Sheet1") ' <-- modify to your sheet's name
    N = .Cells(.Rows.Count, "A").End(xlUp).Row ' <-- get last row from Column "A", skips blank cells in te middle
    ' set the range to Columns A, F, K, AA
    Set CopyRng = Application.Union(.Range("A2:A" & N), .Range("F2:F" & N), .Range("K2:K" & N), .Range("AA2:AA" & N))
End With

Set Y = Workbooks.Open("C:\Desktop\Destination.xlsx")
With Y.Sheets("Data")
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 '<-- get first empty row at Column A to paste at
    CopyRng.Copy
    .Range("A" & LastRow).PasteSpecial xlPasteValues
End With
Y.Close True

Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.CutCopyMode = False

End Sub


问:
Play Framework and jQuery Ajax request with data as Array
I am sending an Array of values through Ajax via jQuery with a Play Framework backend, and I'm in front of a problem.

Here's an example :

```<code>$.ajax ({
    'type':     'POST',
    'url':          '/url',
    'timeout':  5000,
    'data':     {'ids': [0, 1, 2, 3]},
    'dataType': 'json',
    'success':  function (oData) {
        // Process ...
    }
});
</code>```

But in Play!, if I do a params.get("ids");, I got an empty value, and if I do a params.getAll("ids"); also.

I know where the problem is, jQuery send the data as : ids[]=0&ids[]=1&ids[]=2&ids[]=3
but Play! Framework expect array data to be sent as ids=0&ids=1&ids=2&ids=3

Is there a proper way to send the data properly (or get the data as an array in my controller) ?

So far, I managed to make it works simply but creating the request as a String manually in javascript.

Thanks for your help.

答:
This solution worked for me. Give it a try,</p>

```<code>// Sending request
var params = {
    myArray: [1, 2, 3, 4]
};
var url = '@controllers.routes.AppController.jquery()';
$.post(url, params, function (data) {
    // Process response here
});

// Receiving request
Map<String, String[]> params = request().body().asFormUrlEncoded();
Logger.debug("Params : " + params.size());
for (Map.Entry<String, String[]> param : params.entrySet()) {
    Logger.debug(param.getKey() + " = " + param.getValue()[0]);
}
</code>```

Body:
I am sending an Array of values through Ajax via jQuery with a Play Framework backend, and I'm in front of a problem.

Here's an example :

$.ajax ({
    'type':     'POST',
    'url':          '/url',
    'timeout':  5000,
    'data':     {'ids': [0, 1, 2, 3]},
    'dataType': 'json',
    'success':  function (oData) {
        // Process ...
    }
});

But in Play!, if I do a params.get("ids");, I got an empty value, and if I do a params.getAll("ids"); also.

I know where the problem is, jQuery send the data as : ids[]=0&ids[]=1&ids[]=2&ids[]=3
but Play! Framework expect array data to be sent as ids=0&ids=1&ids=2&ids=3

Is there a proper way to send the data properly (or get the data as an array in my controller) ?

So far, I managed to make it works simply but creating the request as a String manually in javascript.

Thanks for your help.

Body:
This solution worked for me. Give it a try,

// Sending request
var params = {
    myArray: [1, 2, 3, 4]
};
var url = '@controllers.routes.AppController.jquery()';
$.post(url, params, function (data) {
    // Process response here
});

// Receiving request
Map<String, String[]> params = request().body().asFormUrlEncoded();
Logger.debug("Params : " + params.size());
for (Map.Entry<String, String[]> param : params.entrySet()) {
    Logger.debug(param.getKey() + " = " + param.getValue()[0]);
}


问:
Laravel 5.4 - How to setup a optional parameter in a route. If it exists must be the word "home"?
I have the follow code from Laravel routes:

```<code>Route::group(['prefix'=>'{account}'], function (){

    Route::group(['prefix'=>'{location}'], function (){

        Route::get('/{home?}', function ($account,$location) {
            $loc=explode("_", $location);
            $locale = $loc[0];
            $country= $loc[1];
            App::setLocale($locale);
            return view('homeProfPublic')->with(['account' => $account,'active' => 'home','locale'=>$locale,"country"=>$country]);
        })->where('home', '/home/');
   });
});
</code>```

I want this route to catch:

mysite.com/bob/US_en

mysite.com/bob/US_en/

mysite.com/bob/US_en/home

In other words I want the word "home" to be optional, but if it is there, to be only the word "home". All previuos route should redirect to the home page.

mysite.com/bob/US_en/contact  //Should redirect to contact page.

How can I accomplish this task?

答:
You don't want to do this in the route itself.

Check out how packages like laravel-localization handle this, by creating and applying route middleware which handle your localization.
The middleware will handle setting the locale, and you can create a service to return the account based on the first part of the url for example. This eliminates the need of having this logic in your routes at all.

What you have right now, is that you use the value of the optional home parameter, where you actually just want to define 2 routes (/ and /home) to give the same output.

For the routes, I would suggest creating a controller action to handle displaying the view, and set up your routes to call the controller action instead of having this logic in your routes file. This takes away the need for duplicate code.

For example (using the localization package)

```<code>Route::group(
[
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]
],
function()
{
    Route::get('/', 'HomeController@index');

    Route::get('contact', 'ContactController@index');

    // add catchall as the last route in the group
    Route::get('{any}', 'HomeController@index')->where('any', '.*');
});
</code>```

This will allow /contact to show the contact page, and everything else will give the output of the HomeController@index controller action.

To be honest, I would rethink the re-directing to home instead of showing a 404 on a non-existing url. If something doesn't exist, it doesn't exist :)

```<code>Route::group(
[
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]
],
function()
{
    Route::get('/', 'HomeController@index');
    Route::get('home', 'HomeController@index');

    Route::get('contact', 'ContactController@index');
});
</code>```

Body:
I have the follow code from Laravel routes:

Route::group(['prefix'=>'{account}'], function (){

    Route::group(['prefix'=>'{location}'], function (){

        Route::get('/{home?}', function ($account,$location) {
            $loc=explode("_", $location);
            $locale = $loc[0];
            $country= $loc[1];
            App::setLocale($locale);
            return view('homeProfPublic')->with(['account' => $account,'active' => 'home','locale'=>$locale,"country"=>$country]);
        })->where('home', '/home/');
   });
});

I want this route to catch:

mysite.com/bob/US_en

mysite.com/bob/US_en/

mysite.com/bob/US_en/home

In other words I want the word "home" to be optional, but if it is there, to be only the word "home". All previuos route should redirect to the home page.

mysite.com/bob/US_en/contact  //Should redirect to contact page.

How can I accomplish this task?

Body:
You don't want to do this in the route itself.

Check out how packages like laravel-localization handle this, by creating and applying route middleware which handle your localization.
The middleware will handle setting the locale, and you can create a service to return the account based on the first part of the url for example. This eliminates the need of having this logic in your routes at all.

What you have right now, is that you use the value of the optional home parameter, where you actually just want to define 2 routes (/ and /home) to give the same output.

For the routes, I would suggest creating a controller action to handle displaying the view, and set up your routes to call the controller action instead of having this logic in your routes file. This takes away the need for duplicate code.

For example (using the localization package)

Route::group(
[
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]
],
function()
{
    Route::get('/', 'HomeController@index');

    Route::get('contact', 'ContactController@index');

    // add catchall as the last route in the group
    Route::get('{any}', 'HomeController@index')->where('any', '.*');
});

This will allow /contact to show the contact page, and everything else will give the output of the HomeController@index controller action.

To be honest, I would rethink the re-directing to home instead of showing a 404 on a non-existing url. If something doesn't exist, it doesn't exist :)

Route::group(
[
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]
],
function()
{
    Route::get('/', 'HomeController@index');
    Route::get('home', 'HomeController@index');

    Route::get('contact', 'ContactController@index');
});


问:
VBA loop through textboxes and insert each box on different row
I have much of this form

coded to what I want but I'm having difficulty with the most significant part of it. As shown in the image, the frame in the form with 30 textboxes is designed to have names entered in it. Each box has a different name. When I click "save data" button I want the names in the textboxes to be entered on the next available row on the worksheet, also in the image.

So, if the form has Bob, Joe, and Jane in the first three boxes, I'd want rows A:2-4 in the worksheet to be populated with each name respectively.

答:
If you can't (or don't want to) rely on textbox names, there are two possible ways out:

exploit TabIndex

if your textboxes inside "Individuals" frame have same TabIndex order as the cells you want to write their content into, then you could go as follows:

```<code>Dim i As Long
Dim strng As String

With Me.Frame1 '<--| change "Frame1" to your actual "Individuals" frame name
    For i = 0 To .Controls.Count - 1
        strng = strng & GetTextBox(i).Value & " "
    Next
    Cells(Rows.Count, 1).End(xlUp).Offset(1).Resize(.Controls.Count) = Application.Transpose(Split(Trim(strng), " "))
End With
</code>```

where you exploit the following Function:

```<code>Function GetTextBox(tabId As Long) As Control
    Dim ctrl As Control

    For Each ctrl In Me.Frame1.Controls
        If ctrl.TabIndex = tabId Then Exit For
    Next
    Set GetTextBox = ctrl
End Function
</code>```

exploit Top and Left control properties

if your textboxes are properly vertically aligned (i.e. all texboxes in the same row share the very same Top property), then you could go as follows:

```<code>    Dim dict As Object
    Dim ctrl As Control

    Set dict = CreateObject("Scripting.Dictionary")
    With dict
        For Each ctrl In Me.Frame1.Controls
            .Item(Format(ctrl.Top, "000") & "-" & Format(ctrl.Left, "000")) = ctrl
        Next
    End With
    SortDictionary dict

    Cells(Rows.Count, 1).End(xlUp).Offset(1).Resize(Me.Frame1.Controls.Count) = Application.Transpose(dict.items)
</code>```

where you exploit the following Function:

```<code>Sub SortDictionary(dict As Object)
    Dim i As Long
    Dim key As Variant

    With CreateObject("System.Collections.SortedList")
        For Each key In dict
            .Add key, dict(key)
        Next
        dict.RemoveAll
        For i = 0 To .Keys.Count - 1
            dict.Add .GetKey(i), .Item(.GetKey(i))
        Next
    End With
End Sub
</code>```

Body:
If you can't (or don't want to) rely on textbox names, there are two possible ways out:

exploit TabIndex

if your textboxes inside "Individuals" frame have same TabIndex order as the cells you want to write their content into, then you could go as follows:

Dim i As Long
Dim strng As String

With Me.Frame1 '<--| change "Frame1" to your actual "Individuals" frame name
    For i = 0 To .Controls.Count - 1
        strng = strng & GetTextBox(i).Value & " "
    Next
    Cells(Rows.Count, 1).End(xlUp).Offset(1).Resize(.Controls.Count) = Application.Transpose(Split(Trim(strng), " "))
End With

where you exploit the following Function:

Function GetTextBox(tabId As Long) As Control
    Dim ctrl As Control

    For Each ctrl In Me.Frame1.Controls
        If ctrl.TabIndex = tabId Then Exit For
    Next
    Set GetTextBox = ctrl
End Function

exploit Top and Left control properties

if your textboxes are properly vertically aligned (i.e. all texboxes in the same row share the very same Top property), then you could go as follows:

    Dim dict As Object
    Dim ctrl As Control

    Set dict = CreateObject("Scripting.Dictionary")
    With dict
        For Each ctrl In Me.Frame1.Controls
            .Item(Format(ctrl.Top, "000") & "-" & Format(ctrl.Left, "000")) = ctrl
        Next
    End With
    SortDictionary dict

    Cells(Rows.Count, 1).End(xlUp).Offset(1).Resize(Me.Frame1.Controls.Count) = Application.Transpose(dict.items)

where you exploit the following Function:

Sub SortDictionary(dict As Object)
    Dim i As Long
    Dim key As Variant

    With CreateObject("System.Collections.SortedList")
        For Each key In dict
            .Add key, dict(key)
        Next
        dict.RemoveAll
        For i = 0 To .Keys.Count - 1
            dict.Add .GetKey(i), .Item(.GetKey(i))
        Next
    End With
End Sub


问:
Pandas Dataframe: Split a column into multiple columns
I have a pandas dataframe with columns names as: (columns type as Object)

```<code>1. x_id
2. y_id
3. Sentence1
4. Sentences2
5. Label
</code>```

I want to separate sentences1 and sentence2 into multiple columns in same dataframe.

Here is an example: dataframe names as df

```<code>x_id     y_id     Sentence1          Sentence2          Label
0        2        This is a ball     I hate you         0
1        5        I am a boy         Ahmed Ali          1
2        1        Apple is red       Rose is red        1
3        9        I love you so much Me too             1
</code>```

After splitting the columns[Sentence1,Sentence2] by ' ' Space, dataframe looks like:

```<code>x_id     y_id     1     2     3    4     5      6      7     8      Label
0        2        This  is    a    ball  NONE   I      hate  you    0
1        5        I     am    a    boy   NONE   Ahmed  Ali   NONE   1
2        1        Apple is    red  NONE  NONE   Rose   is    red    1
3        9        I     love  you  so    much   Me     too   NONE   1
</code>```

How to split the columns like this in python? How to do this using pandas dataframe?

答:
```<code>In [26]: x = pd.concat([df.pop('Sentence1').str.split(expand=True),
    ...:                df.pop('Sentence2').str.split(expand=True)],
    ...:               axis=1)
    ...:

In [27]: x.columns = np.arange(1, x.shape[1]+1)

In [28]: x
Out[28]:
       1     2    3     4     5      6     7     8
0   This    is    a  ball  None      I  hate   you
1      I    am    a   boy  None  Ahmed   Ali  None
2  Apple    is  red  None  None   Rose    is   red
3      I  love  you    so  much     Me   too  None

In [29]: df = df.join(x)

In [30]: df
Out[30]:
   x_id  y_id  Label      1     2    3     4     5      6     7     8
0     0     2      0   This    is    a  ball  None      I  hate   you
1     1     5      1      I    am    a   boy  None  Ahmed   Ali  None
2     2     1      1  Apple    is  red  None  None   Rose    is   red
3     3     9      1      I  love  you    so  much     Me   too  None
</code>```

Body:
I have a pandas dataframe with columns names as: (columns type as Object)

1. x_id
2. y_id
3. Sentence1
4. Sentences2
5. Label

I want to separate sentences1 and sentence2 into multiple columns in same dataframe.

Here is an example: dataframe names as df

x_id     y_id     Sentence1          Sentence2          Label
0        2        This is a ball     I hate you         0
1        5        I am a boy         Ahmed Ali          1
2        1        Apple is red       Rose is red        1
3        9        I love you so much Me too             1

After splitting the columns[Sentence1,Sentence2] by ' ' Space, dataframe looks like:

x_id     y_id     1     2     3    4     5      6      7     8      Label
0        2        This  is    a    ball  NONE   I      hate  you    0
1        5        I     am    a    boy   NONE   Ahmed  Ali   NONE   1
2        1        Apple is    red  NONE  NONE   Rose   is    red    1
3        9        I     love  you  so    much   Me     too   NONE   1

How to split the columns like this in python? How to do this using pandas dataframe?


问:
Puma Rails 5 binding.pry only available for 60 seconds before timeout
Puma times out my request when I'm using binding.pry. In my controller

```<code>def new
  require 'pry'
  binding.pry
end
</code>```

I then make a request that hits the controller and enter the pry session. After 60 seconds Puma? times out my request, restarts a worker and subsequently blows up by debugging session.

```<code>[1] pry(#<Agent::ClientsController>)> [3522] ! Terminating timed out worker: 3566
[3522] - Worker 0 (pid: 4171) booted, phase: 0
</code>```

I generated this app with suspenders if that matters. How do I extend my debugging session in rails 5?

答:
How about this?

```<code># config/puma.rb
...

environment ENV['RACK_ENV'] || 'development'

...

if ENV['RACK_ENV'] == 'development'
  worker_timeout 3600
end
</code>```

Edit (Rails 5.1.5):

Because ENV['RACK_ENV'] was empty, I did the following:

```<code># config/puma.rb

...

if ENV.fetch('RAILS_ENV') == 'development'
   puts "LOGGER: development => worker_timeout 3600"
   worker_timeout 3600
end
</code>```

Body:
Puma times out my request when I'm using binding.pry. In my controller

def new
  require 'pry'
  binding.pry
end

I then make a request that hits the controller and enter the pry session. After 60 seconds Puma? times out my request, restarts a worker and subsequently blows up by debugging session.

[1] pry(#<Agent::ClientsController>)> [3522] ! Terminating timed out worker: 3566
[3522] - Worker 0 (pid: 4171) booted, phase: 0

I generated this app with suspenders if that matters. How do I extend my debugging session in rails 5?

Body:
How about this?

# config/puma.rb
...

environment ENV['RACK_ENV'] || 'development'

...

if ENV['RACK_ENV'] == 'development'
  worker_timeout 3600
end

Edit (Rails 5.1.5):

Because ENV['RACK_ENV'] was empty, I did the following:

# config/puma.rb

...

if ENV.fetch('RAILS_ENV') == 'development'
   puts "LOGGER: development => worker_timeout 3600"
   worker_timeout 3600
end


问:
Our application uploads hundreds of videos per day using the YouTube API, but now getting quota exceeded errors
My application allows users to "link" their YouTube accounts to our system and then we allow them to upload videos to their channels both automatically in some cases, and on an "upload" action on their part. We have hundreds of videos being uploaded because we have thousands of users that use our system.

Today I saw hundreds of errors in my application when our batch automatic upload job was running. The errors were for:

quotaExceeded, video upload limit reached.

My API quotas are very high (50,000,000 per day, 3,000,000 per 100 seconds, 300,000 per 100 seconds per user), so if a video is 1600 points, I have enough limit to upload 30,000+ per day, 1,800 videos per 100 seconds, and 180+ per 100 seconds per user.

I have seen other questions out there hinting at some newly enforced limit by Google to just 50 videos and then 1 video every 15 minutes? This is a very low limit for my application which has such a large quota! To be clear, at most I have seen my application handle 1,000 videos in a single day (1,600,000 points of my total 50,000,000 quota).

Is there any way I can get this artificial limit of 50 videos and then 1 per 15 minutes removed? This is a major block to my users' functionality for a very popular web app. I could understand if it were 50 videos per user and then 1 every 15 minutes, but I highly doubt my errors this morning were from one user trying to upload 300+ videos at a time. My system only uploads their "newest" videos each day, which most people only have 1-10 videos at max. Hundreds would be a very rare edge case.

答:
You can actually confirm in your Developers Console the available quota for your application. By default, YouTube API have a quota allocation of 1 million units per day as mentioned in Quota usage. If you see that your usage reached your quota limit, you can request additional quota on the Quotas tab.

Note also that, all API requests, including invalid requests, incur a quota cost of at least one point. You may use the Quota Calculator to get an estimate of the quota cost for an API query.

On the other hand, to work efficiently with your quota and if you haven't done so, I suggest that you implement exponential backoff if you're encountering high error ratio. See this sample code which shows an exponential backoff strategy to resume a failed upload. Also, if applicable, subscribe to Push Notifications which is much more efficient than polling-based solutions.

Check the documentation for more information on how PubSubHubbub callback server receives Atom feed notifications when a channel does any of the following activities:

uploads a video

updates a video's title

updates a video's description

Hope that helps!


问:
Calculate distance using google map given a latitude and longitude
I am developing a desktop application and I have two point (latitude, longitude). How can I get the distance between these two points? I have looked at the API and most of them are javascript or web based. I am not developing a web page. How can I do this in java?

I want a road distance, not a straight distance

答:
If you've got the latitude and longitude, you can use the Haversine formula to calculate the distance between them - assuming you want "straight line" distance.

EDIT: Okay, now you've actually told us what you want, I suspect you need to use the Directions API. You'll need to make a web request to the appropriate URL with your parameters, specifying either XML or JSON output - which you'll then need to parse.

Note that "JSON" != "Javascript-based". Think of JSON as a data serialization format which just happens to be executable Javascript.


答:
If you use RecyleView. You have to use onLongClickListener() event on Adapter of RecyleView. Just like -

```<code>    @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                final ViewHolder holder = (ViewHolder) holder;

                //go news details fragment
                holder.newsContentLayout.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public void onLongClick(View v) {
                    // change you cardview background
                     holder.cvCardView.setImageDrawable(holder.cvCardView.getContext().getResources()
                          .getDrawable(R.drawable.bg_cardview));

                    }
                });
        }
</code>```

If you use ListView then you can do it by -

```<code>listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

          CardView cardView = (CardView)  view.findViewById(R.id.cardview);
            cardView.setBackgroundDrawable(getApplicationContext().getResources().getD    rawable(R.drawable.background));
                    return false;
                }
            });
</code>```

Title: Change Background of Items on Long Press

Body:
I want to change the background of Card View on Long Press and I have visited so many forum but no one gave the proper answer.

So, How to change the background of list/card/recycler view just like the long press on navigation view items ??

Body:
If you use RecyleView. You have to use onLongClickListener() event on Adapter of RecyleView. Just like -

    @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                final ViewHolder holder = (ViewHolder) holder;

                //go news details fragment
                holder.newsContentLayout.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public void onLongClick(View v) {
                    // change you cardview background
                     holder.cvCardView.setImageDrawable(holder.cvCardView.getContext().getResources()
                          .getDrawable(R.drawable.bg_cardview));

                    }
                });
        }

If you use ListView then you can do it by -

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

          CardView cardView = (CardView)  view.findViewById(R.id.cardview);
            cardView.setBackgroundDrawable(getApplicationContext().getResources().getD    rawable(R.drawable.background));
                    return false;
                }
            });


问:
CakePHP 3 Error on using SplFileInfo class
i'm getting the next error:
Error: Class 'App\JL\SplFileInfo' not found  while trying to create a SplFileInfo class like this: $i = new SplFileInfo($P['Carpeta'].DS.$v);
i tested this with same results: $i = new SplFileInfo('');
this is in a cutom class called JL in namespace App\JL and calling it like use App\JL\JL;

The function is declared like this: public static function LeerArchivos(&$P = array()) {

i'm working in an element to be shown on a template...

¿Do i have to activate somethig? or ¿What am i doing wrong?

答:
The problem is that you don't know how namespaces work. You should fix that gap in your knowledge first: http://php.net/manual/en/language.namespaces.php

You need to "import" the class from the "root" namespace \ into your current namespace \App\JL\JL. This us done via the use keyword. See the documentation for it.


问:
How do I install AcmeDemoBundle on Symfony 2.8
How do I install AcmeDemoBundle on Symfony 2.8?

I have Symfony 2.8 and I dont't have AcmeDemoBundle in this version of Symfony, but I want it. It is possible install this bundle? And how may I do it?

答:
If you want a demo of Symfony, the best is to use git clone https://github.com/symfony/symfony-demo

AcmeDemoBundle is deprecated since long time!


问:
Jenkins pipeline shared library vs plugin
I am working on Jenkins pipeline for two projects. I built some customized configuration alerts messages via slack and emails. We expect my code can be used for my projects and also several other projects. So I am thinking to make it a small lib so that others don't need to ask me every time they onboard a Jenkins pipeline jobs. I was thinking using shared library  with @Library() for other to use, as described in the docs.

However, since my lib depends on the existence of slack and emails plugin, it will not be usable when these plugin are not installed.

My question is: is there are way to declare dependency in pipeline Shared Libraries or I have to make jenkins plugin to address this issue?

答:
As far as I know there is no way to declare dependencies to plugins right now (or version of Jenkins). Instead, what you can do is add a check for the plugin and give a proper error to the user of your library:

```<code>if (Jenkins.getInstance().getPluginManager().getPlugin("Slack+Plugin") == null) {
  error "This shared library function requires "Slack plugin!"
}
</code>```

Put this at the start of your shared library script, before any uses of the plugin. Note though, this gets tricky if you need to import classes from a plugin (since imports goes first in the groovy file). What you do in that situation is to make two scripts, the first script has the check and is the one the user calls, the second contains all the logic and imports, and is called by the first script once the checks pass.

Body:
As far as I know there is no way to declare dependencies to plugins right now (or version of Jenkins). Instead, what you can do is add a check for the plugin and give a proper error to the user of your library:

if (Jenkins.getInstance().getPluginManager().getPlugin("Slack+Plugin") == null) {
  error "This shared library function requires "Slack plugin!"
}

Put this at the start of your shared library script, before any uses of the plugin. Note though, this gets tricky if you need to import classes from a plugin (since imports goes first in the groovy file). What you do in that situation is to make two scripts, the first script has the check and is the one the user calls, the second contains all the logic and imports, and is called by the first script once the checks pass.


问:
Parsing tabular data in ansible
Trying to parse route information in ansible to something like below.
What's the right way to do</p>

```<code>[
   {
      "destination":  '10.110.2.192',
      "gateway":  '10.110.0.129'
      "interface": 'eth2'
    },
    {
      "destination": '10.110.2.64',
       "gateway":   '10.110.0.129'
       "interface": 'eth2'
     },
    {
      "destination": '10.110.1.0',
      "gateway": '0.0.0.0'
       "interface": 'eth0'
     },
    {
      "destination": '10.110.1.128',
      "gateway": '0.0.0.0'
       "interface": 'eth2'
     },
    {
      "destination": '0.0.0.0',
      "gateway": '10.110.1.1'
      "interface": 'eth0'
     }
]
</code>```

答:
You can take this as example:

First part is native Ansible with regex search, and second part uses jq on remote host as helper.

```<code>---
- hosts: server
  gather_facts: no
  tasks:
    # without jq on remote host
    - command: netstat -nrw
      register: routes
    - debug:
        msg: "{{ route }}"
      with_items: "{{ routes.stdout_lines[2:] }}"
      vars:
        route: '{{ item | regex_search(regex,"\g<dest>","\g<gw>","\g<mask>","\g<flags>","\g<iface>") }}'
        regex: '^(?P<dest>\S+)\s+(?P<gw>\S+)\s+(?P<mask>\S+)\s+(?P<flags>\S+).*\s(?P<iface>\S+)$'
    # with jq on remote host
    - shell: netstat -nrw | tail -n+3 | jq -R -c 'capture("^(?<dest>\\S+)\\s+(?<gw>\\S+)\\s+(?<mask>\\S+)\\s+(?<flags>\\S+).*\\s(?<iface>\\S+)$")'
      register: routes
    - debug:
        msg: "{{ item }}"
      with_items: "{{ routes.stdout_lines | map('from_json') | list }}"
</code>```

Title: Parsing tabular data in ansible

Body:
Trying to parse route information in ansible to something like below.
What's the right way to do

[
   {
      "destination":  '10.110.2.192',
      "gateway":  '10.110.0.129'
      "interface": 'eth2'
    },
    {
      "destination": '10.110.2.64',
       "gateway":   '10.110.0.129'
       "interface": 'eth2'
     },
    {
      "destination": '10.110.1.0',
      "gateway": '0.0.0.0'
       "interface": 'eth0'
     },
    {
      "destination": '10.110.1.128',
      "gateway": '0.0.0.0'
       "interface": 'eth2'
     },
    {
      "destination": '0.0.0.0',
      "gateway": '10.110.1.1'
      "interface": 'eth0'
     }
]

Body:
You can take this as example:

First part is native Ansible with regex search, and second part uses jq on remote host as helper.

---
- hosts: server
  gather_facts: no
  tasks:
    # without jq on remote host
    - command: netstat -nrw
      register: routes
    - debug:
        msg: "{{ route }}"
      with_items: "{{ routes.stdout_lines[2:] }}"
      vars:
        route: '{{ item | regex_search(regex,"\g<dest>","\g<gw>","\g<mask>","\g<flags>","\g<iface>") }}'
        regex: '^(?P<dest>\S+)\s+(?P<gw>\S+)\s+(?P<mask>\S+)\s+(?P<flags>\S+).*\s(?P<iface>\S+)$'
    # with jq on remote host
    - shell: netstat -nrw | tail -n+3 | jq -R -c 'capture("^(?<dest>\\S+)\\s+(?<gw>\\S+)\\s+(?<mask>\\S+)\\s+(?<flags>\\S+).*\\s(?<iface>\\S+)$")'
      register: routes
    - debug:
        msg: "{{ item }}"
      with_items: "{{ routes.stdout_lines | map('from_json') | list }}"


问:
Is a good convention using semicolon at the end of the line when using ES6 in babel
I saw several examples on the web of tutorials using redux and react where the code of omitting the semicolon when using es6 with babel.

Example semicolon at the end of import, export.

What is the reason?

What is a good practice?

Missing semicolon

```<code>import React, { PropTypes } from 'react'

const Location = ({ onClick, name, country}) => (
    <li
        onClick={onClick}
    >
        {name} {country}
    </li>
)

export default Location
</code>```

vs with semicolon

```<code>import React, { PropTypes } from 'react';

const Location = ({ onClick, name, country}) => (
    <li
        onClick={onClick}
    >
        {name} {country}
    </li>
);

export default Location;
</code>```

答:
Referring to ASI section of ES documentation confirms the following.

Most ECMAScript statements and declarations must be terminated with a semicolon. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

In your case, ES6 is being used through babel. It's a transpiler and it may add the missed semicolons in the process of transpiling the source text to native JS.

IMO, good practice is to enable ES linter and it can help to avoid most of the silly mistakes that can culminate the application in undefined state at later point in the time line.

This link can give you some more information.

Body:
I saw several examples on the web of tutorials using redux and react where the code of omitting the semicolon when using es6 with babel.

Example semicolon at the end of import, export.

What is the reason?

What is a good practice?

Missing semicolon

import React, { PropTypes } from 'react'

const Location = ({ onClick, name, country}) => (

        {name} {country}

)

export default Location

vs with semicolon

import React, { PropTypes } from 'react';

const Location = ({ onClick, name, country}) => (

        {name} {country}

);

export default Location;


问:
Disable specific week day according to the day number(0,1,2,....,6)
I'm trying to disable all weekdays in JQuery UI datepicker and keep one day on and not disabled according to the day number that i write in the textbox nb.

Is there a way to do that?

My code is:

day number: <input type="text" id="nb">

Date: <input type="text" id="datepicker">
```

Notice about day number :

sunday is day 0, monday is day 1 ,..., wednesday is day 3,.....

FOR EXAMPLE : if i write 3 in the textbox nb, so i want only to turn wednesday on in the datepicker

答:
You need to use beforeShowDay method

```<code>$('#datepicker').datepicker({
    beforeShowDay: function(date) {
        var weekDay = parseInt($('#nb').val(), 10);
        if (weekDay === date.getDay()) {
            return [true, '', ''];
        }
        return [false, '', ''];
    }
});
</code>```

https://jsfiddle.net/x8jcd48c/

Body:
I'm trying to disable all weekdays in JQuery UI datepicker and keep one day on and not disabled according to the day number that i write in the textbox nb.

Is there a way to do that?

My code is:

day number: <input type="text" id="nb">

Date: <input type="text" id="datepicker">

Notice about day number :

sunday is day 0, monday is day 1 ,..., wednesday is day 3,.....

FOR EXAMPLE : if i write 3 in the textbox nb, so i want only to turn wednesday on in the datepicker

Body:
You need to use beforeShowDay method

$('#datepicker').datepicker({
    beforeShowDay: function(date) {
        var weekDay = parseInt($('#nb').val(), 10);
        if (weekDay === date.getDay()) {
            return [true, '', ''];
        }
        return [false, '', ''];
    }
});

https://jsfiddle.net/x8jcd48c/


问:
Need the SQL query to find this result
This is the source table with data

```<code>PARENT_ID   PARENT_NAME CHILD_GENDER
------------------------------------
1111        AAA         M
1111        AAA         F
1234        BBB         M
1234        BBB         M
1235        CCC         M
1236        DDD         F
1236        DDD         F
1236        DDD         M
1237        EEE         M
1237        EEE         M
1237        EEE         F
1238        FFF         F
1239        GGG         F
1239        GGG         F
</code>```

And I need to find out the Parent_ID who has children with gender both M & F.

The required output is this:

```<code>PARENT_ID   PARENT_NAME CHILD_GENDER
------------------------------------
1111        AAA         M
1111        AAA         F
1236        DDD         F
1236        DDD         F
1236        DDD         M
1237        EEE         M
1237        EEE         M
1237        EEE         F
</code>```

What is the SQL query?

答:
You can use aggregation to find out the parent_ids that have children of both gender (hence the distinct count 2) and join with your original table to get the corresponding rows.</p>

```<code>select t.*
from your_table t
join (
    select parent_id
    from your_table
    group by parent_id
    having count(distinct child_gender) = 2
    ) t2 on t.parent_id = t2.parent_id;
</code>```

Title: Need the SQL query to find this result

Body:
This is the source table with data

PARENT_ID   PARENT_NAME CHILD_GENDER
------------------------------------
1111        AAA         M
1111        AAA         F
1234        BBB         M
1234        BBB         M
1235        CCC         M
1236        DDD         F
1236        DDD         F
1236        DDD         M
1237        EEE         M
1237        EEE         M
1237        EEE         F
1238        FFF         F
1239        GGG         F
1239        GGG         F

And I need to find out the Parent_ID who has children with gender both M & F.

The required output is this:

PARENT_ID   PARENT_NAME CHILD_GENDER
------------------------------------
1111        AAA         M
1111        AAA         F
1236        DDD         F
1236        DDD         F
1236        DDD         M
1237        EEE         M
1237        EEE         M
1237        EEE         F

What is the SQL query?

Body:
You can use aggregation to find out the parent_ids that have children of both gender (hence the distinct count 2) and join with your original table to get the corresponding rows.

select t.*
from your_table t
join (
    select parent_id
    from your_table
    group by parent_id
    having count(distinct child_gender) = 2
    ) t2 on t.parent_id = t2.parent_id;


问:
Get json from misformatted json string
I have a json string, which look like that:

```<code>data: { "type": "add",
"newsId": "5da979e0-161d-11e7-9e14-bd201bbe920c",
"articleId": "null",
"category": "news",
"timestamp": "1490970103941",
"id": "5daa8b50-161d-11e7-9e14-bd201bbe920c"}
</code>```

I've created pojo to parse this json using Gson.

```<code>public class SSENewsEvent {

    private String type;

    private String newsId;

    private String articleId;

    private String category;

    private String timestamp;

    private String id;
}
</code>```

But, as you can see, it cannot be parsed because it's somehow misformatted by this

```<code>data:
</code>```

at the beginning of the string. Can you help me to find the best way to parse this string?

答:
You can follow this way:

```<code>myObj = {
    "type": "add",
    "newsId": "5da979e0-161d-11e7-9e14-bd201bbe920c",
     "articleId": "null",
     "category": "news",
     "timestamp": "1490970103941",
     "id": "5daa8b50-161d-11e7-9e14-bd201bbe920c"
 }
var type = myObj.type;
var newsId= myObj.newsId;
var articleId=myObj.articleId;
var category= myObj.category;
var timestamp= myObj.timestamp;
var id=myObj.id;
</code>```

Hope it will help you

Title: Get json from misformatted json string

Body:
I have a json string, which look like that:

data: { "type": "add",
"newsId": "5da979e0-161d-11e7-9e14-bd201bbe920c",
"articleId": "null",
"category": "news",
"timestamp": "1490970103941",
"id": "5daa8b50-161d-11e7-9e14-bd201bbe920c"}

I've created pojo to parse this json using Gson.

public class SSENewsEvent {

    private String type;

    private String newsId;

    private String articleId;

    private String category;

    private String timestamp;

    private String id;
}

But, as you can see, it cannot be parsed because it's somehow misformatted by this

data:

at the beginning of the string. Can you help me to find the best way to parse this string?

Body:
You can follow this way:

myObj = {
    "type": "add",
    "newsId": "5da979e0-161d-11e7-9e14-bd201bbe920c",
     "articleId": "null",
     "category": "news",
     "timestamp": "1490970103941",
     "id": "5daa8b50-161d-11e7-9e14-bd201bbe920c"
 }
var type = myObj.type;
var newsId= myObj.newsId;
var articleId=myObj.articleId;
var category= myObj.category;
var timestamp= myObj.timestamp;
var id=myObj.id;

Hope it will help you


问:
Complex List Comprehension slower than straight loop
I saw an interesting solution for a programming exercise on leetcode  It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:

Snippet 1

```<code>def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]
</code>```

Snippet 2

```<code>def fizzBuzz(n):
    out = []
    for i in range(1, n+1):
        if i % 3 == 0 and i % 5 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))

    return out
</code>```

However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.

What is making Snippet 1 slow?

答:
your snippet

```<code>def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]
</code>```

performs a lot of string concatenations (even with empty strings). I traded that with an extra modulo operation which saves the concatenation and it's already faster.

```<code>def fizzBuzz3(n):
    return  ["FizzBuzz" if not i%15 else "Fizz" if not i%3 else "Buzz" if not i%5 else str(i) for i in range(1, n+1)]
</code>```

and BTW on my machine, both comprehensions are faster than the "classical" approach so I get different results than you stated:

```<code>your comp: 4.927702903747559
my listcomp: 4.343341112136841
classical: 6.015967845916748
</code>```

So my optimized listcomp wins (and seems to win too on your machine), even if I'm not satisfied with the extra modulo operations induced by the flow control of the listcomp)

My test protocol is performing 10000 times the operation with n=1000:

```<code>import time
start_time = time.time()
for i in range(10000):
    fizzBuzz2(1000)
print("your comp:",time.time()-start_time)
start_time = time.time()
for i in range(10000):
    fizzBuzz3(1000)
print("my listcomp:",time.time()-start_time)
start_time = time.time()
for i in range(10000):
    fizzBuzz(1000)
print("classical:",time.time()-start_time)
</code>```

note that even with pre-computing the modulos in the "classical" approach, it drops to 5.375272035598755 seconds (which is good) but still worse than listcomps because of all the instructions (you also kill the listcomp speed by calling a method to save modulo computations). I guess that python is not the proper language to obtain the fastest speed in that case.

Body:
I saw an interesting solution for a programming exercise on leetcode  It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:

Snippet 1

def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]

Snippet 2

def fizzBuzz(n):
    out = []
    for i in range(1, n+1):
        if i % 3 == 0 and i % 5 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))

    return out

However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.

What is making Snippet 1 slow?

Body:
your snippet

def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]

performs a lot of string concatenations (even with empty strings). I traded that with an extra modulo operation which saves the concatenation and it's already faster.

def fizzBuzz3(n):
    return  ["FizzBuzz" if not i%15 else "Fizz" if not i%3 else "Buzz" if not i%5 else str(i) for i in range(1, n+1)]

and BTW on my machine, both comprehensions are faster than the "classical" approach so I get different results than you stated:

your comp: 4.927702903747559
my listcomp: 4.343341112136841
classical: 6.015967845916748

So my optimized listcomp wins (and seems to win too on your machine), even if I'm not satisfied with the extra modulo operations induced by the flow control of the listcomp)

My test protocol is performing 10000 times the operation with n=1000:

import time
start_time = time.time()
for i in range(10000):
    fizzBuzz2(1000)
print("your comp:",time.time()-start_time)
start_time = time.time()
for i in range(10000):
    fizzBuzz3(1000)
print("my listcomp:",time.time()-start_time)
start_time = time.time()
for i in range(10000):
    fizzBuzz(1000)
print("classical:",time.time()-start_time)

note that even with pre-computing the modulos in the "classical" approach, it drops to 5.375272035598755 seconds (which is good) but still worse than listcomps because of all the instructions (you also kill the listcomp speed by calling a method to save modulo computations). I guess that python is not the proper language to obtain the fastest speed in that case.


问:
How to Logout of an Application Where I Used OAuth2 To Login With Google?
In my application, I implemented Google signout using jsapi.

I used the url https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=xxxxxx to connect to Google and then https://www.googleapis.com/plus/v1/people/xxxxxx to get user data from google profile.

Now I need to signout the user from Google while clicking a button from my application. How can I implement this in JavaScript, or at least it must ask the Google login page every time the user signs in.

I have tried approval_prompt=force, but seems not to be working.

答:
This works to sign the user out of the application, but not Google.

```<code>var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
  console.log('User signed out.');
});
</code>```

Source: https://developers.google.com/identity/sign-in/web/sign-in

Body:
This works to sign the user out of the application, but not Google.

var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
  console.log('User signed out.');
});

Source: https://developers.google.com/identity/sign-in/web/sign-in

ContentLicense: CC BY-SA 4.0


问:
Changing text colour of a text view using a spinner
So I am attempting to use a spinner to change the text colour of a message in a text view. However, when I attempt to use the function attached to my button click the activity crashes. I have attached the relevant part of the java code and the xml file

```<code>import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;

public class Colour extends AppCompatActivity {

private Spinner mySpinner;
public static final String EXTRA_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_colour);
    Intent intent = getIntent();
    String messageText = intent.getStringExtra(EXTRA_MESSAGE);
    TextView messageView = (TextView)findViewById(R.id.message);
    messageView.setText(messageText);
}

public void change(View v){
    String text = mySpinner.getSelectedItem().toString();
    TextView newColour = (TextView) findViewById(R.id.message);
    if(text == "Red"){
        newColour.setTextColor(Color.RED);
    }
    if(text == "Blue"){
        newColour.setTextColor(Color.BLUE);
    }
    if(text == "Green"){
        newColour.setTextColor(Color.GREEN);
    }
}
</code>```

XML file:

```<code><TextView
    android:textColor="#000000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/message" />

<Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/colours"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="16dp"
    android:id="@+id/spinner" />

<Button
    android:text="HOME"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:onClick="home"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp" />

<Button
    android:text="changeColour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button4"
    android:layout_above="@+id/button"
    android:layout_alignStart="@+id/button"
    android:layout_marginBottom="101dp"
    android:onClick="change" />
</code>```

答:
mySpinner is not initialized before access it's method. please initialize mySpinner first. use following code</p>

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mySpinner = (Spinner)findViewById(R.id.spinner);

    }

public void change(View v){
        String text = mySpinner.getSelectedItem().toString();
        TextView newColour = (TextView) findViewById(R.id.message);
        if(text.equals("Red")){
            newColour.setTextColor(Color.RED);
        }
        if(text.equals("Blue")){
            newColour.setTextColor(Color.BLUE);
        }
        if(text.equals("Green")){
            newColour.setTextColor(Color.GREEN);
        }
    }
</code>```

Body:
So I am attempting to use a spinner to change the text colour of a message in a text view. However, when I attempt to use the function attached to my button click the activity crashes. I have attached the relevant part of the java code and the xml file

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;

public class Colour extends AppCompatActivity {

private Spinner mySpinner;
public static final String EXTRA_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_colour);
    Intent intent = getIntent();
    String messageText = intent.getStringExtra(EXTRA_MESSAGE);
    TextView messageView = (TextView)findViewById(R.id.message);
    messageView.setText(messageText);
}

public void change(View v){
    String text = mySpinner.getSelectedItem().toString();
    TextView newColour = (TextView) findViewById(R.id.message);
    if(text == "Red"){
        newColour.setTextColor(Color.RED);
    }
    if(text == "Blue"){
        newColour.setTextColor(Color.BLUE);
    }
    if(text == "Green"){
        newColour.setTextColor(Color.GREEN);
    }
}

XML file:

<TextView
    android:textColor="#000000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/message" />

<Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/colours"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="16dp"
    android:id="@+id/spinner" />

<Button
    android:text="HOME"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:onClick="home"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp" />

<Button
    android:text="changeColour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button4"
    android:layout_above="@+id/button"
    android:layout_alignStart="@+id/button"
    android:layout_marginBottom="101dp"
    android:onClick="change" />

Body:
mySpinner is not initialized before access it's method. please initialize mySpinner first. use following code

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mySpinner = (Spinner)findViewById(R.id.spinner);

    }

public void change(View v){
        String text = mySpinner.getSelectedItem().toString();
        TextView newColour = (TextView) findViewById(R.id.message);
        if(text.equals("Red")){
            newColour.setTextColor(Color.RED);
        }
        if(text.equals("Blue")){
            newColour.setTextColor(Color.BLUE);
        }
        if(text.equals("Green")){
            newColour.setTextColor(Color.GREEN);
        }
    }


问:
Sphinx PDF output using latexpdf
I am trying to build Sphinx doc output as PDF rather than HTML. I can only use the tools which come with Sphinx, i.e. I cannot download additionl tools like rst2pdf. I have tried using 'make latexpdf', per the Sphinx documentation, which states it will produce pdf in addition to the .tex files. However I am only getting .tex. What am I missing? The Sphinx documentation states that PDF files will be produced.</p>

答:
Sphinx uses Latex to export the documentation as a PDF file.

Thus one needs the basic Latex dependencies used to write a pdf on the system.

For example, on a system running Ubuntu 16.04, they can be downloaded and installed by :

apt-get install texlive-latex-recommended texlive-latex-extra texlive-fonts-recommended

 If running Sphinx 1.6 or above on GNU/Linux or OSX, you may also need the latexmk package.

  Reference: sphinx.builders.latex.LaTeXBuilder documentation.

After installing the above packages, running  make latexpdf in the sphinx project directory generates the documentation output as the PDF file ./_build/latex/<sphinx-project-name>.pdf>

Note: In the current scenario where you do not see a PDF file on your system after running make latexpdf, check the output of the command for any errors regarding missing latex tools/files. Use the system package manager to identify the missing packages and install them.

Title: Sphinx PDF output using latexpdf


问:
Populate drop-down list in HTML using JSON data
I'm a student and very new to code. I've created a drop-down list using HTML and CSS, and I'm trying to populate it using data from JSON. This is my HTML code:

```<code>    <div class="dropdown">
  <button class="dropbtn">Choose your area</button>
  <div class="dropdown-content">
    <a href="#">Place 1</a>
    <a href="#">Place 2</a>
    <a href="#">Place 3</a>

  </div>
</div>
</code>```

I'm trying to replace 'Place 1', 'Place 2' etc with about 150 real place names. These are in JSON:

```<code>    "areaNames": [
 {
   "A": 1,
   "B": "Barking & Dagenham"
 },
 {
   "A": 2,
   "B": "Barnet"
 },
</code>```

and so on. How do I pull in the place names from JSON to be in the place of  'Place 1', 'Place 2' etc? I've tried following the advice in response to similar tutorials but that seems to give me a list of several separate drop-down boxes rather than a simple list of places.

Thanks for your help.

Body:
I'm a student and very new to code. I've created a drop-down list using HTML and CSS, and I'm trying to populate it using data from JSON. This is my HTML code:

  <button class="dropbtn">Choose your area</button>

    Place 1
    Place 2
    Place 3

I'm trying to replace 'Place 1', 'Place 2' etc with about 150 real place names. These are in JSON:

    "areaNames": [
 {
   "A": 1,
   "B": "Barking & Dagenham"
 },
 {
   "A": 2,
   "B": "Barnet"
 },

and so on. How do I pull in the place names from JSON to be in the place of  'Place 1', 'Place 2' etc? I've tried following the advice in response to similar tutorials but that seems to give me a list of several separate drop-down boxes rather than a simple list of places.

Thanks for your help.

Body:
I believe you have already loaded the JSON data in the DOM so you can access the data in your javascript.
Are you using any javascript library or framework like - jQuery, AngularJS or plain Javascript?
It is always better to organize your javascript code externally in a file with extension .js and load it in your HTML using <script> tag within <head> or <body> section.

Steps to generate the anchor tags dynamically in an HTML:

Get the Data from JSON into the DOM object (javascript)

Create/track the parent HTML element which will contain the options. Keep this reference in a variable.

Iterate into the data array (or objects) accessed from the JSON

Get the value of the relevant property within each iteration

Create the HTML element that will be repeatedly used with each data value. In this case the template should be 'value'

Append this generated code into the parent element that was stored in #2 above.

After the iteration is complete, inject (append) the parent element into the DOM at the appropriate place.

Case 1: Plain javascript -

Use XHR to read the JSON and get the data into a variable. Lets name it JSONData.

We will keep the reference of the parent element created in the HTML within javascript.

//hoping that you have only one element with this classname or the

//concerned element is the first element by this classname in this HTML code.

//Generally, as a good practice we should either use ID to identify an element individually within our javascript code,

//else use specific identifiers for the same.

var parentDropdownContainer = document.getElementsByClassName('dropdown-content')[0];

Iterating in the JSON data

for (var counter = 0, len = JSONData.length - 1; counter < len; counter ++){
  //we will add logic to generate HTML
}

You can use the other variants of the iteration - for in, while, Array.splice(), etc upto your understanding.

Within this iterator we need to create a HTML code and append it to the parent container

for (var counter = 0, len = JSONData.length - 1; counter < len; counter ++){
  var currentData = JSONData[counter]; //this holds the reference of the current data in this iteration
  var dropdownElement = document.createElement('a');
  dropdownElement.setAttribute('href','#'); //this adds the href attribute into the anchor element.
  //lets add another attribute to the anchor element to represent the dynamic id/value associated with this data
  dropdownElement.setAttribute('data-value',currentData.A);
  //lets add the value inside the anchor element
  dropdownElement.innerHTML = currentData.B;
  //lets append this element to the parent container
  parentDropdownContainer.appendChild(dropdownElement);
}

Now this should render the required dynamic options in the dropdown.


问:
Youtube channel feed
I need to get all statistics from a Youtube channel so that I can create a document using PHP containing all of the data.

I want information such as the dates the video was viewed, if it has been liked, if it has been blogged and so on.

Is it possible to do this?

Thanks

答:
Please see the sample code below for how you can do some of this. You can find a basic demo here. As seen, you do not necessarily need to write any PHP code to do this. More details are available in developer documents.</p>

```<code><html>
<head>
    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script>
    $(document).ready(function(){
        $("button").click(function(){
            $("body").append("<div id = 'data'><ul>jffnfjnkj</ul></div>");
            var dataContainer = $("#data ul");
            $.ajax({
                url:'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?alt=jsonc&v=2&callback=?',
                dataType: "jsonp",
                timeout: 5000,
                success: function(data){

                         $.each(data.data.items,
                                   function(i, val) {

                                     if (typeof(val.player) !== 'undefined' && typeof(val.title) !== 'undefined') {
                                        dataContainer.append('<li><a href='+val.player["default"]+' target="_blank">'+val.title+'</a></li>');
                                     }
                             });
                        }
                    });
                });
    });
    </script>
</head>
<body>
    <h2>Header</h2>
    <p>Paragraph</p>
    <p>Paragraph.</p>
    <button>Click me</button>
</body>
</html>
</code>```

Title: Youtube channel feed

Body:
Please see the sample code below for how you can do some of this. You can find a basic demo here. As seen, you do not necessarily need to write any PHP code to do this. More details are available in developer documents.

<html>
<head>
    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script>
    $(document).ready(function(){
        $("button").click(function(){
            $("body").append("<div id = 'data'><ul>jffnfjnkj</ul></div>");
            var dataContainer = $("#data ul");
            $.ajax({
                url:'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?alt=jsonc&v=2&callback=?',
                dataType: "jsonp",
                timeout: 5000,
                success: function(data){

                         $.each(data.data.items,
                                   function(i, val) {

                                     if (typeof(val.player) !== 'undefined' && typeof(val.title) !== 'undefined') {
                                        dataContainer.append('<li><a href='+val.player["default"]+' target="_blank">'+val.title+'</a></li>');
                                     }
                             });
                        }
                    });
                });
    });
    </script>
</head>
<body>
    <h2>Header</h2>
    <p>Paragraph</p>
    <p>Paragraph.</p>
    <button>Click me</button>
</body>
</html>


问:
Too many mq connections for a server connection channel which are not created by queue
As per our configuration, we have WAS version is 8.5.5.11, IBM MQ version 7.5.0.3. We are using 2 channels to connect to WMQ, one with MAXINST set to 250 and one with 500. SHARECNV is set to 10 for both. Now we have an upper limit of making maximum 2000 connections in a queue manager but we end up crossing that limit after 3-4 days of continuous running of WAS Server.
After doing some analysis we can see that at any point of time we have only 120-160 active connections. DIS CONN command gives shows a lot of connections with OBJNAME, OBJTYPE empty and ASTATE "NONE". Even these connections are made from our WAS Server IP but it seems they are not created by queues as OBJTYPE is not Queue for these connections. These connections keep on growing over a period of time and ultimately we reach our limit of 2000 connections.

Can somebody help in identifying why these connections are getting created and make sure they get closed like normal idle connections.
This is how connection are made and closed in the application: We have an abstrack bean class which is extended by all MDB's.

```<code>@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })
public class TrackBeanV2 extends AbstractServiceBean implements MessageListener {//code}
</code>```

The abstrack bean handles creation and closing of connections in following manner:

```<code>public abstract class AbstractServiceBean {
@Resource(name = "myQCF", type = QueueConnectionFactory.class, shareable =     true, description = "Reply Connection Factory")
private ConnectionFactory replyCF;

@PostConstruct
private void postConstruct() {
    replyConnection = replyCF.createConnection();

}  catch (JMSException e) {
    throw new RuntimeException("Failed to create JMS Connection");
}

}
@PreDestroy
private void preDestroy() {
try {
    replyConnection.close();
} catch (JMSException e) {
    throw new RuntimeException("Failed to close JMS connection", e);
}
}

private void sendResponseMessage(String outputMessageText, String  jmsMessageID , Destination replyDestination) {
TextMessage replyMessage = null;
try {
    createSession();
    createProducer();
    replyMessage = createReplyMessage(outputMessageText , jmsMessageID);
    sendReply(replyMessage, replyDestination);
    closeProducer();
    closeSession();
} catch (JMSException exp) {
    handleException(exp);
}
}
private void createSession() throws JMSException{
replySession = replyConnection.createSession(true, 0);
}`
private void createProducer() throws JMSException{
replyProducer = replySession.createProducer(null);
}

private void closeSession() throws JMSException {
if (replySession != null) {
    replySession.close();
}
}

private void closeProducer() throws JMSException{
if (replyProducer != null) {
    replyProducer.close();
}
}
private void sendReply(TextMessage replyMessage, Destination replyDestination) throws JMSException {
logMessages(replyMessage.getText(), "RESPONSE MESSAGE");
replyProducer.send(replyDestination, replyMessage);
}
</code>```

An output of below command

```<code>echo "DIS CONN(*) TYPE(*) CONNAME CHANNEL OBJNAME OBJTYPE" | mqsc -e -m QPDC1GC2 -p width=1000 | grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS="," 'function printValues() { if ("CHANNEL" in p) { print p["CHANNEL"], p["CURSHCNV"], p["CONNAME"],p["CHSTADA"],p["CHSTATI"],p["LSTMSGDA"],p["LSTMSGTI"],p["OBJNAME"],p["OBJTYPE"],p["ASTATE"],p["APPLDESC"],p["APPLTAG"] } } /^\w+:/ { printValues(); delete p; next } { p[$1] = $2 } END { printValues() }' | grep MYCHANNEL
</code>```

looks like this

```<code>A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,VALIDATE_GET_01,QUEUE,ACTIVE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,VALIDATE_GET_01,QUEUE,ACTIVE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,GETDETAILSGET_01,QUEUE,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
</code>```

This is Config in qm.ini.

```<code>Channels:
MaxChannels=2000
MaxActiveChannels=2000
</code>```

Output of the command provided in the comments:

```<code>   "841DD95801B5DC20","A.QMGR1.MYCHANNEL","10.217.278.15","GETDETAILSGET_01","QUEUE","ACTIVE","WebSphere MQ Channel","WebSphere MQ Client for Java","MQOO_INPUT_SHARED,MQOO_BROWSE,MQOO_INQUIRE,MQOO_SAVE_ALL_CONTEXT,MQOO_FAIL_IF_QUIESCING"
   "841DD958AB2CF820","A.QMGR1.MYCHANNEL","10.217.278.15","GETDETAILSGET_01","QUEUE","NONE","WebSphere MQ Channel","WebSphere MQ Client for Java","MQOO_INPUT_SHARED,MQOO_INQUIRE,MQOO_SAVE_ALL_CONTEXT,MQOO_FAIL_IF_QUIESCING,MQOO_NO_READ_AHEAD"
</code>```

答:
The symptoms point to your application connections not getting closed properly.  I have a IBM MQ administrator background not a Java development background, but based on what you have posted so far it appears to me that you are attempting to close the connections properly.  Hopefully someone with more IBM MQ classes for JMS development background can take a look.  @Roger?

The following script will display the number of channel instances for a specific channel name.  It will also show the total shared conversations across that channel's instances, the number of unique CONNs, and the total number of objects opened by the CONNs including CONNs with no objects open.  Note that when a IBM MQ client process connects to the queue manager a unique CONN to the queue manager will be created, if the process opens a object such as the queue manager, a queue, or a topic, DIS CONN will display those open objects as well.

This may help to observer the increase in these numbers over time to help you understand the connection/channel leak you are experiencing.

Example output:

```<code>./mq-info.ksh MQ.CHANNEL.NAME QMGR.NAME
Total Number of channel instances: 53
Total shared conversations: 94
Unique CONNs: 94
Objects opened by CONNs:
     15 ""
     45 "QMGR"
    120 "QUEUE"
</code>```

Note that if the channel is configured with SHARECNV of at least 1, the value of Total shared conversations and Unique CONNs should always match.

In the example output 15 of the shared conversations have no objects open.  The remaining 70 shared conversations have the queue manager itself open 45 times and queue objects open 120 times.

mq-info.ksh is below:

```<code>#!/bin/ksh

CHL=${1}
QMGR=${2}
echo "Total Number of channel instances: $(echo "DIS CHS(${CHL}) ALL"|runmqsc $QMGR| grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS="," 'function printValues() { if ("CHANNEL" in p) { print p["CHANNEL"], p["CURSHCNV"], p["CONNAME"] } } /^\w+:/ { printValues(); delete p; next } { p[$1] = $2 } END { printValues() }'|wc -l)"
echo "Total shared conversations: $(expr $(echo $(echo "DIS CHS(${CHL}) ALL"|runmqsc $QMGR| grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS="," 'function printValues() { if ("CHANNEL" in p) { print p["CHANNEL"], p["CURSHCNV"], p["CONNAME"] } } /^\w+:/ { printValues(); delete p; next } { p[$1] = $2 } END { printValues() }'|awk -F, '{print $2}')|sed -e 's/ / + /g'))"
echo "Unique CONNs: $(echo "dis conn(*) type(all) where(channel eq ${CHL})"|runmqsc $QMGR|grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS='","' 'function printValues() { if ("CONN" in p) { print p["CONN"], p["CHANNEL"], p["CONNAME"], p["OBJNAME"], p["OBJTYPE"], p["ASTATE"], p["APPLDESC"], p["APPLTAG"], p["OPENOPTS"] } } /^\w+:/ { if (x !~ /YES/) {printValues()}; x = "NO"; delete p; next } { p[$1] = $2 } { if ("OPENOPTS" in p) { printValues() ; delete p["OPENOPTS"]; x = "YES"} } END { if (x !~ /YES/) {printValues()} }'|sed -e 's/^/"/g' -e 's/$/"/g'|awk -F, '{print $1}'|sort -u|wc -l)"
echo "Objects opened by CONNs:"
echo "dis conn(*) type(all) where(channel eq ${CHL})"|runmqsc $QMGR|grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS='","' 'function printValues() { if ("CONN" in p) { print p["CONN"], p["CHANNEL"], p["CONNAME"], p["OBJNAME"], p["OBJTYPE"], p["ASTATE"], p["APPLDESC"], p["APPLTAG"], p["OPENOPTS"] } } /^\w+:/ { if (x !~ /YES/) {printValues()}; x = "NO"; delete p; next } { p[$1] = $2 } { if ("OPENOPTS" in p) { printValues() ; delete p["OPENOPTS"]; x = "YES"} } END { if (x !~ /YES/) {printValues()} }'|sed -e 's/^/"/g' -e 's/$/"/g'|awk -F, '{print $5}'|sort|uniq -c
</code>```

Body:
As per our configuration, we have WAS version is 8.5.5.11, IBM MQ version 7.5.0.3. We are using 2 channels to connect to WMQ, one with MAXINST set to 250 and one with 500. SHARECNV is set to 10 for both. Now we have an upper limit of making maximum 2000 connections in a queue manager but we end up crossing that limit after 3-4 days of continuous running of WAS Server.
After doing some analysis we can see that at any point of time we have only 120-160 active connections. DIS CONN command gives shows a lot of connections with OBJNAME, OBJTYPE empty and ASTATE "NONE". Even these connections are made from our WAS Server IP but it seems they are not created by queues as OBJTYPE is not Queue for these connections. These connections keep on growing over a period of time and ultimately we reach our limit of 2000 connections.

Can somebody help in identifying why these connections are getting created and make sure they get closed like normal idle connections.
This is how connection are made and closed in the application: We have an abstrack bean class which is extended by all MDB's.

@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })
public class TrackBeanV2 extends AbstractServiceBean implements MessageListener {//code}

The abstrack bean handles creation and closing of connections in following manner:

public abstract class AbstractServiceBean {
@Resource(name = "myQCF", type = QueueConnectionFactory.class, shareable =     true, description = "Reply Connection Factory")
private ConnectionFactory replyCF;

@PostConstruct
private void postConstruct() {
    replyConnection = replyCF.createConnection();

}  catch (JMSException e) {
    throw new RuntimeException("Failed to create JMS Connection");
}

}
@PreDestroy
private void preDestroy() {
try {
    replyConnection.close();
} catch (JMSException e) {
    throw new RuntimeException("Failed to close JMS connection", e);
}
}

private void sendResponseMessage(String outputMessageText, String  jmsMessageID , Destination replyDestination) {
TextMessage replyMessage = null;
try {
    createSession();
    createProducer();
    replyMessage = createReplyMessage(outputMessageText , jmsMessageID);
    sendReply(replyMessage, replyDestination);
    closeProducer();
    closeSession();
} catch (JMSException exp) {
    handleException(exp);
}
}
private void createSession() throws JMSException{
replySession = replyConnection.createSession(true, 0);
}`
private void createProducer() throws JMSException{
replyProducer = replySession.createProducer(null);
}

private void closeSession() throws JMSException {
if (replySession != null) {
    replySession.close();
}
}

private void closeProducer() throws JMSException{
if (replyProducer != null) {
    replyProducer.close();
}
}
private void sendReply(TextMessage replyMessage, Destination replyDestination) throws JMSException {
logMessages(replyMessage.getText(), "RESPONSE MESSAGE");
replyProducer.send(replyDestination, replyMessage);
}

An output of below command

echo "DIS CONN(*) TYPE(*) CONNAME CHANNEL OBJNAME OBJTYPE" | mqsc -e -m QPDC1GC2 -p width=1000 | grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS="," 'function printValues() { if ("CHANNEL" in p) { print p["CHANNEL"], p["CURSHCNV"], p["CONNAME"],p["CHSTADA"],p["CHSTATI"],p["LSTMSGDA"],p["LSTMSGTI"],p["OBJNAME"],p["OBJTYPE"],p["ASTATE"],p["APPLDESC"],p["APPLTAG"] } } /^\w+:/ { printValues(); delete p; next } { p[$1] = $2 } END { printValues() }' | grep MYCHANNEL

looks like this

A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,VALIDATE_GET_01,QUEUE,ACTIVE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,,,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,VALIDATE_GET_01,QUEUE,ACTIVE,WebSphere MQ Channel,WebSphere MQ Client for Java
A.QMGR1.MYCHANNEL,,10.217.278.15,,,,,GETDETAILSGET_01,QUEUE,NONE,WebSphere MQ Channel,WebSphere MQ Client for Java

This is Config in qm.ini.

Channels:
MaxChannels=2000
MaxActiveChannels=2000

Output of the command provided in the comments:

   "841DD95801B5DC20","A.QMGR1.MYCHANNEL","10.217.278.15","GETDETAILSGET_01","QUEUE","ACTIVE","WebSphere MQ Channel","WebSphere MQ Client for Java","MQOO_INPUT_SHARED,MQOO_BROWSE,MQOO_INQUIRE,MQOO_SAVE_ALL_CONTEXT,MQOO_FAIL_IF_QUIESCING"
   "841DD958AB2CF820","A.QMGR1.MYCHANNEL","10.217.278.15","GETDETAILSGET_01","QUEUE","NONE","WebSphere MQ Channel","WebSphere MQ Client for Java","MQOO_INPUT_SHARED,MQOO_INQUIRE,MQOO_SAVE_ALL_CONTEXT,MQOO_FAIL_IF_QUIESCING,MQOO_NO_READ_AHEAD"

Body:
The symptoms point to your application connections not getting closed properly.  I have a IBM MQ administrator background not a Java development background, but based on what you have posted so far it appears to me that you are attempting to close the connections properly.  Hopefully someone with more IBM MQ classes for JMS development background can take a look.  @Roger?

The following script will display the number of channel instances for a specific channel name.  It will also show the total shared conversations across that channel's instances, the number of unique CONNs, and the total number of objects opened by the CONNs including CONNs with no objects open.  Note that when a IBM MQ client process connects to the queue manager a unique CONN to the queue manager will be created, if the process opens a object such as the queue manager, a queue, or a topic, DIS CONN will display those open objects as well.

This may help to observer the increase in these numbers over time to help you understand the connection/channel leak you are experiencing.

Example output:

./mq-info.ksh MQ.CHANNEL.NAME QMGR.NAME
Total Number of channel instances: 53
Total shared conversations: 94
Unique CONNs: 94
Objects opened by CONNs:
     15 ""
     45 "QMGR"
    120 "QUEUE"

Note that if the channel is configured with SHARECNV of at least 1, the value of Total shared conversations and Unique CONNs should always match.

In the example output 15 of the shared conversations have no objects open.  The remaining 70 shared conversations have the queue manager itself open 45 times and queue objects open 120 times.

mq-info.ksh is below:

#!/bin/ksh

CHL=${1}
QMGR=${2}
echo "Total Number of channel instances: $(echo "DIS CHS(${CHL}) ALL"|runmqsc $QMGR| grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS="," 'function printValues() { if ("CHANNEL" in p) { print p["CHANNEL"], p["CURSHCNV"], p["CONNAME"] } } /^\w+:/ { printValues(); delete p; next } { p[$1] = $2 } END { printValues() }'|wc -l)"
echo "Total shared conversations: $(expr $(echo $(echo "DIS CHS(${CHL}) ALL"|runmqsc $QMGR| grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS="," 'function printValues() { if ("CHANNEL" in p) { print p["CHANNEL"], p["CURSHCNV"], p["CONNAME"] } } /^\w+:/ { printValues(); delete p; next } { p[$1] = $2 } END { printValues() }'|awk -F, '{print $2}')|sed -e 's/ / + /g'))"
echo "Unique CONNs: $(echo "dis conn(*) type(all) where(channel eq ${CHL})"|runmqsc $QMGR|grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS='","' 'function printValues() { if ("CONN" in p) { print p["CONN"], p["CHANNEL"], p["CONNAME"], p["OBJNAME"], p["OBJTYPE"], p["ASTATE"], p["APPLDESC"], p["APPLTAG"], p["OPENOPTS"] } } /^\w+:/ { if (x !~ /YES/) {printValues()}; x = "NO"; delete p; next } { p[$1] = $2 } { if ("OPENOPTS" in p) { printValues() ; delete p["OPENOPTS"]; x = "YES"} } END { if (x !~ /YES/) {printValues()} }'|sed -e 's/^/"/g' -e 's/$/"/g'|awk -F, '{print $1}'|sort -u|wc -l)"
echo "Objects opened by CONNs:"
echo "dis conn(*) type(all) where(channel eq ${CHL})"|runmqsc $QMGR|grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS='","' 'function printValues() { if ("CONN" in p) { print p["CONN"], p["CHANNEL"], p["CONNAME"], p["OBJNAME"], p["OBJTYPE"], p["ASTATE"], p["APPLDESC"], p["APPLTAG"], p["OPENOPTS"] } } /^\w+:/ { if (x !~ /YES/) {printValues()}; x = "NO"; delete p; next } { p[$1] = $2 } { if ("OPENOPTS" in p) { printValues() ; delete p["OPENOPTS"]; x = "YES"} } END { if (x !~ /YES/) {printValues()} }'|sed -e 's/^/"/g' -e 's/$/"/g'|awk -F, '{print $5}'|sort|uniq -c


答: it seems that you did not setup the spinner in the change method so you need to initialize it first

Title: Changing text colour of a text view using a spinner


问:
Dilate works fine and erode does not output correctly image
I have this code.

```<code>#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <opencv/cv.h>
#include <iostream>
#include <Windows.h>

using namespace std;
using namespace cv;

int main(int, char**)

{
Mat image = imread("text.tif", 0);
Mat dilate_im = image.clone();
Mat erode_im = image.clone();

if (image.empty())//check if empty
{
    printf("Image is not read! File is probably missing! Press any key to        exim program");//message for error
    waitKey(); //10 second delay for showing message to user
}
else
{

    namedWindow("Original", 1);
    imshow("Original", image);

    dilate(image, dilate_im, Mat());
    erode(image, erode_im, Mat());

    namedWindow("Dilate Image", 1);
    imshow("Dilate Image", dilate_im);

    namedWindow("Erode Image", 1);
    imshow("Erode Image", erode_im);

    waitKey();
}
return 0;
}
</code>```

While the dilate function works and outputs the correctly image, erode does not work and I get only one black image.

This is the output:

View the output of this program here

Can you please help me and explain why the erode function does not work?

Thank you very much in advance.

答:
You are calling both erode and dilate methods as:

```<code>dilate(image, dilate_im, Mat());
erode(image, erode_im, Mat());
</code>```

As per the documentation:

src – input image; the number of channels can be arbitrary, but the depth should be one of CV_8U, CV_16U, CV_16S, CV_32F` or ``CV_64F.

dst – output image of the same size and type as src.

element – structuring element used for erosion; if element=Mat() , a 3 x 3 rectangular structuring element is used.

So unknowingly you are calling both erode and dilate with a default 3x3 kernel, But in case of erosion, the width of foreground Text seems to be less than 3 pixels, which would over-ridden by black color and hence the black output.

Body:
I have this code.

#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <opencv/cv.h>
#include <iostream>
#include <Windows.h>

using namespace std;
using namespace cv;

int main(int, char**)

{
Mat image = imread("text.tif", 0);
Mat dilate_im = image.clone();
Mat erode_im = image.clone();

if (image.empty())//check if empty
{
    printf("Image is not read! File is probably missing! Press any key to        exim program");//message for error
    waitKey(); //10 second delay for showing message to user
}
else
{

    namedWindow("Original", 1);
    imshow("Original", image);

    dilate(image, dilate_im, Mat());
    erode(image, erode_im, Mat());

    namedWindow("Dilate Image", 1);
    imshow("Dilate Image", dilate_im);

    namedWindow("Erode Image", 1);
    imshow("Erode Image", erode_im);

    waitKey();
}
return 0;
}

While the dilate function works and outputs the correctly image, erode does not work and I get only one black image.

This is the output:

View the output of this program here

Can you please help me and explain why the erode function does not work?

Thank you very much in advance.

Body:
You are calling both erode and dilate methods as:

dilate(image, dilate_im, Mat());
erode(image, erode_im, Mat());

As per the documentation:

src – input image; the number of channels can be arbitrary, but the depth should be one of CV_8U, CV_16U, CV_16S, CV_32F` or ``CV_64F.

dst – output image of the same size and type as src.

element – structuring element used for erosion; if element=Mat() , a 3 x 3 rectangular structuring element is used.

So unknowingly you are calling both erode and dilate with a default 3x3 kernel, But in case of erosion, the width of foreground Text seems to be less than 3 pixels, which would over-ridden by black color and hence the black output.