问:
Convert xml ntext in mssql to csv (ucomponents migration)
I have lots of rows in an mssql table which are in xml format and I want to convert them to csv. The column is an ntext and the values are like.

```<code><MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>
</code>```

and I would like to convert them in 5713,6817,5424,1888,6128,6339
Any ideas how to achieve this with sql command?

** Probably this seems to be the way to go https://social.msdn.microsoft.com/Forums/sqlserver/en-US/780e80b2-f898-4451-b19f-332289fb1c8d/sql-xml-get-xml-values-into-csv?forum=sqlxml , save it in a function and then loop through all the rows and update the values. At the moment it is failing at x.y.value.

I tried also to use replace but it failed because it is xml and it doesnt get the space between the xml nodes.

I also used

```<code>set dataNvarchar = substring(CAST(dataNtext as nvarchar(500)), patindex('%[0-9]%', CAST(dataNtext as nvarchar(500))), 1+patindex('%[0-9][^0-9]%', CAST(dataNtext as nvarchar(500))+'x')-patindex('%[0-9]%', CAST(dataNtext as nvarchar(500))))
</code>```

but it gets only the first numeric.

******* Additional Solution *********
These values come from uComponent plugin for Umbraco. I couldn't find a way to read it as xml - even though the solution to this as proper xml is correct.
Instead I wrote this function which solved my problem

```<code>Create Function [dbo].[ParseXml](@text ntext)
returns nvarchar(500) as
Begin
declare @strnvar nvarchar(MAX) -- main string to subtruct
declare @numberstr nvarchar(500) -- extracted number
declare @csvstr nvarchar(500) -- constructed csv string
-- Convert text to nvarchar
set @strnvar = CAST(@text as nvarchar(MAX))
set @csvstr = ''
set @numberstr = substring(@strnvar, patindex('%[0-9]%', @strnvar), 1 + patindex('%[0-9][^0-9]%', @strnvar+'x') - patindex('%[0-9]%', @strnvar))

while(DATALENGTH(@numberstr) > 0)
BEGIN
set @csvstr = @csvstr + @numberstr + ','
set @strnvar = REPLACE(@strnvar, @numberstr, '')
set @numberstr = substring(@strnvar, patindex('%[0-9]%', @strnvar), 1 + patindex('%[0-9][^0-9]%', @strnvar+'x') - patindex('%[0-9]%', @strnvar))
END

IF RIGHT(@csvstr,1) = ','
    set @csvstr =  LEFT(@csvstr, LEN(@csvstr) - 1)
return @csvstr
end
GO
</code>```

答:
```<code>declare @text varchar(max) = '<MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>'

declare @xml xml = @text;

select
t.c.query('.').value('.', 'int') as NodeId
from @xml.nodes('/MultiNodePicker/nodeId') t(c)
</code>```

Body:
I have lots of rows in an mssql table which are in xml format and I want to convert them to csv. The column is an ntext and the values are like.

<MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>

and I would like to convert them in 5713,6817,5424,1888,6128,6339
Any ideas how to achieve this with sql command?

** Probably this seems to be the way to go https://social.msdn.microsoft.com/Forums/sqlserver/en-US/780e80b2-f898-4451-b19f-332289fb1c8d/sql-xml-get-xml-values-into-csv?forum=sqlxml , save it in a function and then loop through all the rows and update the values. At the moment it is failing at x.y.value.

I tried also to use replace but it failed because it is xml and it doesnt get the space between the xml nodes.

I also used

set dataNvarchar = substring(CAST(dataNtext as nvarchar(500)), patindex('%[0-9]%', CAST(dataNtext as nvarchar(500))), 1+patindex('%[0-9][^0-9]%', CAST(dataNtext as nvarchar(500))+'x')-patindex('%[0-9]%', CAST(dataNtext as nvarchar(500))))

but it gets only the first numeric.

******* Additional Solution *********
These values come from uComponent plugin for Umbraco. I couldn't find a way to read it as xml - even though the solution to this as proper xml is correct.
Instead I wrote this function which solved my problem

Create Function [dbo].[ParseXml](@text ntext)
returns nvarchar(500) as
Begin
declare @strnvar nvarchar(MAX) -- main string to subtruct
declare @numberstr nvarchar(500) -- extracted number
declare @csvstr nvarchar(500) -- constructed csv string
-- Convert text to nvarchar
set @strnvar = CAST(@text as nvarchar(MAX))
set @csvstr = ''
set @numberstr = substring(@strnvar, patindex('%[0-9]%', @strnvar), 1 + patindex('%[0-9][^0-9]%', @strnvar+'x') - patindex('%[0-9]%', @strnvar))

while(DATALENGTH(@numberstr) > 0)
BEGIN
set @csvstr = @csvstr + @numberstr + ','
set @strnvar = REPLACE(@strnvar, @numberstr, '')
set @numberstr = substring(@strnvar, patindex('%[0-9]%', @strnvar), 1 + patindex('%[0-9][^0-9]%', @strnvar+'x') - patindex('%[0-9]%', @strnvar))
END

IF RIGHT(@csvstr,1) = ','
    set @csvstr =  LEFT(@csvstr, LEN(@csvstr) - 1)
return @csvstr
end
GO


来源: stackexchange

问:
Yii2 Ajax returns whole page content
I am trying to make simple ajax :

```<code>$('.send-contact-button').on('click', function(e){
        e.preventDefault();

       var id = $('.send-contact-button').data('id');
       var flag = $('.send-contact-button').data('flag');

       $.ajax({
           method : 'GET',
           url : "contactHandler?id="+id+"&flag="+flag,
           success : function( data ){
                console.log( data );
           }
       });

    });
</code>```

but every time i get the html content. Tryied to send the data through json but without result. This Ajax is just test.
Controller:

```<code>public function contactHandler($id, $flag)
{
    echo $id;
}
</code>```

Can you guys tell me where i am wrong ? Thank you very much!

答:
Your action is not defined correctly, you are probably getting an error page.

try this:

```<code>public function actionContactHandler($id, $flag)
{
    echo $id;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Yii2 Ajax returns whole page content

Body:
I am trying to make simple ajax :

$('.send-contact-button').on('click', function(e){
        e.preventDefault();

       var id = $('.send-contact-button').data('id');
       var flag = $('.send-contact-button').data('flag');

       $.ajax({
           method : 'GET',
           url : "contactHandler?id="+id+"&flag="+flag,
           success : function( data ){
                console.log( data );
           }
       });

    });

but every time i get the html content. Tryied to send the data through json but without result. This Ajax is just test.
Controller:

public function contactHandler($id, $flag)
{
    echo $id;
}

Can you guys tell me where i am wrong ? Thank you very much!

Body:
Your action is not defined correctly, you are probably getting an error page.

try this:

public function actionContactHandler($id, $flag)
{
    echo $id;
}


问:
How to retrieve the list of all GitHub repositories of a person?
We need to display all the projects of a person in his repository on GitHub account.

How can I display the names of all the git repositories of a particular person using his git-user name?

答:
You probably need a jsonp solution:

https://api.github.com/users/[user name]/repos?callback=abc

If you use jQuery:

$.ajax({
  url: "https://api.github.com/users/blackmiaool/repos",
  jsonp: true,
  method: "GET",
  dataType: "json",
  success: function(res) {
    console.log(res)
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Body:
You probably need a jsonp solution:

https://api.github.com/users/[user name]/repos?callback=abc

If you use jQuery:

$.ajax({
  url: "https://api.github.com/users/blackmiaool/repos",
  jsonp: true,
  method: "GET",
  dataType: "json",
  success: function(res) {
    console.log(res)
  }
});

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


问:
Why can I not override and annotate a getter method for entity mapping?
Given this class:

```<code>@MappedSuperclass
public abstract class AbstractEntity {

    int id;
    public void setId(int id) { this.id = id; }
    public int getId() { return id; }

    // other mappings
}
</code>```

I want to define an entity:

```<code>@Entity
public class SomeEntity extends AbstractEntity {

    @Override
    @Id // or @OneToOne etc.
    public int getId() { return id; }
}
</code>```

But this fails with a "No identifier specified"
(or a "Could not determine type for") error on SomeEntity. If I remove the getter from the superclass it works. Can't I do this override strategy? Why not, or if yes - how?

Adding

```<code>@AttributeOverride(name = "id", column = @Column(name = "ID"))
</code>```

to the subclass does not change the error.

答:
For you to create an entity class there are requirements that the class must meet.  Ex. must have a public/private constructor.

Here is the list of requirements:

http://docs.oracle.com/javaee/5/tutorial/doc/bnbqa.html

Hope this helps.

Body:
Given this class:

@MappedSuperclass
public abstract class AbstractEntity {

    int id;
    public void setId(int id) { this.id = id; }
    public int getId() { return id; }

    // other mappings
}

I want to define an entity:

@Entity
public class SomeEntity extends AbstractEntity {

    @Override
    @Id // or @OneToOne etc.
    public int getId() { return id; }
}

But this fails with a "No identifier specified"
(or a "Could not determine type for") error on SomeEntity. If I remove the getter from the superclass it works. Can't I do this override strategy? Why not, or if yes - how?

Adding

@AttributeOverride(name = "id", column = @Column(name = "ID"))

to the subclass does not change the error.


问:
Angular 2 Empty Component Routing
I am new to Angular 2 and I have a question regarding routing. I have a app.routing file, in which I only want one path.

```<code>{path: 'signup', component: SignupComponent}
</code>```

But if I run this code I get an error:

```<code>Error: Uncaught (in promise): Error: Cannot match any routes: ''
</code>```

So i decided to just use an empty component on the ' ' path, which works exactly like i wanted.

Routing File:

```<code>import {Routes, RouterModule} from '@angular/router';
import {SignupComponent} from "./signup/signup.component";
import {EmptyComponent} from "./empty/empty.component";

const appRoutes:Routes = [
    {path: '', component: EmptyComponent},
    {path: 'signup', component: SignupComponent}
];

export const appRoutingProviders = [];

export const routing = RouterModule.forRoot(appRoutes);
</code>```

The file with the router-outlet:

```<code><header>
    <div class="btn-wrapper">
        <button class="btn-sign-up btn-fancy" routerLink="/signup">Sign Up</button>
        <button class="btn-sign-in btn-ghost btn-fancy">Sign In</button>
    </div>
    <i class="material-icons more">keyboard_arrow_down</i>
    <router-outlet></router-outlet>
    <div class="overlay" *ngIf="overlay" (click)="close()"></div>
    <div class="tinted"></div>
</header>
</code>```

I just want that the router only routes the SignupComponent on the 'signup' path. Is there another way to do this and eliminate the use of an empty component? I am sorry if this question is poorly written, I am very new to StackOverflow.

答:
```<code>import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { DemoComponent } from './demo.component';

const demoRoutes: Routes = [
    { path: '', component: DemoComponent }
];

export const demoRouting: ModuleWithProviders = RouterModule.forChild( demoRoutes );
</code>```

Title: Angular 2 Empty Component Routing

Body:
I am new to Angular 2 and I have a question regarding routing. I have a app.routing file, in which I only want one path.

{path: 'signup', component: SignupComponent}

But if I run this code I get an error:

Error: Uncaught (in promise): Error: Cannot match any routes: ''

So i decided to just use an empty component on the ' ' path, which works exactly like i wanted.

Routing File:

import {Routes, RouterModule} from '@angular/router';
import {SignupComponent} from "./signup/signup.component";
import {EmptyComponent} from "./empty/empty.component";

const appRoutes:Routes = [
    {path: '', component: EmptyComponent},
    {path: 'signup', component: SignupComponent}
];

export const appRoutingProviders = [];

export const routing = RouterModule.forRoot(appRoutes);

The file with the router-outlet:

        <button class="btn-sign-up btn-fancy" routerLink="/signup">Sign Up</button>
        <button class="btn-sign-in btn-ghost btn-fancy">Sign In</button>

    keyboard_arrow_down
    <router-outlet></router-outlet>

I just want that the router only routes the SignupComponent on the 'signup' path. Is there another way to do this and eliminate the use of an empty component? I am sorry if this question is poorly written, I am very new to StackOverflow.


问:
wpf class library with resource dictionary
Is it possible to have a resource dictionary in a WPF class library assembly (.dll)? I ask this because I have an "Application WPF" assembly (.exe), if I try to turn the type of the assembly to "WPF Class Library" I get the error:

Impossible to specify the element ApplicationDefinition in the project file of the Library

How can I make it work?

答: This will be the build action of one of your XAML files.  I would use a WPF User Control Library or WPF Custom Control Library instead of a general class library.</p>

ContentLicense: CC BY-SA 2.5


问:
How to get all links on a page that start with a https in link - PHP
I'm trying to get all the links on a page. So for example if a user types in https://laravel.com/ in the input field they will see all the links on that page.

I already got the concept working. Here is part of the code I have:

```<code>$website = request('website_url');

$pureURL = 'http://www.'.$website.'/';
$doc = new \DOMDocument;
@$doc->loadHTMLFile($pureURL);

foreach ($doc->getElementsByTagName('a') as $link){
    $linkDetail[] = array('url' => $link->getAttribute('href'));
}

$pageLinks = $linkDetail;

return view('api.index', compact('result'));
</code>```

My frontend code:

```<code>@foreach($pageLinks as $key => $link)
        {{ $link['url'] }}<br />
@endforeach
</code>```

This is what I get:

The problem is, I just want to get all the links that start with https. I want to avoid the links that have a /doc in them and so on.
How would I go about doing that. Im not really good with regex, but I know there is a way you can use that.

答:
```<code>^https.*[^doc|avoid_end]$
</code>```

something like that https://regex101.com/r/I4ebAR/1 ?

```<code>foreach ($doc->getElementsByTagName('a') as $link){
    $linkTmp = $link->getAttribute('href');
    if (preg_match('/^https.*[^doc|avoid_end]$/')) {
        $linkDetail[] = ['url' => $linkTmp];
    }
}
</code>```

Body:
I'm trying to get all the links on a page. So for example if a user types in https://laravel.com/ in the input field they will see all the links on that page.

I already got the concept working. Here is part of the code I have:

$website = request('website_url');

$pureURL = 'http://www.'.$website.'/';
$doc = new \DOMDocument;
@$doc->loadHTMLFile($pureURL);

foreach ($doc->getElementsByTagName('a') as $link){
    $linkDetail[] = array('url' => $link->getAttribute('href'));
}

$pageLinks = $linkDetail;

return view('api.index', compact('result'));

My frontend code:

@foreach($pageLinks as $key => $link)
        {{ $link['url'] }}

@endforeach

This is what I get:

The problem is, I just want to get all the links that start with https. I want to avoid the links that have a /doc in them and so on.
How would I go about doing that. Im not really good with regex, but I know there is a way you can use that.

Body:
^https.*[^doc|avoid_end]$

something like that https://regex101.com/r/I4ebAR/1 ?

foreach ($doc->getElementsByTagName('a') as $link){
    $linkTmp = $link->getAttribute('href');
    if (preg_match('/^https.*[^doc|avoid_end]$/')) {
        $linkDetail[] = ['url' => $linkTmp];
    }
}


问:
When calling Delegate Lib API got error InValidFunctionPointerInDelegate was detected
```<code>Dim fl_prevproc As SubClassProcDelegate
</code>```

I have created function as below:

```<code>Public Function SetupClassNotification() As Boolean
   Dim subclassform As System.Windows.Forms.Form
   Dim i As Integer
      For i = 0 To FORMLIST_END
        If Formlist(i).fl_threadid = 0 Then
        subclassform = New frmSubclassingForm
        subclassform.Hide()
        Formlist(i).fl_prevproc = SetWindowLong(subclassform.Handle.ToInt32, GWL_WNDPROC, AddressOf WindowProc)
        Exit Function
        End If
      Next i
End Function
</code>```

Implementation of WindowProc Function with exactly same argument as Delegate Function

```<code>Private Function WindowProc(ByVal hw As Integer, ByVal uMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

    Dim i As Integer

    If uMsg = VB_WM_USER_PLUS_1 Then

        CheckForResponses()
    Else
        For i = 0 To FORMLIST_END
            If hw = Formlist(i).fl_gHW Then
                WindowProc = CallWindowProc(Formlist(i).fl_prevproc, hw, uMsg, wParam, lParam)
            End If
        Next i
    End If
End Function
</code>```

Declaration for Lib API is as follows:

```<code>Delegate Function SubClassProcDelegate(ByVal hw As Integer, ByVal uMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

Declare Function CallWindowProc Lib "user32.dll" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As SubClassProcDelegate, ByVal hwnd As Integer, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

Declare Function SetWindowLong Lib "user32.dll" Alias "SetWindowLongA" (ByVal hwnd As Integer, ByVal attr As Integer, ByVal lVal As SubClassProcDelegate) As SubClassProcDelegate
</code>```

Execution stops at a line:

```<code>Formlist(i).fl_prevproc = SetWindowLong(subclassform.Handle.ToInt32, GWL_WNDPROC, AddressOf WindowProc)
</code>```

The error message I'm getting is

Invalid function pointer 0xffff0a95 was passed into the runtime to be
  converted to a delegate. Passing in invalid function pointers to be
  converted to delegates can cause crashes, corruption or data loss.

Any help will be appreciated. Thank you.

答:
Declaring the window handle as Integer is asking for problems especially if you are using a 64 bit OS; use IntPtr or SafeHandle.  wParam, and lParam should also be IntPtr.

That said, why not use the .Net NativeWindow Class to hook into the window procedure?

Edit:

Here is a working example using the Win32 API.  I still recommend that you implement a solution based on the NativeWindow class.

```<code>Imports System.Runtime.InteropServices

Public Class Form1
    Private prevWndProc As IntPtr
    Public Delegate Function WndProcDelegate(ByVal hWnd As IntPtr, ByVal msg As UInt32, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr

    <System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SetWindowLong")> _
    Private Shared Function SetWindowLong32(ByVal hWnd As IntPtr, nIndex As Int32, ByVal dwNewLong As IntPtr) As IntPtr
    End Function

    <System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SetWindowLongPtr")> _
    Private Shared Function SetWindowLongPtr64(ByVal hWnd As IntPtr, nIndex As Int32, ByVal dwNewLong As IntPtr) As IntPtr
    End Function

    Private Shared Function SetWindowProc(hwnd As IntPtr, wndProcDelegate As WndProcDelegate) As IntPtr
        Const GWL_WNDPROC As Int32 = -4

        Dim ptr As IntPtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate)
        If IntPtr.Size = 8 Then
            Return SetWindowLongPtr64(hwnd, GWL_WNDPROC, ptr)
        Else
            Return SetWindowLong32(hwnd, GWL_WNDPROC, ptr)
        End If
    End Function

    <DllImport("user32.dll")> _
    Private Shared Function CallWindowProc(lpPrevWndFunc As IntPtr, hWnd As IntPtr, Msg As UInt32, wParam As IntPtr, lParam As IntPtr) As IntPtr
    End Function

    Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)
        prevWndProc = SetWindowProc(Me.Handle, AddressOf MyWindowProcedure)
    End Sub

    Private Function MyWindowProcedure(ByVal hWnd As IntPtr, ByVal msg As UInt32, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
        Debug.Print(msg.ToString)
        Return CallWindowProc(prevWndProc, hWnd, msg, wParam, lParam)
    End Function
End Class
</code>```

Body:
Dim fl_prevproc As SubClassProcDelegate

I have created function as below:

Public Function SetupClassNotification() As Boolean
   Dim subclassform As System.Windows.Forms.Form
   Dim i As Integer
      For i = 0 To FORMLIST_END
        If Formlist(i).fl_threadid = 0 Then
        subclassform = New frmSubclassingForm
        subclassform.Hide()
        Formlist(i).fl_prevproc = SetWindowLong(subclassform.Handle.ToInt32, GWL_WNDPROC, AddressOf WindowProc)
        Exit Function
        End If
      Next i
End Function

Implementation of WindowProc Function with exactly same argument as Delegate Function

Private Function WindowProc(ByVal hw As Integer, ByVal uMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

    Dim i As Integer

    If uMsg = VB_WM_USER_PLUS_1 Then

        CheckForResponses()
    Else
        For i = 0 To FORMLIST_END
            If hw = Formlist(i).fl_gHW Then
                WindowProc = CallWindowProc(Formlist(i).fl_prevproc, hw, uMsg, wParam, lParam)
            End If
        Next i
    End If
End Function

Declaration for Lib API is as follows:

Delegate Function SubClassProcDelegate(ByVal hw As Integer, ByVal uMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

Declare Function CallWindowProc Lib "user32.dll" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As SubClassProcDelegate, ByVal hwnd As Integer, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

Declare Function SetWindowLong Lib "user32.dll" Alias "SetWindowLongA" (ByVal hwnd As Integer, ByVal attr As Integer, ByVal lVal As SubClassProcDelegate) As SubClassProcDelegate

Execution stops at a line:

Formlist(i).fl_prevproc = SetWindowLong(subclassform.Handle.ToInt32, GWL_WNDPROC, AddressOf WindowProc)

The error message I'm getting is

Invalid function pointer 0xffff0a95 was passed into the runtime to be
  converted to a delegate. Passing in invalid function pointers to be
  converted to delegates can cause crashes, corruption or data loss.

Any help will be appreciated. Thank you.

Body:
Declaring the window handle as Integer is asking for problems especially if you are using a 64 bit OS; use IntPtr or SafeHandle.  wParam, and lParam should also be IntPtr.

That said, why not use the .Net NativeWindow Class to hook into the window procedure?

Edit:

Here is a working example using the Win32 API.  I still recommend that you implement a solution based on the NativeWindow class.

Imports System.Runtime.InteropServices

Public Class Form1
    Private prevWndProc As IntPtr
    Public Delegate Function WndProcDelegate(ByVal hWnd As IntPtr, ByVal msg As UInt32, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr

    <System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SetWindowLong")> _
    Private Shared Function SetWindowLong32(ByVal hWnd As IntPtr, nIndex As Int32, ByVal dwNewLong As IntPtr) As IntPtr
    End Function

    <System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SetWindowLongPtr")> _
    Private Shared Function SetWindowLongPtr64(ByVal hWnd As IntPtr, nIndex As Int32, ByVal dwNewLong As IntPtr) As IntPtr
    End Function

    Private Shared Function SetWindowProc(hwnd As IntPtr, wndProcDelegate As WndProcDelegate) As IntPtr
        Const GWL_WNDPROC As Int32 = -4

        Dim ptr As IntPtr = Marshal.GetFunctionPointerForDelegate(wndProcDelegate)
        If IntPtr.Size = 8 Then
            Return SetWindowLongPtr64(hwnd, GWL_WNDPROC, ptr)
        Else
            Return SetWindowLong32(hwnd, GWL_WNDPROC, ptr)
        End If
    End Function

    <DllImport("user32.dll")> _
    Private Shared Function CallWindowProc(lpPrevWndFunc As IntPtr, hWnd As IntPtr, Msg As UInt32, wParam As IntPtr, lParam As IntPtr) As IntPtr
    End Function

    Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)
        prevWndProc = SetWindowProc(Me.Handle, AddressOf MyWindowProcedure)
    End Sub

    Private Function MyWindowProcedure(ByVal hWnd As IntPtr, ByVal msg As UInt32, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
        Debug.Print(msg.ToString)
        Return CallWindowProc(prevWndProc, hWnd, msg, wParam, lParam)
    End Function
End Class


问:
select names of students, whose GPA is greater than the average GPA on course and specialty
I have table "student":

```<code>+-----+---------+---------+------------+-------+
| id  |  name   | course  | specialty  |  gpa  |
+-----+---------+---------+------------+-------+
</code>```

How can I select names of students, whose GPA is greater than the average GPA on their course and specialty?

Thanks a lot

答:
```<code>SELECT name
FROM student s
INNER JOIN (
    SELECT course , speciality , AVG(gpa) gpa
    FROM student
    GROUP BY course , speciality
) a ON s.course = a.course AND s.speciality = a.speciality
WHERE s.gpa > a.gpa
</code>```

Body:
I have table "student":

+-----+---------+---------+------------+-------+
| id  |  name   | course  | specialty  |  gpa  |
+-----+---------+---------+------------+-------+

How can I select names of students, whose GPA is greater than the average GPA on their course and specialty?

Thanks a lot


问:
How to create Sql Synonym or "Alias" for Database Name?
I'm using ms sql 2008 and trying to create a database name that references another database. For example 'Dev', 'Test', 'Demo' would be database names that i could reference from my multiple config files, but each name would point to another database such as 'db20080101' or 'db20080114'.

[Edit]Some of the configs are for applications that i control the code and some aren't (ex. MS Reporting service datasource file configs)[/Edit]

It seems that sqlserver only supports synonyms for View,Table,Sproc, or Function. And Alias' are for table and column names.

Is there a way to do this that i missed in the docs?
Any one have any suggestions on a workaround?

答:
use 3 part notation and alias up to the table, example</p>

```<code>select * from tempdb.dbo.sysobjects a
join master.dbo.sysobjects b on a.id = b.id
</code>```

OwnerDisplayName: Kevin

LastEditorDisplayName: Cade Roux

Body:
use 3 part notation and alias up to the table, example

select * from tempdb.dbo.sysobjects a
join master.dbo.sysobjects b on a.id = b.id

OwnerDisplayName: SQLMenace


问:
Are there any good open source smalltalk implementations?
Do you know any good smalltalk implementations which meet the following criteria:

are open source (and free)

are enterprise ready - I can do commercial apps into it

works on os x

I'm asking this because I heard a lot about smalltalk, and I want to learn it - just for fun. But it seems to be hard to find the right tools and books for this language.

答: Pharo meets all your criteria. It is open source and free, it was forked from Squeak specially to be for professional development and because Squeak was actually born under the Apple umbrella, it supports OS X perfectly.</p>


问:
How to count methods in a Kotlin library
I am developing a future open source Android library with Kotlin, and I'd like to count the methods from my own code as well as from dependencies.
Since how Kotlin differs from Java, I assume the tool should take an aar input as a file to get the real methods count, but I only found tools taking apk files as inputs so far.

How can I do it the simplest way?

Thanks for your help!

答:
The dexcount-gradle-plugin works with libraries as well. The resulting @aar file should not differ when using Kotlin instead of Java, since Kotlin just compiles to Java byte code as well. So just use it and you'll get all the information you need for your library.

```<code>buildscript {
    dependencies {
        classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.6.4'
    }
}
apply plugin: 'com.getkeepsafe.dexcount'
</code>```

Body:
The dexcount-gradle-plugin works with libraries as well. The resulting @aar file should not differ when using Kotlin instead of Java, since Kotlin just compiles to Java byte code as well. So just use it and you'll get all the information you need for your library.

buildscript {
    dependencies {
        classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.6.4'
    }
}
apply plugin: 'com.getkeepsafe.dexcount'


问:
XQuery Show Collection Name
What is the XQuery to search the entire database and show the collection name which has a given element-name?</p>

答:
Thanks for your response. But I just ran the following query and got no response, why? My collection lexicon is enabled by the way:

cts:collections((), (),
cts:element-query(QName("http://www.w3.org/1999/html", "adr_key"), cts:true-query()))

Title: XQuery Show Collection Name


问:
how can i achieve FibonacciSecret in php
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>
</code>```

Output

```<code>h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-
</code>```

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

答:
Edit: this code will return an undefined index because it doesn't stop when it exceeds strlen

Made a similar edit as @mkaatman

Here's my 3v4l: https://3v4l.org/5KIZD

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$message = str_replace(' ', '', $message);
$str_split = str_split($message);

$x = 0;
$y = 1;
$farray[0] = 0;
$farray[1] = 1;

for($i=2;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       //echo $key . " => " . $fvalue . "\n";
       echo $str_split[$fvalue]."-";
}

?>
</code>```

Body:
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>

Output

h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

Body:
Edit: this code will return an undefined index because it doesn't stop when it exceeds strlen

Made a similar edit as @mkaatman

Here's my 3v4l: https://3v4l.org/5KIZD

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$message = str_replace(' ', '', $message);
$str_split = str_split($message);

$x = 0;
$y = 1;
$farray[0] = 0;
$farray[1] = 1;

for($i=2;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       //echo $key . " => " . $fvalue . "\n";
       echo $str_split[$fvalue]."-";
}

?>


问:
Variable for RowNum of first and last integer in a column and creating a range between the 2
I want to create two variables, one for the row number of the first integer in column J  and one for the last integer in column J (after this there are many rows of #N A N A).  I then would like to use these two points to create a range for column J but also for column D (using the same variables)
I just started using vba earlier this week, understand the simplicity and I have found similar answers elsewhere but none quite so specific.  Any help would be much appreciated.  What I have so far:</p>

```<code>Dim StartRow As Integer
Dim sht As Worksheet
Dim LastRow As Integer
Dim JRange As Range
Dim DRange As Range

Set StartRow = Range("j7:j100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells(1, 1).Row
LastNonRow = sht.Cells(sht.Rows.Count, 8).End(xlUp).Row (I fear this includes the #N A N A rows too)

Set JRange = sht.Range(StartRow,10,sht.Cells(LastRow,10))
Set DRange = sht.Range(StartRow,4,sht.Cells(LastRow,4))
</code>```

答:
There's a bunch of issues with your code:
Set StartRow - You only use Set when you're creating an object.
Also there's an issue with referencing the cells. There are a bunch of different ways to do this, I suggest to read up on this.

The following will take the first row with a number and the last row with a number, even if there are Non-number values in between. It will run on the currently active sheet.

```<code>Sub test()
Dim StartRow As Integer
Dim LastRow As Integer

Dim JRange As Range
Dim DRange As Range
Dim RangeForLoop As Range

StartRow = Range("J7:J100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells(1, 1).Row
For Each RangeForLoop In Range("J7:J100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells
    LastRow = RangeForLoop.Row
Next RangeForLoop

Set JRange = Range("J" & StartRow & ":J" & LastRow)
Set DRange = Range("D" & StartRow & ":D" & LastRow)

End Sub
</code>```

Body:
I want to create two variables, one for the row number of the first integer in column J  and one for the last integer in column J (after this there are many rows of #N A N A).  I then would like to use these two points to create a range for column J but also for column D (using the same variables)
I just started using vba earlier this week, understand the simplicity and I have found similar answers elsewhere but none quite so specific.  Any help would be much appreciated.  What I have so far:

Dim StartRow As Integer
Dim sht As Worksheet
Dim LastRow As Integer
Dim JRange As Range
Dim DRange As Range

Set StartRow = Range("j7:j100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells(1, 1).Row
LastNonRow = sht.Cells(sht.Rows.Count, 8).End(xlUp).Row (I fear this includes the #N A N A rows too)

Set JRange = sht.Range(StartRow,10,sht.Cells(LastRow,10))
Set DRange = sht.Range(StartRow,4,sht.Cells(LastRow,4))

Body:
There's a bunch of issues with your code:
Set StartRow - You only use Set when you're creating an object.
Also there's an issue with referencing the cells. There are a bunch of different ways to do this, I suggest to read up on this.

The following will take the first row with a number and the last row with a number, even if there are Non-number values in between. It will run on the currently active sheet.

Sub test()
Dim StartRow As Integer
Dim LastRow As Integer

Dim JRange As Range
Dim DRange As Range
Dim RangeForLoop As Range

StartRow = Range("J7:J100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells(1, 1).Row
For Each RangeForLoop In Range("J7:J100").SpecialCells(xlCellTypeConstants, xlNumbers).Cells
    LastRow = RangeForLoop.Row
Next RangeForLoop

Set JRange = Range("J" & StartRow & ":J" & LastRow)
Set DRange = Range("D" & StartRow & ":D" & LastRow)

End Sub


问:
Why is my rails db:migrate not working?
I typed in rails db:migrate and received the following error. I googled and someone said something like changing the Migration version from [4.2] to [5.1] but it still has not worked.

rails db:migrate
  rails aborted!
  StandardError: An error has occurred, this and all later migrations canceled:

Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:

class CreateCkeditorAssets < ActiveRecord::Migration[4.2]

答:
Rails 5 changed the way migrations are created. You'll have to specify the Rails release starting Rails 5 like this (assuming you're using Rails 5.1):

```<code>class CreateCkeditorAssets < ActiveRecord::Migration[5.1]
</code>```

Alternately, you can try creating a test migration and see how your version of Rails generates a migration and then take it from there:

```<code>rails g model Test name:string
</code>```

Title: Why is my rails db:migrate not working?

Body:
Rails 5 changed the way migrations are created. You'll have to specify the Rails release starting Rails 5 like this (assuming you're using Rails 5.1):

class CreateCkeditorAssets < ActiveRecord::Migration[5.1]

Alternately, you can try creating a test migration and see how your version of Rails generates a migration and then take it from there:

rails g model Test name:string


问:
How can I convert float to int?
```<code>cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);
</code>```

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

答:
I would just specify the number of digits on the formatting. It can be done by entering a format.

Like this:

```<code>// here                                |     |
cube1.name = string.Format("Terrain_{0:0}_{1:0}",
    Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);
</code>```

Title: How can I convert float to int?

Body:
cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

Body:
I would just specify the number of digits on the formatting. It can be done by entering a format.

Like this:

// here                                |     |
cube1.name = string.Format("Terrain_{0:0}_{1:0}",
    Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);


问:
Split string at different characters into 2d array
When I want to split a string at a character and put it into an array I use:

```<code>var arr = data.split("\n");
</code>```

This time however I need to split a string at different characters and need to store it into an 2d-array.
The string is as follows:

```<code>PMC12365AB
PMC23456AB
PMC34567AB
</code>```

The desired outcome

```<code>arr = [
    ["PMC", "12365", "AB"],
    ["PMC", "23456", "AB"],
    ["PMC", "34567", "AB"]
];
</code>```

Any ideas

答:
I wouldn't use regexp for this job. If you are already sure about the pattern of the text format (like n letters - m numbers - k letters) then you can simply use standard JS string operations like substr. However if you would like to give a little intelligence to this code then you can still do it by not touching regexp.

var input  = "PMC12365AB\nPMCX2347756AB\nPMC34567ABCT0123";
    result = input.split("\n")
                  .map(s => [].reduce.call(s, (p,c) => isNaN(p[p.length-1]) === isNaN(c) ? p + c : p + "_" + c).split("_"));
console.log(result);```

Body:
When I want to split a string at a character and put it into an array I use:

var arr = data.split("\n");

This time however I need to split a string at different characters and need to store it into an 2d-array.
The string is as follows:

PMC12365AB
PMC23456AB
PMC34567AB

The desired outcome

arr = [
    ["PMC", "12365", "AB"],
    ["PMC", "23456", "AB"],
    ["PMC", "34567", "AB"]
];

Any ideas


问:
HTML templating using Jinja2 - Lost
I am trying to create a html template in python using Jinja2. I have a templates folder with my 'template.html' but I don't know how to deal with environments or package loaders.

I installed Jinja2 using easy_python and ran the following script.

```<code>from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render()
</code>```

I get the following error because I don't know how to define a package/module. Please help me I just want to create a simple template.

```<code>  File "log_manipulationLL.py", line 291, in <module>
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
 File "/usr/local/lib/python2.7/dist-packages/Jinja2-2.6-py2.7.egg/jinja2/loaders.py",    line 216, in __init__
provider = get_provider(package_name)
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 213, in get_provider
__import__(moduleOrReq)
ImportError: No module named yourapplication
</code>```

答:
PackageLoader is defined like this:

```<code>class PackageLoader(BaseLoader):
    """Load templates from python eggs or packages.  It is constructed with
    the name of the python package and the path to the templates in that
    package::

        loader = PackageLoader('mypackage', 'views')

    If the package path is not given, ``'templates'`` is assumed.

    Per default the template encoding is ``'utf-8'`` which can be changed
    by setting the `encoding` parameter to something else.  Due to the nature
    of eggs it's only possible to reload templates if the package was loaded
    from the file system and not a zip file.
    """
</code>```

And then the __init__() method is as follows:

```<code>def __init__(self, package_name, package_path='templates',
             encoding='utf-8'):
</code>```

This makes us notice that a structure like this:

```<code>myapp/
  __init__.py
  ...
  templates/
    mytemplate.html
</code>```

Will have the same PackageLoader instance with both of these declarations:

```<code>PackageLoader('myapp')
PackageLoader('myapp', 'templates')
</code>```

And so if you are running from the myapp/ path, you then just need to say:

```<code>PackageLoader('templates', '')
</code>```

So that it will just take templates/ as the path. If you leave the 2nd argument empty, it will try to find the templates in templates/templates.

Finally, you can check what has been loaded by using the list_templates() method:

```<code>PackageLoader('templates', '').list_templates()
</code>```

Title: HTML templating using Jinja2 - Lost

Body:
I am trying to create a html template in python using Jinja2. I have a templates folder with my 'template.html' but I don't know how to deal with environments or package loaders.

I installed Jinja2 using easy_python and ran the following script.

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render()

I get the following error because I don't know how to define a package/module. Please help me I just want to create a simple template.

  File "log_manipulationLL.py", line 291, in <module>
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
 File "/usr/local/lib/python2.7/dist-packages/Jinja2-2.6-py2.7.egg/jinja2/loaders.py",    line 216, in __init__
provider = get_provider(package_name)
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 213, in get_provider
__import__(moduleOrReq)
ImportError: No module named yourapplication

Body:
PackageLoader is defined like this:

class PackageLoader(BaseLoader):
    """Load templates from python eggs or packages.  It is constructed with
    the name of the python package and the path to the templates in that
    package::

        loader = PackageLoader('mypackage', 'views')

    If the package path is not given, ``'templates'`` is assumed.

    Per default the template encoding is ``'utf-8'`` which can be changed
    by setting the `encoding` parameter to something else.  Due to the nature
    of eggs it's only possible to reload templates if the package was loaded
    from the file system and not a zip file.
    """

And then the __init__() method is as follows:

def __init__(self, package_name, package_path='templates',
             encoding='utf-8'):

This makes us notice that a structure like this:

myapp/
  __init__.py
  ...
  templates/
    mytemplate.html

Will have the same PackageLoader instance with both of these declarations:

PackageLoader('myapp')
PackageLoader('myapp', 'templates')

And so if you are running from the myapp/ path, you then just need to say:

PackageLoader('templates', '')

So that it will just take templates/ as the path. If you leave the 2nd argument empty, it will try to find the templates in templates/templates.

Finally, you can check what has been loaded by using the list_templates() method:

PackageLoader('templates', '').list_templates()


问:
TreeView one-at-a-time hander on CheckBoxTreeItem changes
I'm beginner in JavaFX.

I need to make one-at-a-time handler for any changes in the check boxes for my TreeView. Now it works like it handles all selected nodes simultaneously.

Thanks for help. Here is my code:

```<code>    package sample;

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.CheckBoxTreeItem;
    import javafx.scene.control.TreeView;
    import javafx.scene.control.cell.CheckBoxTreeCell;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;

    public class Main extends Application {

        @Override
        public void start(Stage primaryStage) throws Exception{
            BorderPane root = new BorderPane();
            root.setCenter(initTreeView());
            primaryStage.setTitle("Hello World");
            primaryStage.setScene(new Scene(root, 300, 275));

            primaryStage.show();
        }

        public TreeView initTreeView() {
            TreeView<String> treeView = new TreeView<>();
            treeView.setRoot(new CheckBoxTreeItem<>("123"));
            treeView.getRoot().addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), event -> System.out.println("hello"));
            treeView.setCellFactory(p -> new CheckBoxTreeCell<>());
            treeView.getRoot().getChildren().addAll(new CheckBoxTreeItem<>("1"),new CheckBoxTreeItem<>("2"), new CheckBoxTreeItem<>("3"));
            treeView.getRoot().getChildren().get(0).getChildren().addAll(new CheckBoxTreeItem<>("4"),new CheckBoxTreeItem<>("5"), new CheckBoxTreeItem<>("6"));
            treeView.getRoot().getChildren().get(1).getChildren().addAll(new CheckBoxTreeItem<>("7"),new CheckBoxTreeItem<>("8"), new CheckBoxTreeItem<>("9"));
            treeView.getRoot().getChildren().get(2).getChildren().addAll(new CheckBoxTreeItem<>("10"),new CheckBoxTreeItem<>("11"), new CheckBoxTreeItem<>("12"));
            return treeView;
        }

        public static void main(String[] args) {
            launch(args);
        }

    }
</code>```

答:
Actually it works correctly. Your event handler is called once for every changed checkbox node. Just note that changing subnodes affects parent ones as well, so you get several event handles calls.

Try next code instead which prints the name of the affected checkbox:

```<code>    treeView.getRoot().addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(),
        event -> System.out.println("hello " + event.getTreeItem().getValue()));
</code>```

For example, if you click on checkbox "5" you will get the following log:

```<code>hello 5
hello 1
hello 123
</code>```

because all parent node have changed state as well (from unchecked to intermediate "-" state). If you click "6" after that only one checkbox is affected and output will be:

```<code>hello 6
</code>```

Body:
I'm beginner in JavaFX.

I need to make one-at-a-time handler for any changes in the check boxes for my TreeView. Now it works like it handles all selected nodes simultaneously.

Thanks for help. Here is my code:

    package sample;

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.CheckBoxTreeItem;
    import javafx.scene.control.TreeView;
    import javafx.scene.control.cell.CheckBoxTreeCell;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;

    public class Main extends Application {

        @Override
        public void start(Stage primaryStage) throws Exception{
            BorderPane root = new BorderPane();
            root.setCenter(initTreeView());
            primaryStage.setTitle("Hello World");
            primaryStage.setScene(new Scene(root, 300, 275));

            primaryStage.show();
        }

        public TreeView initTreeView() {
            TreeView<String> treeView = new TreeView<>();
            treeView.setRoot(new CheckBoxTreeItem<>("123"));
            treeView.getRoot().addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), event -> System.out.println("hello"));
            treeView.setCellFactory(p -> new CheckBoxTreeCell<>());
            treeView.getRoot().getChildren().addAll(new CheckBoxTreeItem<>("1"),new CheckBoxTreeItem<>("2"), new CheckBoxTreeItem<>("3"));
            treeView.getRoot().getChildren().get(0).getChildren().addAll(new CheckBoxTreeItem<>("4"),new CheckBoxTreeItem<>("5"), new CheckBoxTreeItem<>("6"));
            treeView.getRoot().getChildren().get(1).getChildren().addAll(new CheckBoxTreeItem<>("7"),new CheckBoxTreeItem<>("8"), new CheckBoxTreeItem<>("9"));
            treeView.getRoot().getChildren().get(2).getChildren().addAll(new CheckBoxTreeItem<>("10"),new CheckBoxTreeItem<>("11"), new CheckBoxTreeItem<>("12"));
            return treeView;
        }

        public static void main(String[] args) {
            launch(args);
        }

    }

Body:
Actually it works correctly. Your event handler is called once for every changed checkbox node. Just note that changing subnodes affects parent ones as well, so you get several event handles calls.

Try next code instead which prints the name of the affected checkbox:

    treeView.getRoot().addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(),
        event -> System.out.println("hello " + event.getTreeItem().getValue()));

For example, if you click on checkbox "5" you will get the following log:

hello 5
hello 1
hello 123

because all parent node have changed state as well (from unchecked to intermediate "-" state). If you click "6" after that only one checkbox is affected and output will be:

hello 6


问:
nightwatch - check for popup window, after each click event
Is there a way in nightwatch to check whether a popup window appears after each click event?

I have a problem that randomly an error message appear and I don't want to write for each click event the same callback function.

I have already tried out the after and afterEach commands in the Global.js but then the commands will only run after the whole test suite.

I also have tried it local within a test file, although it also does not cover all single click events, even though the official website writes "... while beforeEach and afterEach are ran before and after each testcase (test step)"?

Solution I'm looking for:

```<code>.waitForElementVisible('selector')
    .click('selector')
    .click('selector')

</code>```

Solution I have come up with so far:

```<code>.waitForElementVisible('selector')
    .click('selector', isPresent)
    .click('selector', isPresent)
</code>```

isPresent as a callback function, which does the checking and close the popup window if it appears.

Is there another way to write a function (with or without after and/or forEach), so that it will be called after each click event or after each command. Thus, I don't have to write the isPresent repetitive code?

答: Why don't you write your own custom command specific for that case, so that way you will avoid repetitive code?</p>

Body:
Is there a way in nightwatch to check whether a popup window appears after each click event?

I have a problem that randomly an error message appear and I don't want to write for each click event the same callback function.

I have already tried out the after and afterEach commands in the Global.js but then the commands will only run after the whole test suite.

I also have tried it local within a test file, although it also does not cover all single click events, even though the official website writes "... while beforeEach and afterEach are ran before and after each testcase (test step)"?

Solution I'm looking for:

.waitForElementVisible('selector')
    .click('selector')
    .click('selector')

Solution I have come up with so far:

.waitForElementVisible('selector')
    .click('selector', isPresent)
    .click('selector', isPresent)

isPresent as a callback function, which does the checking and close the popup window if it appears.

Is there another way to write a function (with or without after and/or forEach), so that it will be called after each click event or after each command. Thus, I don't have to write the isPresent repetitive code?


问:
Combining rows of the same key into single array
I have a pandas dataframe as follows:

```<code>    error
 0: [[0.1,0.4,-0.3]]
 1: [[-0.6,-0.3,0.2]]
 .
 .
 .
 99: [[0.4,-0.7,0.1]]
</code>```

I would like to combine all values into a single array like this:

```<code> [0.1,0.4,-0.3,-0.6,-0.3,0.2,...,0.4,-0.7,0.1]
</code>```

Is there a fast way to do this using pandas or do I need to iterate over the data and build the array "manually" ?
The data order, in this case, is not important.

In a more general case, how to combine arrays that don't have the same size (e.g. row 0 contains an array of 3 elements, row 1 contains an array of 6 elements,etc...) ?

Body:
I have a pandas dataframe as follows:

    error
 0: [[0.1,0.4,-0.3]]
 1: [[-0.6,-0.3,0.2]]
 .
 .
 .
 99: [[0.4,-0.7,0.1]]

I would like to combine all values into a single array like this:

 [0.1,0.4,-0.3,-0.6,-0.3,0.2,...,0.4,-0.7,0.1]

Is there a fast way to do this using pandas or do I need to iterate over the data and build the array "manually" ?
The data order, in this case, is not important.

In a more general case, how to combine arrays that don't have the same size (e.g. row 0 contains an array of 3 elements, row 1 contains an array of 6 elements,etc...) ?

Body:
Use numpy.ravel:

L = np.array(df['error'].values.tolist()).ravel().tolist()
print (L)
[0.1, 0.4, -0.3, -0.6, -0.3, 0.2, 0.4, -0.7, 0.1]

More general solutions with str[0] for select nested lists:

print (df)
               error
0   [[0.1,0.4,-0.3]]
1      [[-0.6,-0.3]]
99  [[0.4,-0.7,0.1]]

from  itertools import chain

L = list(chain.from_iterable(df['error'].str[0]))
print (L)
[0.1, 0.4, -0.3, -0.6, -0.3, 0.4, -0.7, 0.1]

L =  np.concatenate(df['error'].str[0].values).tolist()
print (L)
[0.1, 0.4, -0.3, -0.6, -0.3, 0.4, -0.7, 0.1]


问:
Read function imported from kernel32.dll in pe on win64
I try to read functions imported from kernel32.dll in pe on win64.It seems that an zero filled IMAGE_THUNK_DATA is the end of IMAGE_THUNK_DATA array.But i found that in kernel32.dll's IMAGE_THUNK_DATA array the second IMAGE_THUNK_DATA is 0 filled.Does it mean there is only one imported function from kernel32? Or how to get the size of IMAGE_THUNK_DATA array?</p>

答:
An In-Depth Look into the Win32 Portable Executable File Format, Part 2:

Each IMAGE_IMPORT_DESCRIPTOR typically points to two essentially
identical arrays. These arrays have been called by several names, but
the two most common names are the Import Address Table (IAT) and the
Import Name Table (INT).

...

Both arrays have elements of type IMAGE_THUNK_DATA, which is a
pointer-sized union. Each IMAGE_THUNK_DATA element corresponds to one
imported function from the executable. The ends of both arrays are
indicated by an IMAGE_THUNK_DATA element with a value of zero.


问:
Is it bad to have your test and production environments on the same machine?
Would it be bad to have things set up so that MySite.com is production and test.MySite.com is test?  Both running off the same machine.  The site doesn't get a lot of traffic.

UPDATE

I am talking about an ASP.NET web application running on a Windows server.

答: It is a bad idea. When you have a new untested feature it may kill the production site.</p>


问:
RxJava continue emitting after subscribing again
i am struggling with implementation of RxJava with Socket.io. I have a problem to subscribe again to same observable, so i made an example and bit clearer code to understand.

here is the function:

```<code>private void testObservable() throws InterruptedException {
    io.reactivex.Observable observable = io.reactivex.Observable.create(new ObservableOnSubscribe() {
        @Override
        public void subscribe(ObservableEmitter e) throws Exception {
            for (int i = 0; i < 20; i++) {
                java.lang.Thread.sleep(100);
                e.onNext(i);
                Timber.d("TESTOBSERVER emit %d", i);
            }
            e.onComplete();
        }
    });
    DisposableObserver observer = new DisposableObserver<Integer>() {
        @Override
        public void onNext(Integer value) {
            Timber.d("TESTOBSERVER observed: %d", value);
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };
    observable.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(observer);
    Timber.d("TESTOBSERVER subscribe 1");

    java.lang.Thread.sleep(500);
    observer.dispose();

    Timber.d("TESTOBSERVER dispose 1");

    java.lang.Thread.sleep(500);
    observable.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(observer);
    Timber.d("TESTOBSERVER subscribe 2");
    java.lang.Thread.sleep(500);
    observer.dispose();
    Timber.d("TESTOBSERVER dispose 2");
}
</code>```

and here is what it prints

```<code>06-07 15:02:49.851 12649-12649/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER subscribe 1
06-07 15:02:49.951 12649-12840/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER emit 0
06-07 15:02:50.051 12649-12840/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER emit 1
06-07 15:02:50.161 12649-12840/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER emit 2
06-07 15:02:50.261 12649-12840/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER emit 3
06-07 15:02:50.351 12649-12649/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER dispose 1
06-07 15:02:50.861 12649-12649/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER subscribe 2
06-07 15:02:51.361 12649-12649/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER dispose 2
</code>```

I have two questions:

Why it doesn't print out TESTOBSERVER observed: 1?

Why after second subscribe it doesn't continue with emitting 9,10,11,12,13?

答:
Why it doesn't print out TESTOBSERVER observed: 1?

Presumably because testObservable() is executing on the android main thread. So there is never a chance to observe values using AndroidSchedulers.mainThread() before it is cancelled.

Why after second subscribe it doesn't continue with emitting 9,10,11,12,13?

Because Observables are not stateful. Every .subscribe() call is independant of all others.
The reason it does not emit anything is because Observer cannot be reused. So since it was already subscribed and disposed it will not subscribe to the observable.

Body:
i am struggling with implementation of RxJava with Socket.io. I have a problem to subscribe again to same observable, so i made an example and bit clearer code to understand.

here is the function:

private void testObservable() throws InterruptedException {
    io.reactivex.Observable observable = io.reactivex.Observable.create(new ObservableOnSubscribe() {
        @Override
        public void subscribe(ObservableEmitter e) throws Exception {
            for (int i = 0; i < 20; i++) {
                java.lang.Thread.sleep(100);
                e.onNext(i);
                Timber.d("TESTOBSERVER emit %d", i);
            }
            e.onComplete();
        }
    });
    DisposableObserver observer = new DisposableObserver<Integer>() {
        @Override
        public void onNext(Integer value) {
            Timber.d("TESTOBSERVER observed: %d", value);
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };
    observable.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(observer);
    Timber.d("TESTOBSERVER subscribe 1");

    java.lang.Thread.sleep(500);
    observer.dispose();

    Timber.d("TESTOBSERVER dispose 1");

    java.lang.Thread.sleep(500);
    observable.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(observer);
    Timber.d("TESTOBSERVER subscribe 2");
    java.lang.Thread.sleep(500);
    observer.dispose();
    Timber.d("TESTOBSERVER dispose 2");
}

and here is what it prints

06-07 15:02:49.851 12649-12649/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER subscribe 1
06-07 15:02:49.951 12649-12840/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER emit 0
06-07 15:02:50.051 12649-12840/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER emit 1
06-07 15:02:50.161 12649-12840/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER emit 2
06-07 15:02:50.261 12649-12840/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER emit 3
06-07 15:02:50.351 12649-12649/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER dispose 1
06-07 15:02:50.861 12649-12649/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER subscribe 2
06-07 15:02:51.361 12649-12649/com.skunkaga.Skunkaga D/ThreadListPresenter: TESTOBSERVER dispose 2

I have two questions:

Why it doesn't print out TESTOBSERVER observed: 1?

Why after second subscribe it doesn't continue with emitting 9,10,11,12,13?


问:
How to identify the Neighbours of a Visio-Shape in C#?
I am trying to implement a token game for BPMN processes in Microsoft Visio. As I am able to get all the drawed shapes, I want to identify the neighbours of a shape, in order to find out which shape comes next in the process.
That is my current idea for this token game.

However I am struggling with the documentation for these Visio-Shapes.

Does anybody know how to find out the next shape in such a process?

答:
Try use SpatialNeighbors property - https://msdn.microsoft.com/en-us/library/office/ff767509.aspx
Hope that article also can help
http://mikeborozdin.com/post/analysing-parent-child-relations-in-visio/</p>


问:
Is there a search engine with an API and python implament
i'm looking for a good search engine API for a project, a simple one that i can send a query and get a result set via API.

Google, bing, yahoo all seemed to stop providing with these kind of service and Faroo requires me to have an actual website.

thanks

答:
You can look into duckduckgo. Although not a complete API but this may serve partially the purpose.

Search engines are very large, complex and involved systems. The most valuable brand on this planet is a search engine giant. I am not surprised that this data is not readily available for people to consume and build their own apps.

And I also think Bing also gives you search results via APIs. I personally used it and it works perfectly fine.

I am not sure any of them has a official Python client(duckduckgo seems to have a community one). But with a little bit of work you can build one easily.


问:
sqlite3 c++ function: INSERT statement not executed when it comes as an argument
I am implementing a function that receives any SQL statement and then executes it.

```<code>void dbExec(std::string str, bool vertical)
{
   sqlite3 *db; // Create db object
   char *zErrMsg = 0;
   int rc;
   const char *sql = str.c_str(); // Convert string to char
   sqlite3_stmt *stmt = NULL; // SQL statement

   /* Open Database */
   rc = sqlite3_open("db/survey.db",&db);
   if (rc)
   {
      fprintf(stderr, "DBOPEN_ERR: %s\n", sqlite3_errmsg(db));
   }

   /* Execute SQL statement */
   rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); // Prepare statement

   if (rc != SQLITE_OK )
   { // Check error
      fprintf(stderr, "DB error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }

   int cols = sqlite3_column_count(stmt); // Number of columns
   const char *data = NULL; // data char pointer

   if (vertical)
   {
      sqlite3_step( stmt );
      for (int i = 0; i < cols; i++)
      {
         // Print column name and info
         data = (const char*)sqlite3_column_text( stmt, i );
         std::cout << std::setw(20) << sqlite3_column_name(stmt,i)
                   << std::setw(30) << (data ? data : "[NULL]" );
         printf("\n");
      }
   }
   else
   {
      for (int i = 0; i < cols; i++)
      {
         // Print column name
         std::cout << std::setw(15) << sqlite3_column_name(stmt,i);
      }
      printf("\n");

      while ( sqlite3_step( stmt ) == SQLITE_ROW )
      {
         // print each row
         for (int i = 0; i < cols; i++)
         {
            data = (const char*)sqlite3_column_text( stmt, i );
            std::cout << std::setw(15) << (data ? data : "[NULL]" );
         }
         printf("\n");
      }
   }

   /* Close Database */
   sqlite3_close(db);
}
</code>```

When the str argument is:

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

it works perfect. If the str argument is:

```<code>INSERT INTO TABLE (COL1) VALUES(100)
</code>```

it doesn't work.

However, if inside of the function I add the following line:

```<code>str = "INSERT INTO TABLE (COL1) VALUES(100)";
</code>```

it works perfect. I tried many things but I still can't figure out what's going on... Any ideas?

Thanks!

EDIT:
The function dbExec is being called in this way:

```<code>void addBorehole()
{
   std::string statement;
   statement = "INSERT INTO BOREHOLE (TOTAL_DEPTH) VALUES (45)";

   dbExec(statement, false);
}
</code>```

答:
Your problem is that the database is busy (SQLITE_BUSY). The documentation sais:

[...] SQLITE_BUSY indicates a conflict with a separate database connection, probably in a separate process [...]

So there must be a process that is blocking your database.
To get the process which is blocking the database you can do the following (Copied from the Stack Exchange network).

Linux:

$ fuser development.db

This command will show what process is locking the file:

> development.db: 5430

Just kill the process...

kill -9 5430

Windows:

PowerShell method:

```<code>IF((Test-Path -Path $FileOrFolderPath) -eq $false) {
    Write-Warning "File or directory does not exist."
}
Else {
    $LockingProcess = CMD /C "openfiles /query /fo table | find /I ""$FileOrFolderPath"""
    Write-Host $LockingProcess
}
</code>```

More details How to find out which process is locking a file or folder in Windows

The other method for Windows would be to use the ProcessExplorer.

Body:
I am implementing a function that receives any SQL statement and then executes it.

void dbExec(std::string str, bool vertical)
{
   sqlite3 *db; // Create db object
   char *zErrMsg = 0;
   int rc;
   const char *sql = str.c_str(); // Convert string to char
   sqlite3_stmt *stmt = NULL; // SQL statement

   /* Open Database */
   rc = sqlite3_open("db/survey.db",&db);
   if (rc)
   {
      fprintf(stderr, "DBOPEN_ERR: %s\n", sqlite3_errmsg(db));
   }

   /* Execute SQL statement */
   rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); // Prepare statement

   if (rc != SQLITE_OK )
   { // Check error
      fprintf(stderr, "DB error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }

   int cols = sqlite3_column_count(stmt); // Number of columns
   const char *data = NULL; // data char pointer

   if (vertical)
   {
      sqlite3_step( stmt );
      for (int i = 0; i < cols; i++)
      {
         // Print column name and info
         data = (const char*)sqlite3_column_text( stmt, i );
         std::cout << std::setw(20) << sqlite3_column_name(stmt,i)
                   << std::setw(30) << (data ? data : "[NULL]" );
         printf("\n");
      }
   }
   else
   {
      for (int i = 0; i < cols; i++)
      {
         // Print column name
         std::cout << std::setw(15) << sqlite3_column_name(stmt,i);
      }
      printf("\n");

      while ( sqlite3_step( stmt ) == SQLITE_ROW )
      {
         // print each row
         for (int i = 0; i < cols; i++)
         {
            data = (const char*)sqlite3_column_text( stmt, i );
            std::cout << std::setw(15) << (data ? data : "[NULL]" );
         }
         printf("\n");
      }
   }

   /* Close Database */
   sqlite3_close(db);
}

When the str argument is:

SELECT * FROM TABLE

it works perfect. If the str argument is:

INSERT INTO TABLE (COL1) VALUES(100)

it doesn't work.

However, if inside of the function I add the following line:

str = "INSERT INTO TABLE (COL1) VALUES(100)";

it works perfect. I tried many things but I still can't figure out what's going on... Any ideas?

Thanks!

EDIT:
The function dbExec is being called in this way:

void addBorehole()
{
   std::string statement;
   statement = "INSERT INTO BOREHOLE (TOTAL_DEPTH) VALUES (45)";

   dbExec(statement, false);
}

Body:
Your problem is that the database is busy (SQLITE_BUSY). The documentation sais:

[...] SQLITE_BUSY indicates a conflict with a separate database connection, probably in a separate process [...]

So there must be a process that is blocking your database.
To get the process which is blocking the database you can do the following (Copied from the Stack Exchange network).

Linux:

$ fuser development.db

This command will show what process is locking the file:

> development.db: 5430

Just kill the process...

kill -9 5430

Windows:

PowerShell method:

IF((Test-Path -Path $FileOrFolderPath) -eq $false) {
    Write-Warning "File or directory does not exist."
}
Else {
    $LockingProcess = CMD /C "openfiles /query /fo table | find /I ""$FileOrFolderPath"""
    Write-Host $LockingProcess
}

More details How to find out which process is locking a file or folder in Windows

The other method for Windows would be to use the ProcessExplorer.


问:
spring-kafka how to run consumer in background
I found a tutorial on spring-kafka where they created a producer and consumer. However, the program was run through a test case. As the test case ends, the consumer stops.

How to ensure the consumer keeps running in the backgorund so that I can test some messages from my terminal command line.

SpringKafkaExampleApplication.java

```<code>package com.howtoprogram.kafka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringKafkaExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringKafkaExampleApplication.class,
        args);
    }
}
</code>```

KafkaProducerConfig.java

```<code>package com.howtoprogram.kafka;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

@Configuration
@EnableKafka
public class KafkaProducerConfig {
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
        "localhost:9092");
        props.put(ProducerConfig.RETRIES_CONFIG, 0);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        return props;
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<String, String>(producerFactory());
    }
}
</code>```

KafkaConsumerConfig.java

```<code>package com.howtoprogram.kafka;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;

@Configuration
@EnableKafka
public class KafkaConsumerConfig {
    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(3);
        factory.getContainerProperties().setPollTimeout(3000);
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");
        propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        return propsMap;
    }

    @Bean
    public Listener listener() {
        return new Listener();
    }
}
</code>```

Listener.java

```<code>package com.howtoprogram.kafka;

import java.util.concurrent.CountDownLatch;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;

public class Listener {

public final CountDownLatch countDownLatch1 = new CountDownLatch(1);

    @KafkaListener(id = "foo", topics = "topic1", group = "group1")
    public void listen(ConsumerRecord<?, ?> record) {
        System.out.println(record);
        countDownLatch1.countDown();
    }

}
</code>```

SpringKafkaExampleApplicationTests.java

```<code>package com.howtoprogram.kafka;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.concurrent.TimeUnit;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringKafkaExampleApplicationTests {

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
private Listener listener;

@Test
public void contextLoads() throws InterruptedException {

    ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("topic1", "ABC");
    future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
        @Override
        public void onSuccess(SendResult<String, String> result) {
            System.out.println("success");
        }

        @Override
        public void onFailure(Throwable ex) {
            System.out.println("failed");
        }
    });
    System.out.println(Thread.currentThread().getId());
    assertThat(this.listener.countDownLatch1.await(60, TimeUnit.SECONDS)).isTrue();

}

}
</code>```

Please help!

答:
Add this code to your main after SpringApplication.run():

```<code>System.out.println("Hit 'Enter' to terminate");
System.in.read();
ctx.close();
System.exit(0);
</code>```

And your program won't exit until you hit the Enter button in console.

Body:
I found a tutorial on spring-kafka where they created a producer and consumer. However, the program was run through a test case. As the test case ends, the consumer stops.

How to ensure the consumer keeps running in the backgorund so that I can test some messages from my terminal command line.

SpringKafkaExampleApplication.java

package com.howtoprogram.kafka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

KafkaProducerConfig.java

package com.howtoprogram.kafka;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

@Configuration
@EnableKafka
public class KafkaProducerConfig {
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
        "localhost:9092");
        props.put(ProducerConfig.RETRIES_CONFIG, 0);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        return props;
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<String, String>(producerFactory());
    }
}

KafkaConsumerConfig.java

package com.howtoprogram.kafka;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;

@Configuration
@EnableKafka
public class KafkaConsumerConfig {
    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(3);
        factory.getContainerProperties().setPollTimeout(3000);
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");
        propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        return propsMap;
    }

    @Bean
    public Listener listener() {
        return new Listener();
    }
}

Listener.java

package com.howtoprogram.kafka;

import java.util.concurrent.CountDownLatch;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;

public class Listener {

public final CountDownLatch countDownLatch1 = new CountDownLatch(1);

    @KafkaListener(id = "foo", topics = "topic1", group = "group1")
    public void listen(ConsumerRecord<?, ?> record) {
        System.out.println(record);
        countDownLatch1.countDown();
    }

}

SpringKafkaExampleApplicationTests.java

package com.howtoprogram.kafka;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.concurrent.TimeUnit;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringKafkaExampleApplicationTests {

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
private Listener listener;

@Test
public void contextLoads() throws InterruptedException {

    ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("topic1", "ABC");
    future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
        @Override
        public void onSuccess(SendResult<String, String> result) {
            System.out.println("success");
        }

        @Override
        public void onFailure(Throwable ex) {
            System.out.println("failed");
        }
    });
    System.out.println(Thread.currentThread().getId());
    assertThat(this.listener.countDownLatch1.await(60, TimeUnit.SECONDS)).isTrue();

}

}

Please help!

Body:
Add this code to your main after SpringApplication.run():

System.out.println("Hit 'Enter' to terminate");
System.in.read();
ctx.close();
System.exit(0);

And your program won't exit until you hit the Enter button in console.


问:
Changing an image while click is held
I am looking to change an image of a button from when a click is held, then change back upon click release. I currently have a flat image, and I want it to change to one with an inner-shadow to make it look like a button press, but change back to the original flat image when the mouse click is released. I tried onmouseup but I think i'm using it incorrectly. I want the "item" and "item2" to hold their image when clicked, and that works correctly. However I want the "item3" to change back upon mouse release, or just change back instantly after being clicked.

(Edit: I'm new to JavaScript, it doesn't have to be an onmouseup solution. If someone can explain how to create a function which does this then that would be great.)

JS:

```<code>var onImgStp= "images/stop.png";
var onImgPnk= "images/pink.png";
var onImgMut= "images/mute.png";
var offImg= "images/green.png";
var offImgStp= "images/stop2.png";
</code>```

HTML:

```<code><img class="item" src="images/pink.png" onclick="manage(1); this.src = (this.src.endsWith(offImg)? onImgPnk : offImg);"/>
<img class="item" src="images/pink.png" onclick="manage(2); this.src = (this.src.endsWith(offImg)? onImgPnk : offImg);"/>
<img class="item" src="images/pink.png" onclick="manage(3); this.src = (this.src.endsWith(offImg)? onImgPnk : offImg);"/>
<img class="item" src="images/pink.png" onclick="manage(4); this.src = (this.src.endsWith(offImg)? onImgPnk : offImg);"/>
<img class="item" src="images/pink.png" onclick="manage(5); this.src = (this.src.endsWith(offImg)? onImgPnk : offImg);"/>
<img class="item" src="images/pink.png" onclick="manage(6); this.src = (this.src.endsWith(offImg)? onImgPnk : offImg);"/>
<img class="item" src="images/pink.png" onclick="manage(7); this.src = (this.src.endsWith(offImg)? onImgPnk : offImg);"/>
<img class="item" src="images/pink.png" onclick="manage(8); this.src = (this.src.endsWith(offImg)? onImgPnk : offImg);"/>
<img class="item2" src="images/mute.png" onclick="this.src = (this.src.endsWith(offImg)? onImgMut : offImg);"/>
<img class="item3" src="images/stop.png" onmouseup="this.src = (this.src.endsWith(offImgStp)? onImgStp : offImgStp);"/>
</code>```

答:
Simple solution

.image-swap {
  cursor: pointer;
}

.image-swap>img, .image-swap:active>img:first-child {
  display: none;
}

.image-swap>img:first-child, .image-swap:active>img:last-child {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-swap">
  <img src="http://blog.hvidtfeldts.net/media/city7.png" />
  <img src="http://blog.hvidtfeldts.net/media/city2.png" />
</div></code>```

Remove select and drag effect

.image-swap {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  cursor: pointer;
}

.image-swap>img {
  pointer-events: none;
  display: none;
}

.image-swap>img:first-child {
  display: block;
}

.image-swap:active>img:first-child {
  display: none;
}

.image-swap:active>img:last-child {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-swap">
  <img src="http://blog.hvidtfeldts.net/media/city7.png" />
  <img src="http://blog.hvidtfeldts.net/media/city2.png" />
</div></code>```

Smooth transition

.image-swap {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  cursor: pointer;
  position: relative;
}

.image-swap>img {
  pointer-events: none;
  transition: all 0.6s;
  position: absolute;
  opacity: 0;
  left: 0;
}

.image-swap>img:first-child {
  position: static;
  opacity: 1;
}

.image-swap:active>img:first-child {
  opacity: 0;
}

.image-swap:active>img:last-child {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-swap">
  <img src="http://blog.hvidtfeldts.net/media/city7.png" />
  <img src="http://blog.hvidtfeldts.net/media/city2.png" />
</div></code>```

If you want you could give classes to the images like base-img and active-img

So you could replace the :first-child with .base-img and :last-child with .active-img

Title: Changing an image while click is held

Body:
I am looking to change an image of a button from when a click is held, then change back upon click release. I currently have a flat image, and I want it to change to one with an inner-shadow to make it look like a button press, but change back to the original flat image when the mouse click is released. I tried onmouseup but I think i'm using it incorrectly. I want the "item" and "item2" to hold their image when clicked, and that works correctly. However I want the "item3" to change back upon mouse release, or just change back instantly after being clicked.

(Edit: I'm new to JavaScript, it doesn't have to be an onmouseup solution. If someone can explain how to create a function which does this then that would be great.)

JS:

var onImgStp= "images/stop.png";
var onImgPnk= "images/pink.png";
var onImgMut= "images/mute.png";
var offImg= "images/green.png";
var offImgStp= "images/stop2.png";

HTML:

Body:
Simple solution

.image-swap {
  cursor: pointer;
}

.image-swap>img, .image-swap:active>img:first-child {
  display: none;
}

.image-swap>img:first-child, .image-swap:active>img:last-child {
  display: block;
}

<div class="image-swap">
  <img src="http://blog.hvidtfeldts.net/media/city7.png" />
  <img src="http://blog.hvidtfeldts.net/media/city2.png" />
</div>

Remove select and drag effect

.image-swap {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  cursor: pointer;
}

.image-swap>img {
  pointer-events: none;
  display: none;
}

.image-swap>img:first-child {
  display: block;
}

.image-swap:active>img:first-child {
  display: none;
}

.image-swap:active>img:last-child {
  display: block;
}

<div class="image-swap">
  <img src="http://blog.hvidtfeldts.net/media/city7.png" />
  <img src="http://blog.hvidtfeldts.net/media/city2.png" />
</div>

Smooth transition

.image-swap {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  cursor: pointer;
  position: relative;
}

.image-swap>img {
  pointer-events: none;
  transition: all 0.6s;
  position: absolute;
  opacity: 0;
  left: 0;
}

.image-swap>img:first-child {
  position: static;
  opacity: 1;
}

.image-swap:active>img:first-child {
  opacity: 0;
}

.image-swap:active>img:last-child {
  opacity: 1;
}

<div class="image-swap">
  <img src="http://blog.hvidtfeldts.net/media/city7.png" />
  <img src="http://blog.hvidtfeldts.net/media/city2.png" />
</div>

If you want you could give classes to the images like base-img and active-img

So you could replace the :first-child with .base-img and :last-child with .active-img


问:
neutral element to cbind with dataframe
i can do the following:

```<code>a <- rep(5,5)

> cbind(6,a)
       a
[1,] 6 5
[2,] 6 5
[3,] 6 5
[4,] 6 5
[5,] 6 5
> cbind(NULL,a)
     a
[1,] 5
[2,] 5
[3,] 5
[4,] 5
[5,] 5
</code>```

When i do it with a dataframe it gives me an error

```<code>> cbind(NULL,mtcars)

Error in data.frame(..., check.names = FALSE) :    arguments imply differing number of rows: 0, 32
</code>```

What is the neutral element so that:

```<code>cbind(neutralElement,DF) = DF
</code>```

EDIT:

I have a code where something goes like cbind(IDCOL,DF). In the function IDCOL can also be non-Exisiting so it would be convinient to just set IDCOL to the neutral element so the code still runs smooth.

答:
What you are looking for is unlikely to exist.

Documentation of the cbind and rbind command:

If there are several matrix arguments, they must all have the same number of columns (or rows) and this will be the number of columns (or rows) of the result. If all the arguments are vectors, the number of columns (rows) in the result is equal to the length of the longest vector. Values in shorter arguments are recycled to achieve this length (with a warning if they are recycled only fractionally). ... For cbind (rbind), vectors of zero length (including NULL) are ignored unless the result would have zero rows (columns), for S compatibility.

Thus, I would suggest working with an if-else condition:

```<code>if(length(IDCOL) > 0) {
   cbind(IDCOL, df) # make sure lengths are identical
} else {
   df # do whatever you want here
}
</code>```

Title: neutral element to cbind with dataframe

Body:
i can do the following:

a <- rep(5,5)

> cbind(6,a)
       a
[1,] 6 5
[2,] 6 5
[3,] 6 5
[4,] 6 5
[5,] 6 5
> cbind(NULL,a)
     a
[1,] 5
[2,] 5
[3,] 5
[4,] 5
[5,] 5

When i do it with a dataframe it gives me an error

> cbind(NULL,mtcars)

Error in data.frame(..., check.names = FALSE) :    arguments imply differing number of rows: 0, 32

What is the neutral element so that:

cbind(neutralElement,DF) = DF

EDIT:

I have a code where something goes like cbind(IDCOL,DF). In the function IDCOL can also be non-Exisiting so it would be convinient to just set IDCOL to the neutral element so the code still runs smooth.

Body:
What you are looking for is unlikely to exist.

Documentation of the cbind and rbind command:

If there are several matrix arguments, they must all have the same number of columns (or rows) and this will be the number of columns (or rows) of the result. If all the arguments are vectors, the number of columns (rows) in the result is equal to the length of the longest vector. Values in shorter arguments are recycled to achieve this length (with a warning if they are recycled only fractionally). ... For cbind (rbind), vectors of zero length (including NULL) are ignored unless the result would have zero rows (columns), for S compatibility.

Thus, I would suggest working with an if-else condition:

if(length(IDCOL) > 0) {
   cbind(IDCOL, df) # make sure lengths are identical
} else {
   df # do whatever you want here
}


问:
get text in between text using regex
I want to extract the text in between the %3A.

Here is the sample phrase :

```<code>http://www.sample.com/res?ccode=1232&note=sampletext&token=12Add-12sre-24Aod-23343-34kdi%3A3232121%3ATVLOPQUI%3AIOOPDA%3AKKKKK%3A&ltr=23232
</code>```

I tried below expression:

```<code>[&]{1}token[=]{1}([a-zA-Z0-9-%]*)(%3A(.*?)%3A){1}
</code>```

but the expected phrase is : 3232121

whereas, it is capturing the invalid thing.

Can you please suggest me, how to do that in better way

答:
You can use a positive lookbehind to find %3A, then match all digits after that.

```<code>(?<=%3A|:)(\d+)
</code>```

https://regex101.com/r/IHaXQT/4

Title: get text in between text using regex

Body:
I want to extract the text in between the %3A.

Here is the sample phrase :

http://www.sample.com/res?ccode=1232&note=sampletext&token=12Add-12sre-24Aod-23343-34kdi%3A3232121%3ATVLOPQUI%3AIOOPDA%3AKKKKK%3A&ltr=23232

I tried below expression:

[&]{1}token[=]{1}([a-zA-Z0-9-%]*)(%3A(.*?)%3A){1}

but the expected phrase is : 3232121

whereas, it is capturing the invalid thing.

Can you please suggest me, how to do that in better way

Body:
You can use a positive lookbehind to find %3A, then match all digits after that.

(?<=%3A|:)(\d+)

https://regex101.com/r/IHaXQT/4