问:
Export Excel range/sheet to formatted text file
I have been tasked with creating a reusable process for our Finance Dept to upload our payroll to the State(WI) for reporting. I need to create something that takes a sheet or range in Excel and creates a specifically formatted text file.

THE FORMAT

Column 1 - A Static Number, never changes, position 1-10

Column 2 - A Dynamic Param filled at runtime for Quarter/Year, position 11-13

Column 3 - SSN, no hyphens or spaces,
filled from column A, position 14-22

Column 4 - Last Name, filled from
column B, Truncated at 10, Left
Justify & fill with blanks, position
23-32

Column 5 - First Name, filled from C,
Truncate at 8, Left Justify & fill
with blanks, position 33-40

Column 6 - Total Gross Wages/Quarter,
filled from D, strip all formatting,
Right Justify Zero Fill, position
41-49

Column 7 - A Static Code, never
changes, position 50-51

Column 8 - BLANKS, Fill with blanks,
position 52-80

I have, I assume, 3 options:

VBA

.NET

SQL

I had explored the .NET method first but I just couldn't find decent documentation to get me going.  I still like this one but I digress.

Next I have some VBA that will dump a Sheet to a fixed width Text.  I am currently pursuing this which leads, finally, to my actual question.

How do I transform a Range of text in Excel?  Do I need to coy it over to another sheet and then pass over that data with the neccesarry formatting functions the run my Dump to text routine?  I currently had planned to have a function for each column but I am having trouble figuring out how to take the next step.  I am fairly new at Office programming and developing in general so any insight will be greatly appreciated.

The SQL option would be my fall back as I have done similar exports from SQL in the past.  I just prefer the other two on the, "I don't want to be responsible for running this," principle.

Thanks in advance for any time given.

答:
Wow!

I have to say, I am blown away.  You so far exceeded my expectations for an answer that I feel guilty that I can ONLY up vote you once and mark as excepted.  I had HOPED for so guidance towards which path was best and some formatting.  Well Happy Birthday to me!

The Format() and FreeFile() were especially new useful info.  Also, just to show that I was trying, my attempt is below.  I was quite close as I was just working out the formatting details but I believe I shall rework it with your input as it seems the more elegant approach.

As a final note.  I found this place thru Jeff Atwood's blog and I was truly excited by the idea.  As a new, inexperienced developer in a solo shop I had always wished there was someplace I could turn for mentorship.  Books and articles get you to a point but nothing equals the advice of someone who's done it or been there.  So far StackOverflow has delivered.

For reference, I posted this exact same question on another very popular Code Forum and have yet to receive a single response in any way.

Now for my attempt:

The Module Code

```<code>
    Sub StateANSIIExport()
    Dim Sizes As Variant
    Dim arr As Variant
    Dim aRow As Long, aCol As Long
    Dim rowLimit As Integer, colLimit As Integer
    Dim SpacesPerCell As Integer
    Dim fso As Object
    Dim ts As Object
    Dim TheLine As String
    Dim TestStr As String

    arr = ActiveSheet.UsedRange
    rowLimit = UBound(arr, 1)
    'colLimit = UBound(arr, 2)
    colLimit = 8
    SpacesPerCell = 20      'Set export text "column" width here

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.CreateTextFile(GetDesktopPath() & "EXCELTEXT.txt", True)

    ' Loop thru the rows
    For aRow = 1 To rowLimit
        TheLine = Space(colLimit * SpacesPerCell)     ' your fixed-width output
        ' Loop thru the columns
        For aCol = 1 To colLimit
            Select Case aCol
                Case 1  ' Employer UI Account #
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = "6979430002"
                Case 2  ' Reporting Period (QYY)
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = "109"
                Case 3  ' SSN
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = Cells(aRow, "A")
                Case 4  ' Last Name
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = Cells(aRow, "B")
                Case 5  ' First Name
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = Cells(aRow, "C")
                Case 6  ' Employee Quartly Gross Wages
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = Cells(aRow, "D")
                Case 7   ' Record Code
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = "01"
                Case 8  ' BLANK
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = "                             "
            End Select
        Next aCol
        ' Write the line to the file
        ts.WriteLine TheLine
    Next aRow

    ts.Close

    Set ts = Nothing
    Set fso = Nothing

    MsgBox "Done"
End Sub

    Sub MacroToRunTwo()
    Dim S As String
    S = "Hello World From Two:" & vbCrLf & _
        "This Add-In File Name: " & ThisWorkbook.FullName
    MsgBox S
End Sub

Function GetDesktopPath() As String
'Return the current user's desktop path
GetDesktopPath = "C:\Users\patrick\Desktop\"
'GetDesktopPath = Environ("HOMEDRIVE") & Environ("HOMEPATH") & "\Desktop\"
End Function
</code>```

And The WorkBook Code:

```<code>
    Private Const C_TAG = "Refracted Solutions" ' C_TAG should be a string unique to this add-in.
Private Const C_TOOLS_MENU_ID As Long = 30007&

Private Sub Workbook_Open()
'''''''''''''''''''''''''''''''''''''''''''''''
' Workbook_Open
' Create a submenu on the Tools menu. The
' submenu has two controls on it.
'''''''''''''''''''''''''''''''''''''''''''''''
Dim ToolsMenu As Office.CommandBarControl
Dim ToolsMenuItem As Office.CommandBarControl
Dim ToolsMenuControl As Office.CommandBarControl

'''''''''''''''''''''''''''''''''''''''''''''''
' First delete any of our controls that
' may not have been properly deleted previously.
'''''''''''''''''''''''''''''''''''''''''''''''
DeleteControls

''''''''''''''''''''''''''''''''''''''''''''''
' Get a reference to the Tools menu.
''''''''''''''''''''''''''''''''''''''''''''''
Set ToolsMenu = Application.CommandBars.FindControl(ID:=C_TOOLS_MENU_ID)
If ToolsMenu Is Nothing Then
    MsgBox "Unable to access Tools menu.", vbOKOnly
    Exit Sub
End If

''''''''''''''''''''''''''''''''''''''''''''''
' Create a item on the Tools menu.
''''''''''''''''''''''''''''''''''''''''''''''
Set ToolsMenuItem = ToolsMenu.Controls.Add(Type:=msoControlPopup, temporary:=True)
If ToolsMenuItem Is Nothing Then
    MsgBox "Unable to add item to the Tools menu.", vbOKOnly
    Exit Sub
End If

With ToolsMenuItem
    .Caption = "&WWCares"
    .BeginGroup = True
    .Tag = C_TAG
End With

''''''''''''''''''''''''''''''''''''''''''''''
' Create the first control on the new item
' in the Tools menu.
''''''''''''''''''''''''''''''''''''''''''''''
Set ToolsMenuControl = ToolsMenuItem.Controls.Add(Type:=msoControlButton, temporary:=True)
If ToolsMenuControl Is Nothing Then
    MsgBox "Unable to add item to Tools menu item.", vbOKOnly
    Exit Sub
End If

With ToolsMenuControl
    ''''''''''''''''''''''''''''''''''''
    ' Set the display caption and the
    ' procedure to run when clicked.
    ''''''''''''''''''''''''''''''''''''
    .Caption = "State ANSII E&xport"
    .OnAction = "'" & ThisWorkbook.Name & "'!StateANSIIExport"
    .Tag = C_TAG
End With

''''''''''''''''''''''''''''''''''''''''''''''
' Create the second control on the new item
' in the Tools menu.
''''''''''''''''''''''''''''''''''''''''''''''
'Set ToolsMenuControl = ToolsMenuItem.Controls.Add(Type:=msoControlButton, temporary:=True)
'If ToolsMenuControl Is Nothing Then
'    MsgBox "Unable to add item to Tools menu item.", vbOKOnly
'    Exit Sub
'End If

'With ToolsMenuControl
    ''''''''''''''''''''''''''''''''''''
    ' Set the display caption and the
    ' procedure to run when clicked.
    ''''''''''''''''''''''''''''''''''''
'    .Caption = "Click Me &Two"
'    .OnAction = "'" & ThisWorkbook.Name & "'!MacroToRunTwo"
'    .Tag = C_TAG
'End With

End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
''''''''''''''''''''''''''''''''''''''''''''''''''''
' Workbook_BeforeClose
' Before closing the add-in, clean up our controls.
''''''''''''''''''''''''''''''''''''''''''''''''''''
    DeleteControls
End Sub

Private Sub DeleteControls()
''''''''''''''''''''''''''''''''''''
' Delete controls whose Tag is
' equal to C_TAG.
''''''''''''''''''''''''''''''''''''
Dim Ctrl As Office.CommandBarControl

On Error Resume Next
Set Ctrl = Application.CommandBars.FindControl(Tag:=C_TAG)

Do Until Ctrl Is Nothing
    Ctrl.Delete
    Set Ctrl = Application.CommandBars.FindControl(Tag:=C_TAG)
Loop

End Sub

</code>```

LastEditorDisplayName: Mark Nold

Body:
Wow!

I have to say, I am blown away.  You so far exceeded my expectations for an answer that I feel guilty that I can ONLY up vote you once and mark as excepted.  I had HOPED for so guidance towards which path was best and some formatting.  Well Happy Birthday to me!

The Format() and FreeFile() were especially new useful info.  Also, just to show that I was trying, my attempt is below.  I was quite close as I was just working out the formatting details but I believe I shall rework it with your input as it seems the more elegant approach.

As a final note.  I found this place thru Jeff Atwood's blog and I was truly excited by the idea.  As a new, inexperienced developer in a solo shop I had always wished there was someplace I could turn for mentorship.  Books and articles get you to a point but nothing equals the advice of someone who's done it or been there.  So far StackOverflow has delivered.

For reference, I posted this exact same question on another very popular Code Forum and have yet to receive a single response in any way.

Now for my attempt:

The Module Code

    Sub StateANSIIExport()
    Dim Sizes As Variant
    Dim arr As Variant
    Dim aRow As Long, aCol As Long
    Dim rowLimit As Integer, colLimit As Integer
    Dim SpacesPerCell As Integer
    Dim fso As Object
    Dim ts As Object
    Dim TheLine As String
    Dim TestStr As String

    arr = ActiveSheet.UsedRange
    rowLimit = UBound(arr, 1)
    'colLimit = UBound(arr, 2)
    colLimit = 8
    SpacesPerCell = 20      'Set export text "column" width here

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.CreateTextFile(GetDesktopPath() & "EXCELTEXT.txt", True)

    ' Loop thru the rows
    For aRow = 1 To rowLimit
        TheLine = Space(colLimit * SpacesPerCell)     ' your fixed-width output
        ' Loop thru the columns
        For aCol = 1 To colLimit
            Select Case aCol
                Case 1  ' Employer UI Account #
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = "6979430002"
                Case 2  ' Reporting Period (QYY)
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = "109"
                Case 3  ' SSN
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = Cells(aRow, "A")
                Case 4  ' Last Name
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = Cells(aRow, "B")
                Case 5  ' First Name
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = Cells(aRow, "C")
                Case 6  ' Employee Quartly Gross Wages
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = Cells(aRow, "D")
                Case 7   ' Record Code
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = "01"
                Case 8  ' BLANK
                    Mid(TheLine, aCol * SpacesPerCell - SpacesPerCell + 1, SpacesPerCell) = "                             "
            End Select
        Next aCol
        ' Write the line to the file
        ts.WriteLine TheLine
    Next aRow

    ts.Close

    Set ts = Nothing
    Set fso = Nothing

    MsgBox "Done"
End Sub

    Sub MacroToRunTwo()
    Dim S As String
    S = "Hello World From Two:" & vbCrLf & _
        "This Add-In File Name: " & ThisWorkbook.FullName
    MsgBox S
End Sub

Function GetDesktopPath() As String
'Return the current user's desktop path
GetDesktopPath = "C:\Users\patrick\Desktop\"
'GetDesktopPath = Environ("HOMEDRIVE") & Environ("HOMEPATH") & "\Desktop\"
End Function

And The WorkBook Code:

    Private Const C_TAG = "Refracted Solutions" ' C_TAG should be a string unique to this add-in.
Private Const C_TOOLS_MENU_ID As Long = 30007&

Private Sub Workbook_Open()
'''''''''''''''''''''''''''''''''''''''''''''''
' Workbook_Open
' Create a submenu on the Tools menu. The
' submenu has two controls on it.
'''''''''''''''''''''''''''''''''''''''''''''''
Dim ToolsMenu As Office.CommandBarControl
Dim ToolsMenuItem As Office.CommandBarControl
Dim ToolsMenuControl As Office.CommandBarControl

'''''''''''''''''''''''''''''''''''''''''''''''
' First delete any of our controls that
' may not have been properly deleted previously.
'''''''''''''''''''''''''''''''''''''''''''''''
DeleteControls

''''''''''''''''''''''''''''''''''''''''''''''
' Get a reference to the Tools menu.
''''''''''''''''''''''''''''''''''''''''''''''
Set ToolsMenu = Application.CommandBars.FindControl(ID:=C_TOOLS_MENU_ID)
If ToolsMenu Is Nothing Then
    MsgBox "Unable to access Tools menu.", vbOKOnly
    Exit Sub
End If

''''''''''''''''''''''''''''''''''''''''''''''
' Create a item on the Tools menu.
''''''''''''''''''''''''''''''''''''''''''''''
Set ToolsMenuItem = ToolsMenu.Controls.Add(Type:=msoControlPopup, temporary:=True)
If ToolsMenuItem Is Nothing Then
    MsgBox "Unable to add item to the Tools menu.", vbOKOnly
    Exit Sub
End If

With ToolsMenuItem
    .Caption = "&WWCares"
    .BeginGroup = True
    .Tag = C_TAG
End With

''''''''''''''''''''''''''''''''''''''''''''''
' Create the first control on the new item
' in the Tools menu.
''''''''''''''''''''''''''''''''''''''''''''''
Set ToolsMenuControl = ToolsMenuItem.Controls.Add(Type:=msoControlButton, temporary:=True)
If ToolsMenuControl Is Nothing Then
    MsgBox "Unable to add item to Tools menu item.", vbOKOnly
    Exit Sub
End If

With ToolsMenuControl
    ''''''''''''''''''''''''''''''''''''
    ' Set the display caption and the
    ' procedure to run when clicked.
    ''''''''''''''''''''''''''''''''''''
    .Caption = "State ANSII E&xport"
    .OnAction = "'" & ThisWorkbook.Name & "'!StateANSIIExport"
    .Tag = C_TAG
End With

''''''''''''''''''''''''''''''''''''''''''''''
' Create the second control on the new item
' in the Tools menu.
''''''''''''''''''''''''''''''''''''''''''''''
'Set ToolsMenuControl = ToolsMenuItem.Controls.Add(Type:=msoControlButton, temporary:=True)
'If ToolsMenuControl Is Nothing Then
'    MsgBox "Unable to add item to Tools menu item.", vbOKOnly
'    Exit Sub
'End If

'With ToolsMenuControl
    ''''''''''''''''''''''''''''''''''''
    ' Set the display caption and the
    ' procedure to run when clicked.
    ''''''''''''''''''''''''''''''''''''
'    .Caption = "Click Me &Two"
'    .OnAction = "'" & ThisWorkbook.Name & "'!MacroToRunTwo"
'    .Tag = C_TAG
'End With

End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
''''''''''''''''''''''''''''''''''''''''''''''''''''
' Workbook_BeforeClose
' Before closing the add-in, clean up our controls.
''''''''''''''''''''''''''''''''''''''''''''''''''''
    DeleteControls
End Sub

Private Sub DeleteControls()
''''''''''''''''''''''''''''''''''''
' Delete controls whose Tag is
' equal to C_TAG.
''''''''''''''''''''''''''''''''''''
Dim Ctrl As Office.CommandBarControl

On Error Resume Next
Set Ctrl = Application.CommandBars.FindControl(Tag:=C_TAG)

Do Until Ctrl Is Nothing
    Ctrl.Delete
    Set Ctrl = Application.CommandBars.FindControl(Tag:=C_TAG)
Loop

End Sub


来源: stackexchange

问:
Learning DirectX10 with GeForce7
So I am planning to start learning DirectX by grabbing Frank Luna's book "Introduction to 3D Game Programming with DirectX 10". But since I have a GeForce Go 7 graphics card, I am wondering will I be able to at least test the code from the book? Or should I take his older book about DirectX 9, which my GPU supports? But speaking about that, it would be a little pity to learn outdated stuff since I read that DX10 has introduced quite a lot of new concept, so I am totally confused at the moment.

On the other hand, perhaps with the hardware I have I would be more happier learning older version of OpenGL?

答:
If you don't have the money to get updated hardware, get the book to match the hardware you have.

Most of what you will need to learn transfers from one to version to the other - if you get proficient with one version, you can move to another and keep most of your knowledge - because most of what you need for graphics programming isn't the API.

You just need to get started and get some code running as quick as possible!

ContentLicense: CC BY-SA 2.5

Title: Learning DirectX10 with GeForce7


问:
SQL Server rank query optimization
I'm trying to optimize a query to get the rank of a user in specific country from the DB. Currently is seems very inefficient.

I'm trying to determine what can be done to improve it.

This is the current SQL:

```<code>SELECT COUNT(*) + 1
FROM leaderboard lb, users u
WHERE u.country = 'United States'
  AND lb.id = u.id
  AND lb.score + 1 > (SELECT lb2.score
                      FROM leaderboard lb2
                      WHERE lb2.id = some_user_id);
</code>```

Details:

Users table:

id is the primary key

country column is indexed

Leadeboard table:

id is the primary key

score column is indexed

The execution plan shows 2 warnings:

Columns With No Statistics: [dbo].[leaderboard].id (cost 23%)

Columns With No Statistics: [dbo].[users].id (cost 28%)

答:
I think you are looking for something like:

```<code>SELECT u.id AS user_id, u.country, lu.score, RANK() OVER (ORDER BY lu.score DESC) AS rnk
FROM users u
INNER JOIN leaderboard lu ON u.id = lu.id
WHERE u.country = 'United States'
</code>```

You can see a demo here: http://rextester.com/KHM76159

ContentLicense: CC BY-SA 3.0

Title: SQL Server rank query optimization

Body:
I'm trying to optimize a query to get the rank of a user in specific country from the DB. Currently is seems very inefficient.

I'm trying to determine what can be done to improve it.

This is the current SQL:

SELECT COUNT(*) + 1
FROM leaderboard lb, users u
WHERE u.country = 'United States'
  AND lb.id = u.id
  AND lb.score + 1 > (SELECT lb2.score
                      FROM leaderboard lb2
                      WHERE lb2.id = some_user_id);

Details:

Users table:

id is the primary key

country column is indexed

Leadeboard table:

id is the primary key

score column is indexed

The execution plan shows 2 warnings:

Columns With No Statistics: [dbo].[leaderboard].id (cost 23%)

Columns With No Statistics: [dbo].[users].id (cost 28%)

Body:
I think you are looking for something like:

SELECT u.id AS user_id, u.country, lu.score, RANK() OVER (ORDER BY lu.score DESC) AS rnk
FROM users u
INNER JOIN leaderboard lu ON u.id = lu.id
WHERE u.country = 'United States'

You can see a demo here: http://rextester.com/KHM76159


问:
Simple SQL Server Delete fails
I am seeing intermittent failures upon a simple delete.

Essentially I have a temporary note that has many entries. Each entry has a classification which is a lookup value. Once this note is completed, it gets sent to a note repository, and the temporary version needs to be deleted.

I can't replicate reliably, but on occasion, when calling the stored procedure that does the delete of the temp note, only SOME of the entries get deleted. Coincidentally (?) the entry left behind has always been of one specific classification type.

After many many many attempts I was able to reproduce the issue while running SQL Server Profiler. Despite trying to catch Attention, ErrorLog, EventLog, Exception, and Execution Warnings, the resulting profile shows nothing out of the ordinary.

None of the involved tables are large. In fact they're minuscule. ~100-1000 at any given time in Entry, ~100 in Draft, 9 in Classification, 3 in Category.

I don't believe it should matter, but just in case, this stored procedure is being called from Entity Framework.

Any ideas? Any ideas on what to try for troubleshooting? I'm completely at a loss. Thanks in advance for any help.

Here is the stored procedure for deletion:

```<code>CREATE PROCEDURE [NoteDraft].[ClearNoteDraft]
    @DraftId BIGINT
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM NoteDraft.[Entry]
    WHERE DraftId = @DraftId

    DELETE FROM NoteDraft.Draft
    WHERE Id = @DraftId
END
</code>```

Here are the table definitions (with some columns left out for brevity as noted.)

```<code>CREATE TABLE [NoteDraft].[Category]
(
   [Id] [int] IDENTITY(1,1) NOT NULL,
   [Name] [varchar](50) NOT NULL,
   [SortOrder] [int] NULL,

   CONSTRAINT [PK_Category]
       PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]

CREATE TABLE [NoteDraft].[Classification]
(
   [Id] [int] IDENTITY(1,1) NOT NULL,
   [CategoryId] [int] NOT NULL,
   [Name] [varchar](50) NOT NULL,
   [SortOrder] [int] NULL,

   CONSTRAINT [PK_Classification]
       PRIMARY KEY CLUSTERED ([Id] ASC)
)

CREATE TABLE [NoteDraft].[Draft]
(
   [Id] [bigint] IDENTITY(1,1) NOT NULL,
   [DateModified] [datetime] NOT NULL CONSTRAINT [DF_TestNoteDraft_DateModified]  DEFAULT (getdate()),
   [AccountNumber] [varchar](30) NULL,
   --...10 other biz columns...
   CONSTRAINT [PK_Notes]
       PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]

CREATE TABLE [NoteDraft].[Entry]
(
   [DraftId] [bigint] NOT NULL,
   [ClassificationId] [int] NOT NULL,
   [Body] [varchar](2100) NULL,
   CONSTRAINT [PK_Entry]
       PRIMARY KEY CLUSTERED ([DraftId] ASC, [ClassificationId] ASC)
) ON [PRIMARY]

ALTER TABLE [NoteDraft].[Classification] WITH CHECK
     ADD CONSTRAINT [FK_Classification_Category]
         FOREIGN KEY([CategoryId]) REFERENCES [NoteDraft].[Category] ([Id])
GO

ALTER TABLE [NoteDraft].[Classification] CHECK CONSTRAINT [FK_Classification_Category]
GO

ALTER TABLE [NoteDraft].[Entry]  WITH CHECK
     ADD CONSTRAINT [FK_Entry_Classification]
         FOREIGN KEY([ClassificationId]) REFERENCES [NoteDraft].[Classification] ([Id])
GO

ALTER TABLE [NoteDraft].[Entry] CHECK CONSTRAINT [FK_Entry_Classification]
GO

ALTER TABLE [NoteDraft].[Entry]  WITH CHECK
     ADD CONSTRAINT [FK_Entry_Draft]
         FOREIGN KEY([DraftId]) REFERENCES [NoteDraft].[Draft] ([Id])
GO

ALTER TABLE [NoteDraft].[Entry] CHECK CONSTRAINT [FK_Entry_Draft]
GO
</code>```

答:
As with everything simple like this, the answer wasn't where I was looking.

Turns out, there's an event listener on the page that's re-inserting the records post deletion.

Still having trouble figuring out why the listener is running, but at least I know what's going on.

Title: Simple SQL Server Delete fails

Body:
I am seeing intermittent failures upon a simple delete.

Essentially I have a temporary note that has many entries. Each entry has a classification which is a lookup value. Once this note is completed, it gets sent to a note repository, and the temporary version needs to be deleted.

I can't replicate reliably, but on occasion, when calling the stored procedure that does the delete of the temp note, only SOME of the entries get deleted. Coincidentally (?) the entry left behind has always been of one specific classification type.

After many many many attempts I was able to reproduce the issue while running SQL Server Profiler. Despite trying to catch Attention, ErrorLog, EventLog, Exception, and Execution Warnings, the resulting profile shows nothing out of the ordinary.

None of the involved tables are large. In fact they're minuscule. ~100-1000 at any given time in Entry, ~100 in Draft, 9 in Classification, 3 in Category.

I don't believe it should matter, but just in case, this stored procedure is being called from Entity Framework.

Any ideas? Any ideas on what to try for troubleshooting? I'm completely at a loss. Thanks in advance for any help.

Here is the stored procedure for deletion:

CREATE PROCEDURE [NoteDraft].[ClearNoteDraft]
    @DraftId BIGINT
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM NoteDraft.[Entry]
    WHERE DraftId = @DraftId

    DELETE FROM NoteDraft.Draft
    WHERE Id = @DraftId
END

Here are the table definitions (with some columns left out for brevity as noted.)

CREATE TABLE [NoteDraft].[Category]
(
   [Id] [int] IDENTITY(1,1) NOT NULL,
   [Name] [varchar](50) NOT NULL,
   [SortOrder] [int] NULL,

   CONSTRAINT [PK_Category]
       PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]

CREATE TABLE [NoteDraft].[Classification]
(
   [Id] [int] IDENTITY(1,1) NOT NULL,
   [CategoryId] [int] NOT NULL,
   [Name] [varchar](50) NOT NULL,
   [SortOrder] [int] NULL,

   CONSTRAINT [PK_Classification]
       PRIMARY KEY CLUSTERED ([Id] ASC)
)

CREATE TABLE [NoteDraft].[Draft]
(
   [Id] [bigint] IDENTITY(1,1) NOT NULL,
   [DateModified] [datetime] NOT NULL CONSTRAINT [DF_TestNoteDraft_DateModified]  DEFAULT (getdate()),
   [AccountNumber] [varchar](30) NULL,
   --...10 other biz columns...
   CONSTRAINT [PK_Notes]
       PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]

CREATE TABLE [NoteDraft].[Entry]
(
   [DraftId] [bigint] NOT NULL,
   [ClassificationId] [int] NOT NULL,
   [Body] [varchar](2100) NULL,
   CONSTRAINT [PK_Entry]
       PRIMARY KEY CLUSTERED ([DraftId] ASC, [ClassificationId] ASC)
) ON [PRIMARY]

ALTER TABLE [NoteDraft].[Classification] WITH CHECK
     ADD CONSTRAINT [FK_Classification_Category]
         FOREIGN KEY([CategoryId]) REFERENCES [NoteDraft].[Category] ([Id])
GO

ALTER TABLE [NoteDraft].[Classification] CHECK CONSTRAINT [FK_Classification_Category]
GO

ALTER TABLE [NoteDraft].[Entry]  WITH CHECK
     ADD CONSTRAINT [FK_Entry_Classification]
         FOREIGN KEY([ClassificationId]) REFERENCES [NoteDraft].[Classification] ([Id])
GO

ALTER TABLE [NoteDraft].[Entry] CHECK CONSTRAINT [FK_Entry_Classification]
GO

ALTER TABLE [NoteDraft].[Entry]  WITH CHECK
     ADD CONSTRAINT [FK_Entry_Draft]
         FOREIGN KEY([DraftId]) REFERENCES [NoteDraft].[Draft] ([Id])
GO

ALTER TABLE [NoteDraft].[Entry] CHECK CONSTRAINT [FK_Entry_Draft]
GO


问:
simple hard coded ajax return value always undefined
I have an Ajax call and a PHP function. Firefox shows an HTTP 200 status. I can see the value "false" in the response, but it does not get passed to the success part of the Ajax handler; I always get undefined.

I have done a lot of Ajax before and many similar ones in my project and never had this issue. It is normal that the parameter is blank and should not affect anything.

I tried Async, print, return and even converting to JSON but not luck. No errors are showing up anywhere.

JavaScript:

```<code>function Init() {
    $.ajax({
        url: "php/file.php",
        type: "post",
        data: {
            action: "userInit",
            parameter: "",
            success: function(result) {
                alert(result);
            },
        },
    });
};
</code>```

PHP:

```<code>function userInit() {
  echo('FALSE');
};
</code>```

firefox report #1

firefox report #2

答:
```<code>function Init() {
    $.ajax({
    url:"php/file.php",
    type: "post",
    data: {
        parameter: "123"
    },
    success: function (result) {    // Success is a callback function, it is part of your data object in the code which is wrong.
        alert(result);
    },
    });
};
</code>```

Body:
I have an Ajax call and a PHP function. Firefox shows an HTTP 200 status. I can see the value "false" in the response, but it does not get passed to the success part of the Ajax handler; I always get undefined.

I have done a lot of Ajax before and many similar ones in my project and never had this issue. It is normal that the parameter is blank and should not affect anything.

I tried Async, print, return and even converting to JSON but not luck. No errors are showing up anywhere.

JavaScript:

function Init() {
    $.ajax({
        url: "php/file.php",
        type: "post",
        data: {
            action: "userInit",
            parameter: "",
            success: function(result) {
                alert(result);
            },
        },
    });
};

PHP:

function userInit() {
  echo('FALSE');
};

firefox report #1

firefox report #2


问:
Regex - Words with 2 different letters repeated twice followed by a number repeated 6 times
I need to regex that matches a string like LLMM222222. I tried with pattern like (\w{2})(\w{2})2{6} but it does not work

答:
You can use this regex with 2 back-references:

```<code>^([A-Za-z])\1([A-Za-z])\2(\d)\3{5}$
</code>```

RegEx Demo

RegEx Breakup:

^: Start

([A-Za-z]): Match a letter and capture it in group #1

\1: Make sure we repeat same letter using a back-reference #1

([A-Za-z]): Match a letter and capture it in group #2

\1: Make sure we repeat same letter using a back-reference #2

\d: Match and capture a digit in capture group #3

\3{5}: Make sure we repeat same digit 5 more times using a back-reference #3

$: End

Body:
You can use this regex with 2 back-references:

^([A-Za-z])\1([A-Za-z])\2(\d)\3{5}$

RegEx Demo

RegEx Breakup:

^: Start

([A-Za-z]): Match a letter and capture it in group #1

\1: Make sure we repeat same letter using a back-reference #1

([A-Za-z]): Match a letter and capture it in group #2

\1: Make sure we repeat same letter using a back-reference #2

\d: Match and capture a digit in capture group #3

\3{5}: Make sure we repeat same digit 5 more times using a back-reference #3

$: End


问:
Changed the URL and ROOT. Main Page won't load. Wordpress
I am trying to redesign a website from a friend and it's chaotic as hell. Now I am stuck a bit.

The old domain it something like http://www.website.com/folder/
I am trying the get rid out of the "folder", so I changed the setting in the wordpress setting and the root in the web-provider. The whole website is working fine, also the Wordpress admin area. But if I'm trying to get into the "home" page, it won't load - or it is loading endlessly.

Do you have any idea how I could fix it?

Regards and thanks,
Natts

答:
A piece often forgotten is the .htaccess file (found in the root of your WP install); I especially suspect it because you're going from a subfolder to no subfolder.

Back it up, then override it with the default WordPress values (or delete it and go to Settings -> Permalinks in WP Admin)

Default .htaccess:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

Body:
A piece often forgotten is the .htaccess file (found in the root of your WP install); I especially suspect it because you're going from a subfolder to no subfolder.

Back it up, then override it with the default WordPress values (or delete it and go to Settings -> Permalinks in WP Admin)

Default .htaccess:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress


问:
Don't have access to Spring boot controller, but have access to index.html
I have a Spring Boot project, what I deployed on remote server. When I call http://109.206.178.66:8080/proxynator/ - I can see an index.html, but when I call rest controller by url http://109.206.178.66:8080/proxynator/countries - I have an error 404 whith

Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

It's strangely, because when I start this project on my local machine, all working right. Project structure is:

Line from catalina.out file:

SEVERE [http-nio-8080-exec-19] org.apache.tomcat.util.descriptor.web.WebXmlParser.parseWebXml Parse error in application web.xml file at [file:/opt/tomcat/webapps/proxynator/WEB-INF/web.

My controller:

```<code>@RestController
class MainController(val proxyRepo: ProxyRepo, val countryRepo:
CountryRepo) {

@GetMapping("/countries")
fun findCountries(): List<Country> = countryRepo.findAll()

@GetMapping("/proxies")
@ResponseBody
fun findProxies(@RequestParam countryid: Int): List<Proxy> =
proxyRepo.findAllByCountryid(countryid)
}
</code>```

UPD

I added configuration class on the root package

```<code>@Configuration
open class RestConfiguration {
    @Bean
    open fun mainController():MainController
            = MainController()
}
</code>```

But it does not working. I don't understand, why I can see index.html by irl http://109.206.178.66:8080/proxynator/, but can't get access to my controllers. When I package my project I have some files:

Any advice?

答: your api access url is wrong  access using http://109.206.178.66:8080/countries this is the correct path for your rest mapping,  not http://109.206.178.66:8080/proxynator/countries</p>

Body:
I have a Spring Boot project, what I deployed on remote server. When I call http://109.206.178.66:8080/proxynator/ - I can see an index.html, but when I call rest controller by url http://109.206.178.66:8080/proxynator/countries - I have an error 404 whith

Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

It's strangely, because when I start this project on my local machine, all working right. Project structure is:

Line from catalina.out file:

SEVERE [http-nio-8080-exec-19] org.apache.tomcat.util.descriptor.web.WebXmlParser.parseWebXml Parse error in application web.xml file at [file:/opt/tomcat/webapps/proxynator/WEB-INF/web.

My controller:

@RestController
class MainController(val proxyRepo: ProxyRepo, val countryRepo:
CountryRepo) {

@GetMapping("/countries")
fun findCountries(): List<Country> = countryRepo.findAll()

@GetMapping("/proxies")
@ResponseBody
fun findProxies(@RequestParam countryid: Int): List<Proxy> =
proxyRepo.findAllByCountryid(countryid)
}

UPD

I added configuration class on the root package

@Configuration
open class RestConfiguration {
    @Bean
    open fun mainController():MainController
            = MainController()
}

But it does not working. I don't understand, why I can see index.html by irl http://109.206.178.66:8080/proxynator/, but can't get access to my controllers. When I package my project I have some files:

Any advice?


问:
How to put some array elements from the middle to last in Javascript
I have this following JS object array whose elements are just columns of a HTML table :

```<code>var my_cols = [
  {
    "id": "name",
    "header": [
      "Name",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "type",
    "header": [
      "Type",
      {
        "content": "textFilter"
      }
    ],
    "width": 180,
    "sort": "string"
  },
  {
    "id": "dob",
    "header": [
      "DOB",
      {
        "content": "textFilter"
      }
    ],
    "width": 100,
    "sort": "string"
  },
  {
    "id": "merged_a",
    "header": [
      {
        "text": "merged_a",
        "colspan": 3
      },
      {
        "text": "port"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_b",
    "header": [
      null,
      {
        "text": "merged_b"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_c",
    "header": [
      null,
      {
        "text": "merged_c"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "place",
    "header": [
      "place",
      {
        "content": "textFilter"
      }
    ],
    "width": 300,
    "sort": "string"
  },
  {
    "id": "address",
    "header": [
      "address",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "phone",
    "header": [
      "phone",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  }
];
</code>```

I want to put elements with id as 'merged_a' , 'merged_b', and 'merged_c' at the end of the entire array my_cols. I have written the below code so far, however it is not giving me the exact result:

```<code>var my_cols= [{"id":"name","header":["Name",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"type","header":["Type",{"content":"textFilter"}],"width":180,"sort":"string"},
{"id":"dob","header":["DOB",{"content":"textFilter"}],"width":100,"sort":"string"},
{"id":"merged_a","header":[{"text":"merged_a","colspan":3},{"text":"port"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_b","header":[null,{"text":"merged_b"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_c","header":[null,{"text":"merged_c"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"place","header":["place",{"content":"textFilter"}],"width":300,"sort":"string"},
{"id":"address","header":["address",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"phone","header":["phone",{"content":"textFilter"}],"width":200,"sort":"string"}];
</code>```

My effort

 var my_cols = [
   { "id": "name", "header": [ "Name", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "type", "header": [ "Type", { "content": "textFilter" } ], "width": 180, "sort": "string" },
   { "id": "dob", "header": [ "DOB", { "content": "textFilter" } ], "width": 100, "sort": "string" },
   { "id": "merged_a", "header": [{ "text": "merged_a", "colspan": 3 }, { "text": "port" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_b", "header": [ null, { "text": "merged_b" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_c", "header": [ null, { "text": "merged_c" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "place", "header": [ "place", { "content": "textFilter" } ], "width": 300, "sort": "string" },
   { "id": "address", "header": [ "address", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "phone", "header": [ "phone", { "content": "textFilter" } ], "width": 200, "sort": "string" }
 ];

for (var i in my_cols) {

  var col = my_cols[i];
  var a_col;
  var b_col;
  var c_col;
  if (col.hasOwnProperty('id')) {
    if (col['id'] == 'merged_a') {
      a_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_b') {
      b_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_c') {
      c_col = my_cols.splice(i, 1);
    }
  }

}

my_cols.push(a_col);
my_cols.push(b_col);
my_cols.push(c_col);

console.log("my_cols = " + JSON.stringify(my_cols));```

答:
You can use array#filter twice and forEach method to get the result.At first get

var my_cols = [{
    "id": "name",
    "header": ["Name", {
      "content": "textFilter"
    }],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "type",
    "header": ["Type", {
      "content": "textFilter"
    }],
    "width": 180,
    "sort": "string"
  },
  {
    "id": "dob",
    "header": ["DOB", {
      "content": "textFilter"
    }],
    "width": 100,
    "sort": "string"
  },
  {
    "id": "merged_a",
    "header": [{
      "text": "merged_a",
      "colspan": 3
    }, {
      "text": "port"
    }, {
      "content": "textFilter"
    }],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_b",
    "header": [null, {
      "text": "merged_b"
    }, {
      "content": "textFilter"
    }],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_c",
    "header": [null, {
      "text": "merged_c"
    }, {
      "content": "textFilter"
    }],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "place",
    "header": ["place", {
      "content": "textFilter"
    }],
    "width": 300,
    "sort": "string"
  },
  {
    "id": "address",
    "header": ["address", {
      "content": "textFilter"
    }],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "phone",
    "header": ["phone", {
      "content": "textFilter"
    }],
    "width": 200,
    "sort": "string"
  }
];
// will return a new array without objects having id as merged_a,merged_b,merged_c
var withOutMergedId = my_cols.filter(function(a) {
    return "merged_a" !== a.id && "merged_b" !== a.id && "merged_c" !== a.id;
  }),
// // will return a new array with objects having only id as merged_a,merged_b,merged_c
  withMergedId = my_cols.filter(function(a) {
    return "merged_a" === a.id || "merged_b" === a.id || "merged_c" === a.id;
  });
  // using forEach to push the elements
withMergedId.forEach(function(a) {
  withOutMergedId.push(a);
});
console.log(withOutMergedId)```

Body:
I have this following JS object array whose elements are just columns of a HTML table :

var my_cols = [
  {
    "id": "name",
    "header": [
      "Name",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "type",
    "header": [
      "Type",
      {
        "content": "textFilter"
      }
    ],
    "width": 180,
    "sort": "string"
  },
  {
    "id": "dob",
    "header": [
      "DOB",
      {
        "content": "textFilter"
      }
    ],
    "width": 100,
    "sort": "string"
  },
  {
    "id": "merged_a",
    "header": [
      {
        "text": "merged_a",
        "colspan": 3
      },
      {
        "text": "port"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_b",
    "header": [
      null,
      {
        "text": "merged_b"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "merged_c",
    "header": [
      null,
      {
        "text": "merged_c"
      },
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "place",
    "header": [
      "place",
      {
        "content": "textFilter"
      }
    ],
    "width": 300,
    "sort": "string"
  },
  {
    "id": "address",
    "header": [
      "address",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  },
  {
    "id": "phone",
    "header": [
      "phone",
      {
        "content": "textFilter"
      }
    ],
    "width": 200,
    "sort": "string"
  }
];

I want to put elements with id as 'merged_a' , 'merged_b', and 'merged_c' at the end of the entire array my_cols. I have written the below code so far, however it is not giving me the exact result:

var my_cols= [{"id":"name","header":["Name",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"type","header":["Type",{"content":"textFilter"}],"width":180,"sort":"string"},
{"id":"dob","header":["DOB",{"content":"textFilter"}],"width":100,"sort":"string"},
{"id":"merged_a","header":[{"text":"merged_a","colspan":3},{"text":"port"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_b","header":[null,{"text":"merged_b"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"merged_c","header":[null,{"text":"merged_c"},{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"place","header":["place",{"content":"textFilter"}],"width":300,"sort":"string"},
{"id":"address","header":["address",{"content":"textFilter"}],"width":200,"sort":"string"},
{"id":"phone","header":["phone",{"content":"textFilter"}],"width":200,"sort":"string"}];

My effort

 var my_cols = [
   { "id": "name", "header": [ "Name", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "type", "header": [ "Type", { "content": "textFilter" } ], "width": 180, "sort": "string" },
   { "id": "dob", "header": [ "DOB", { "content": "textFilter" } ], "width": 100, "sort": "string" },
   { "id": "merged_a", "header": [{ "text": "merged_a", "colspan": 3 }, { "text": "port" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_b", "header": [ null, { "text": "merged_b" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "merged_c", "header": [ null, { "text": "merged_c" }, { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "place", "header": [ "place", { "content": "textFilter" } ], "width": 300, "sort": "string" },
   { "id": "address", "header": [ "address", { "content": "textFilter" } ], "width": 200, "sort": "string" },
   { "id": "phone", "header": [ "phone", { "content": "textFilter" } ], "width": 200, "sort": "string" }
 ];

for (var i in my_cols) {

  var col = my_cols[i];
  var a_col;
  var b_col;
  var c_col;
  if (col.hasOwnProperty('id')) {
    if (col['id'] == 'merged_a') {
      a_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_b') {
      b_col = my_cols.splice(i, 1);
    }
    if (col['id'] == 'merged_c') {
      c_col = my_cols.splice(i, 1);
    }
  }

}

my_cols.push(a_col);
my_cols.push(b_col);
my_cols.push(c_col);

console.log("my_cols = " + JSON.stringify(my_cols));


问:
Styling html progress bar as health bar with value simple Css
I am trying to style a HTML progress bar as a health bar.

I am trying to make it look like this with health value

I tried this but not working

.progressplayer[value]::-webkit-progress-bar {
  background-color: #eee;
}

.progressplayer[value]::-webkit-progress-value {
  background-color: #FF0000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><progress class="progressplayer" id="playerhealth" value="100" max="100"></progress></code>```

Comment to christians answer:

```<code><div class="progress-container">
  <progress id="playerhealth" *ngIf="state==1"   id="playerhealth" value="100" max="100"></progress>
  <p class="progress-label">
    {{playerhp}}
  </p>
  <progress id="enemyhealth" *ngIf="state==1"   id="enemyhealth" value="100" max="100"></progress>
  <p class="progress-label">
    {{mhp}}
  </p>
</div>
</code>```

with this i cant display second progress label.

答:
You need to reset the progress default appearance

```<code>progress[value] {
  /* Reset the default appearance */
  -webkit-appearance: none;
  appearance: none;
}
</code>```

See CSS-Tricks Article

.progressplayer[value]::-webkit-progress-bar {
  background-color: green;
}

.progressplayer[value]::-webkit-progress-value {
  background-color: #FF0000;
}

progress[value] {
  /* Reset the default appearance */
  -webkit-appearance: none;
  appearance: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><progress class="progressplayer" id="playerhealth" value="80" max="100"></progress></code>```

Body:
I am trying to style a HTML progress bar as a health bar.

I am trying to make it look like this with health value

I tried this but not working

.progressplayer[value]::-webkit-progress-bar {
  background-color: #eee;
}

.progressplayer[value]::-webkit-progress-value {
  background-color: #FF0000;
}

<progress class="progressplayer" id="playerhealth" value="100" max="100"></progress>

Comment to christians answer:

  <progress id="playerhealth" *ngIf="state==1"   id="playerhealth" value="100" max="100"></progress>

    {{playerhp}}

  <progress id="enemyhealth" *ngIf="state==1"   id="enemyhealth" value="100" max="100"></progress>

    {{mhp}}

with this i cant display second progress label.

Body:
You need to reset the progress default appearance

progress[value] {
  /* Reset the default appearance */
  -webkit-appearance: none;
  appearance: none;
}

See CSS-Tricks Article

.progressplayer[value]::-webkit-progress-bar {
  background-color: green;
}

.progressplayer[value]::-webkit-progress-value {
  background-color: #FF0000;
}

progress[value] {
  /* Reset the default appearance */
  -webkit-appearance: none;
  appearance: none;
}

<progress class="progressplayer" id="playerhealth" value="80" max="100"></progress>


问:
How to sum column values from two tables and preserve another column which is only in one table
i have created tables item and item2, I know maybe it's data redundancy but i want to know how can select it, and create a view?

```<code>create table item(
id  number(10) primary key,
name varchar2(20),
mark number(10));
insert into item values(10,'Apple1',23);
insert into item values(11,'Apple2',0);
insert into item values(12,'Apple3',0);
insert into item values(13,'Apple4',0);
insert into item values(14,'Apple4',0);
insert into item values(15,'Apple4',0);
insert into item values(16,'Apple4',0);

create table  item2(
id number(10),
mark number(10));
alter table item2 add(constraint id_fk FOREIGN KEY (id) references  item(id));
Insert into  item2 values(10,1);
Insert into  item2 values(10,1);
Insert into  item2 values(11,7);
Insert into  item2 values(12,14);
</code>```

I can query both:

```<code>select * from item;

ID  Name    Mark
10  Apple1    23
11  Apple2     0
12  Apple3     0
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

select * from item2;

ID  Mark
10     1
10     1
11     7
12    14
</code>```

I want to get the result set below using the select statement sum from the item and item2 tables:

```<code>ID  Name    Mark
10  Apple1    25
11  Apple2     7
12  Apple3    14
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0
</code>```

How can I combine my queries to produce that output?

答:
If I understand this correctly, you want to "pretend" that the second table had the NAME column also, populated according to the first table; then you would want to GROUP BY id and get the sum of MARK.

If so, instead of joining the tables to get the names (either before or after combining the tables and computing the sums), you can use a UNION ALL, in which you insert a fake NAME column with NULL in it for the second table; then you group by id, you sum the MARK column, and you take the MAX over NAME. MAX ignores NULL, so it will just pick the name from table ITEM.

The solution below follows that logic in every detail.

```<code>select   id, max(name) as name, sum(mark) as mark
from     ( select id, name, mark
             from item
           union all
           select id, null as name, mark
             from item2
         )
group by id
;
</code>```

Body:
i have created tables item and item2, I know maybe it's data redundancy but i want to know how can select it, and create a view?

create table item(
id  number(10) primary key,
name varchar2(20),
mark number(10));
insert into item values(10,'Apple1',23);
insert into item values(11,'Apple2',0);
insert into item values(12,'Apple3',0);
insert into item values(13,'Apple4',0);
insert into item values(14,'Apple4',0);
insert into item values(15,'Apple4',0);
insert into item values(16,'Apple4',0);

create table  item2(
id number(10),
mark number(10));
alter table item2 add(constraint id_fk FOREIGN KEY (id) references  item(id));
Insert into  item2 values(10,1);
Insert into  item2 values(10,1);
Insert into  item2 values(11,7);
Insert into  item2 values(12,14);

I can query both:

select * from item;

ID  Name    Mark
10  Apple1    23
11  Apple2     0
12  Apple3     0
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

select * from item2;

ID  Mark
10     1
10     1
11     7
12    14

I want to get the result set below using the select statement sum from the item and item2 tables:

ID  Name    Mark
10  Apple1    25
11  Apple2     7
12  Apple3    14
13  Apple4     0
14  Apple4     0
15  Apple4     0
16  Apple4     0

How can I combine my queries to produce that output?

Body:
If I understand this correctly, you want to "pretend" that the second table had the NAME column also, populated according to the first table; then you would want to GROUP BY id and get the sum of MARK.

If so, instead of joining the tables to get the names (either before or after combining the tables and computing the sums), you can use a UNION ALL, in which you insert a fake NAME column with NULL in it for the second table; then you group by id, you sum the MARK column, and you take the MAX over NAME. MAX ignores NULL, so it will just pick the name from table ITEM.

The solution below follows that logic in every detail.

select   id, max(name) as name, sum(mark) as mark
from     ( select id, name, mark
             from item
           union all
           select id, null as name, mark
             from item2
         )
group by id
;


问:
VueJS slot in v-for
I want to make a grid component which accepts as slot additional column cell.

```<code><grid>
  <td slot="additional-column">...</td>
</grid>
</code>```

In the actual component:

```<code><template>
   <table>
     <div v-for="item in items">
       ...
       <slot name="additional-column"></slot>
     </div>
   </table>
</template>
</code>```

Unfortunately the slot starts repeating itself and this is something vuejs doesn't like.

Duplicate presence of slot "additional-column" found in the same render tree - this will likely cause render errors.

Does anybody know how can I deal with this issue?

Thanks in advance!

答:
Make the item a nested component (which you'll be repeating using v-for) and render the additional-column slot in that particular component.

That's the proper way to overcome this issue. The idea is that you need to have one single slot with a particular name per component.

That is, you could do it that way, which is a very rough version of it but nicely outlines the idea:

```<code><!-- Grid Template -->
<template>
  <table>
    <GridItem :item="item" v-for="item in items">
      <!-- Maybe even pass that column conditionally, based on the item data -->
      <div slot="additional-column">
        Content of column
      </div>
    </GridItem>
  </table>
</template>

<!-- GridItem Template -->
<template>
  <div>
    <div>Column 1</div>
    <div>Column 2</div>
    <slot name="additional-column" />
  </div>
</template>
</code>```

Title: VueJS slot in v-for

Body:
I want to make a grid component which accepts as slot additional column cell.

<grid>
  ...
</grid>

In the actual component:

<template>

       ...
       <slot name="additional-column"></slot>

</template>

Unfortunately the slot starts repeating itself and this is something vuejs doesn't like.

Duplicate presence of slot "additional-column" found in the same render tree - this will likely cause render errors.

Does anybody know how can I deal with this issue?

Thanks in advance!

Body:
Make the item a nested component (which you'll be repeating using v-for) and render the additional-column slot in that particular component.

That's the proper way to overcome this issue. The idea is that you need to have one single slot with a particular name per component.

That is, you could do it that way, which is a very rough version of it but nicely outlines the idea:

<!-- Grid Template -->
<template>
  <table>
    <GridItem :item="item" v-for="item in items">
      <!-- Maybe even pass that column conditionally, based on the item data -->
      <div slot="additional-column">
        Content of column
      </div>
    </GridItem>
  </table>
</template>

<!-- GridItem Template -->
<template>
  <div>
    <div>Column 1</div>
    <div>Column 2</div>
    <slot name="additional-column" />
  </div>
</template>


问:
Ruby variables and pointers
I am practicing with different design patterns in Ruby and am trying to figure out the innards of Ruby. Right now I am practicing with Proxy patterns. If I have my main object:

```<code>class BankAccount
  attr_reader :balance

  def initialize(starting_balance = 0)
    @balance = starting_balance
  end

  def deposit(amount)
    @balance += amount
  end

  # other code
end
</code>```

And my Proxy object:

```<code>class BankAccountProxy

  def initialize(real_object)
    @real_object = real_object
  end

  def balance
    @real_object.balance
  end

  def deposit(amount)
    @real_object.deposit(amount)
  end

  # other code
end
</code>```

And I initialize the main and proxy object:

```<code>main = BankAccount.new(100)
proxy = BankAccountProxy.new(main)
</code>```

Does Ruby make a copy of the main object within the proxy object, and therefore take up memory OR does Ruby simply point to main object from the proxy, and therefore not take up additional space?

答: Yes, it's called "references". Ruby will not make a copy of main here. Or anywhere else. It's always references. If you need a copy, you do it yourself.

Title: Ruby variables and pointers

Body:
I am practicing with different design patterns in Ruby and am trying to figure out the innards of Ruby. Right now I am practicing with Proxy patterns. If I have my main object:

class BankAccount
  attr_reader :balance

  def initialize(starting_balance = 0)
    @balance = starting_balance
  end

  def deposit(amount)
    @balance += amount
  end

  # other code
end

And my Proxy object:

class BankAccountProxy

  def initialize(real_object)
    @real_object = real_object
  end

  def balance
    @real_object.balance
  end

  def deposit(amount)
    @real_object.deposit(amount)
  end

  # other code
end

And I initialize the main and proxy object:

main = BankAccount.new(100)
proxy = BankAccountProxy.new(main)

Does Ruby make a copy of the main object within the proxy object, and therefore take up memory OR does Ruby simply point to main object from the proxy, and therefore not take up additional space?


问:
How to generate the similar folding effect as Gmail in JavaScript
I assume Gmail used JavaScript to implement the folding effect for a particular email thread. The effect I am talking about is: after you choose a particular email thread by clicking on it, then you will see that only the latest email is shown, with all the previous emails in a folded state. Only when you click on the folding section, they will expand, but still only showing a snippet of them. Then you click on each individual section, you can read the full message. How can one do this? Many thanks.</p>

答:
Using jQuery is really simple to make that nice visual effect (if you know enough javascript and jQuery). The toggle function is the function that will do the effect.

The accordion control of jQuery UI is really similar to what gmail does for threads. The differences is that the accordion allows only one section open at once, and in gmail several mails can be open at once.

So I recommend you to use the code in below the accordion example which allows multiple sections open at once, and not the accordion control itself for that matter.

```<code>jQuery(document).ready(function(){
    $('.accordion .head').click(function() {
        $(this).next().toggle('slow');
        return false;
    }).next().hide();
});
</code>```

Body:
Using jQuery is really simple to make that nice visual effect (if you know enough javascript and jQuery). The toggle function is the function that will do the effect.

The accordion control of jQuery UI is really similar to what gmail does for threads. The differences is that the accordion allows only one section open at once, and in gmail several mails can be open at once.

So I recommend you to use the code in below the accordion example which allows multiple sections open at once, and not the accordion control itself for that matter.

jQuery(document).ready(function(){
    $('.accordion .head').click(function() {
        $(this).next().toggle('slow');
        return false;
    }).next().hide();
});


问:
Running gdb with a source file
I have a Linux executable file and I can run it on command line, but at first, I should use

```<code>source ./somefile
</code>```

If I don't source it, the executable crashed. I also, can run the file under dbg. But I need to source somefile in gdb also. I mean, I already make source ./somefile then run the gdb and run the executable in it, the executable crashed like without using source ./somefile.

By the way, somefile that I should source contains some EXPORT=bla bla definitions.

Executable is an embedded qt software, running on imx6 board. Sourcing somefile makes some definition about qt libraries. The crash message when I run the executable without sourcing somefile and when sourcing it and then run in gdb is exactly the same. So I think that after source somefile, if I run the executable in gdb, it seems gdb doesn't know libraries' path. May be a way to source a file for gdb.

答:
I guess you are asking how to set environment variables inside gdb.

You should use set environment, see builtin help:

```<code>(gdb) help set environment
Set environment variable value to give the program.
Arguments are VAR VALUE where VAR is variable name and VALUE is value.
VALUES of environment variables are uninterpreted strings.
This does not affect the program until the next "run" command.
(gdb)
</code>```

You will have to take VAR and VALUE from ./somefile. You can't simply source it in gdb prompt because it is shell script, not gdb script.

Title: Running gdb with a source file

Body:
I have a Linux executable file and I can run it on command line, but at first, I should use

source ./somefile

If I don't source it, the executable crashed. I also, can run the file under dbg. But I need to source somefile in gdb also. I mean, I already make source ./somefile then run the gdb and run the executable in it, the executable crashed like without using source ./somefile.

By the way, somefile that I should source contains some EXPORT=bla bla definitions.

Executable is an embedded qt software, running on imx6 board. Sourcing somefile makes some definition about qt libraries. The crash message when I run the executable without sourcing somefile and when sourcing it and then run in gdb is exactly the same. So I think that after source somefile, if I run the executable in gdb, it seems gdb doesn't know libraries' path. May be a way to source a file for gdb.

Body:
I guess you are asking how to set environment variables inside gdb.

You should use set environment, see builtin help:

(gdb) help set environment
Set environment variable value to give the program.
Arguments are VAR VALUE where VAR is variable name and VALUE is value.
VALUES of environment variables are uninterpreted strings.
This does not affect the program until the next "run" command.
(gdb)

You will have to take VAR and VALUE from ./somefile. You can't simply source it in gdb prompt because it is shell script, not gdb script.


问:
Eventhandler-function can't use other (helper)functions
Im trying to build an app with Cytoscape.js and Angular2+.
The Core part take place in a single service (cy.service).
I add all Eventlisteners in a single function and call it after the cy init.

eg:

```<code>initEventlisteners(){
  cy.on('tap', this.handler);
  cy.on(...);
  ...
}

handler(event: any){
 console.log('something');
}
</code>```

If I wrap console.log in a helper-function like that:

```<code>helper(){
 console.log('something');
)
</code>```

And use it in the handler-function

```<code>handler(event:any){
 this.helper();
}
</code>```

It calls: helper() is not a function.
Thats a big problem that a cant use other functions inside the handler.
Any ideas how to solve that problem ?

答:
That's because with binding like this cy.on('tap', this.handler); you are loosing scope of variable. You should use it in this way cy.on('tap', (event) => { this.handler(event) }); (if it's passing any event object) or cy.on('tap', this.handler.bind(this));.

The frist approach with () => { } is called arrow function, which preserve current scope of variables. It's a new feature of ES6 specification. However you don't have to be afraid, angular compiler will convert it to backward compatible to ES5.

The second approach .bind(this) just simply binding this method to current scope where it's was called.

Body:
Im trying to build an app with Cytoscape.js and Angular2+.
The Core part take place in a single service (cy.service).
I add all Eventlisteners in a single function and call it after the cy init.

eg:

initEventlisteners(){
  cy.on('tap', this.handler);
  cy.on(...);
  ...
}

handler(event: any){
 console.log('something');
}

If I wrap console.log in a helper-function like that:

helper(){
 console.log('something');
)

And use it in the handler-function

handler(event:any){
 this.helper();
}

It calls: helper() is not a function.
Thats a big problem that a cant use other functions inside the handler.
Any ideas how to solve that problem ?


问:
Connect a docker node running on a separate ec2 host to Jenkins
I have 2 aws ec2 instances.  One instance is running Jenkins, the other is running Docker. I am trying to connect the container running on the Docker host to Jenkins as a node.

To start the container on the Docker host I ran the following:

sudo dockerd -H tcp://127.0.0.1:2376 -H unix:///var/run/docker.sock

In the cloud settings (under jenkins/configure)

Docker Host URI:
    tcp://IP-ADDRESS-OF-EC2-DOCKER-HOST:2376

Docker Hostname or IP address: IP-ADDRESS-OF-EC2-DOCKER-HOST

Dockerfile:

```<code>FROM ubuntu:16.04
RUN apt-get update
RUN apt-get install openjdk-8-jdk -y
RUN mkdir -p /home/jenkins
EXPOSE 22
</code>```

ec2 Docker host security open incoming ports: 2375, 2376, 4243, 22

When I hit the "Test Connection" button, I get:

```<code>Connection refused: /IP-ADDRESS-OF-EC2-DOCKER-HOST:2376
java.net.ConnectException: Connection refused
Caused: io.netty.channel.AbstractChannel$AnnotatedConnectException:
Connection refused: /IP-ADDRESS-OF-EC2-DOCKER-HOST:2376
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at
sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:352)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:632)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
at java.lang.Thread.run(Thread.java:748)
</code>```

On another stackoverflow post, someone recommended hitting the "Apply" button first, but that doesn't work because I get an error popup stactrace stating a java.lang.NullPointerException.

答:
Try giving  IP-ADDRESS-OF-EC2-DOCKER-HOST instead  of 127.0.0.1 in below CMD

sudo dockerd -H tcp://127.0.0.1:2376 -H unix:///var/run/docker.sock

Test port is open from docker to Jenkins host using

telnet docker_host_ ip 2376

Body:
I have 2 aws ec2 instances.  One instance is running Jenkins, the other is running Docker. I am trying to connect the container running on the Docker host to Jenkins as a node.

To start the container on the Docker host I ran the following:

sudo dockerd -H tcp://127.0.0.1:2376 -H unix:///var/run/docker.sock

In the cloud settings (under jenkins/configure)

Docker Host URI:
    tcp://IP-ADDRESS-OF-EC2-DOCKER-HOST:2376

Docker Hostname or IP address: IP-ADDRESS-OF-EC2-DOCKER-HOST

Dockerfile:

FROM ubuntu:16.04
RUN apt-get update
RUN apt-get install openjdk-8-jdk -y
RUN mkdir -p /home/jenkins
EXPOSE 22

ec2 Docker host security open incoming ports: 2375, 2376, 4243, 22

When I hit the "Test Connection" button, I get:

Connection refused: /IP-ADDRESS-OF-EC2-DOCKER-HOST:2376
java.net.ConnectException: Connection refused
Caused: io.netty.channel.AbstractChannel$AnnotatedConnectException:
Connection refused: /IP-ADDRESS-OF-EC2-DOCKER-HOST:2376
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at
sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:352)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:632)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
at java.lang.Thread.run(Thread.java:748)

On another stackoverflow post, someone recommended hitting the "Apply" button first, but that doesn't work because I get an error popup stactrace stating a java.lang.NullPointerException.


问:
Java parallelStream not showing correct result
I was doing some performance evaluation of Java aggeragate operations to iterate over collections. I was doing an evaluation of performance stream and parallelStream. But I found that the output of parallelStream is wrong most of the times. For example in the following code i got wrong output from parallelStream more than 80% of the time:

```<code>    public class ParallelStreamPerformance {
    static int totaleven = 0;
    public static void main(String[] args) {
        List<Integer> randomList = new ArrayList<>();
        Random rnd = new Random();
        for(int i = 0 ;i < 1000;i++) {
            int r = rnd.nextInt(500000);
            randomList.add(r);
        }

        long s1 = System.currentTimeMillis();

        randomList.stream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e1 = System.currentTimeMillis();
        System.out.println(e1 - s1);

        totaleven = 0;
        long s2 = System.currentTimeMillis();

        randomList.parallelStream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e2 = System.currentTimeMillis();
        System.out.println(e2 - s2);
    }
    public static void count() {
        totaleven++;
    }
}
</code>```

My question is: Am I using parallelStream in a wrong way? Is there any way to ensure the correctness of parallelStream.
Thanks

答: I think your code having issue with count() method. As parallelStream will try to perform task concurrently. This method should be synchronized or you can make totaleven as Atomtic Integer. Hope it helps.

Body:
I was doing some performance evaluation of Java aggeragate operations to iterate over collections. I was doing an evaluation of performance stream and parallelStream. But I found that the output of parallelStream is wrong most of the times. For example in the following code i got wrong output from parallelStream more than 80% of the time:

    public class ParallelStreamPerformance {
    static int totaleven = 0;
    public static void main(String[] args) {
        List<Integer> randomList = new ArrayList<>();
        Random rnd = new Random();
        for(int i = 0 ;i < 1000;i++) {
            int r = rnd.nextInt(500000);
            randomList.add(r);
        }

        long s1 = System.currentTimeMillis();

        randomList.stream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e1 = System.currentTimeMillis();
        System.out.println(e1 - s1);

        totaleven = 0;
        long s2 = System.currentTimeMillis();

        randomList.parallelStream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e2 = System.currentTimeMillis();
        System.out.println(e2 - s2);
    }
    public static void count() {
        totaleven++;
    }
}

My question is: Am I using parallelStream in a wrong way? Is there any way to ensure the correctness of parallelStream.
Thanks


问:
Rails search association
I am creating a simple search form in my Rails app and right now it lets me search a Pdform attribute. A pdform belongs to a user so there is a user_id in the pdform model.

How can I search a users first_name and have it bring up all of the pdforms that belong to them?

This is how I have it setup.

Routes

```<code>get '/pdforms/history', to: 'pdforms#history'
</code>```

Views

```<code><%= form_tag pdforms_history_path, :method => 'get' do %>
  <%= text_field_tag :search, params[:search] %>
  <%= submit_tag 'Search', :name => nil %>
<% end %>
</code>```

Pdforms controller

```<code>def history
    @pdforms = Pdform.search(params[:search])
  end
</code>```

Pdform Model

```<code>def self.search(search)
  if search
    self.where("user.first_name like ?", "%#{search}%")
  else
    self.all
  end
end
</code>```

答:
Try this:  </p>

```<code>def self.search(search)
  if search
    self.joins(:user).where("users.first_name LIKE ? OR users.last_name LIKE ?", "%#{search}%", "%#{search}%")
  else
    self.all
  end
end
</code>```

Title: Rails search association

Body:
I am creating a simple search form in my Rails app and right now it lets me search a Pdform attribute. A pdform belongs to a user so there is a user_id in the pdform model.

How can I search a users first_name and have it bring up all of the pdforms that belong to them?

This is how I have it setup.

Routes

get '/pdforms/history', to: 'pdforms#history'

Views

<%= form_tag pdforms_history_path, :method => 'get' do %>
  <%= text_field_tag :search, params[:search] %>
  <%= submit_tag 'Search', :name => nil %>
<% end %>

Pdforms controller

def history
    @pdforms = Pdform.search(params[:search])
  end

Pdform Model

def self.search(search)
  if search
    self.where("user.first_name like ?", "%#{search}%")
  else
    self.all
  end
end

Body:
Try this:

def self.search(search)
  if search
    self.joins(:user).where("users.first_name LIKE ? OR users.last_name LIKE ?", "%#{search}%", "%#{search}%")
  else
    self.all
  end
end


问:
Does Facebook Messenger Bot provide information about the channel where the message was originated?
I'm having a problem with the lite version of messenger (android only)

This version of the application does not support bot messages with templates or buttons (including the get_started button)

In my case this is an example:

I could not find a parameter in the webhooks to provide the user's platform.
So I have to ask the user: do you use the lite version?
And then set a different flow.

But this means that I must also give the possibility to disable the lite mode when browsing from the web or from the non-lite application (to guarantee a better user experience)

Does Facebook Messenger Bot provide information about the channel where the message was originated ?

答:
This information is not provided via webhook, currently. The closest you can get is detecting user agent in the webview.

A not ideal but doable option would be to have something like a 'Switch to Lite' button in the persistent menu


问:
How to link to current page with different param in react router?
Let's say I have the following routes set up (just an example, actual routes aren't this messy):

```<code><Router>
  <Switch>
    <Route path="/app/fun/:userid/profile" component={Profile} exact/>
    <Route path="/photos/:userid" component={Photos} exact/>
    <Route path="/:userid/contact" component={Contact} exact/>
  </Switch>
</Router>
</code>```

From ANY of the pages above, how can I link to the SAME page, but with a different userid?

eg:

```<code>/**
 * Shared component that's rendered by Profile, Photos and Contact
 */
class SharedComponent extends React.Component {
  render() {
    const bobId = 423423432;

    return (
      <div>
        <Link to={/* what to put here? */}>
          Redirect to the same page but with Bob's userid
        </Link>
      </div>
    );
  }
}

export default withRouter(SharedComponent);
</code>```

Note: using react router v4

答:
Pass userId with path props to shared component like below,

```<code>class Profile extends React.Component {
    render() {
        const bobId = 423423432; // Pass bobId with path from parent to child
        return (
            <SharedComponent path={"/stuff1/stuff2/`${bobId}`/profile"} />
        );
    }
}

class SharedComponent extends React.Component {
  render() {
    return (
      <div>
        <Link to={this.props.path}>
          Redirect to the same page but with Bob's userid
        </Link>
      </div>
    );
  }
}

export default withRouter(SharedComponent);
</code>```

Body:
Let's say I have the following routes set up (just an example, actual routes aren't this messy):

<Router>
  <Switch>
    <Route path="/app/fun/:userid/profile" component={Profile} exact/>
    <Route path="/photos/:userid" component={Photos} exact/>
    <Route path="/:userid/contact" component={Contact} exact/>
  </Switch>
</Router>

From ANY of the pages above, how can I link to the SAME page, but with a different userid?

eg:

/**
 * Shared component that's rendered by Profile, Photos and Contact
 */
class SharedComponent extends React.Component {
  render() {
    const bobId = 423423432;

    return (

        <Link to={/* what to put here? */}>
          Redirect to the same page but with Bob's userid
        </Link>

    );
  }
}

export default withRouter(SharedComponent);

Note: using react router v4

Body:
Pass userId with path props to shared component like below,

class Profile extends React.Component {
    render() {
        const bobId = 423423432; // Pass bobId with path from parent to child
        return (
            <SharedComponent path={"/stuff1/stuff2/`${bobId}`/profile"} />
        );
    }
}

class SharedComponent extends React.Component {
  render() {
    return (
      <div>
        <Link to={this.props.path}>
          Redirect to the same page but with Bob's userid
        </Link>
      </div>
    );
  }
}

export default withRouter(SharedComponent);


问:
Replacing multiple string values in one go
Hey guys how can I replace multiple numbers in a string for their values specified in a dict in one go? ex:

```<code>dic_lanches = {10:'Misto-Quente',11:'X-Burger',
               12:'X-Salada',
               13:'X-Egg',
               14:'X-Bacon',
               15:'X-Calabresa',
               16:'X-Frango',
               17:'X-Coração',
               18:'X-Casa'}

my_string = 11 12 13
</code>```

after replace:

I want X-Burguer X-Salada X-Egg

But what I am getting is:

```<code>X-Burguer 12 13

11 X-Salada 13

11 12 X-Egg
</code>```

now tried:

```<code>result = re.sub(r'\d', lambda x: dic_lanches[int(x.group())], myString)
</code>```

but I'm getting KeyError 1

答:
Using re:

```<code>import re
myString = "I want 11 12 13"
result = re.sub(r'\d', lambda x: dic_lanches[int(x.group())], myString)
</code>```

What we are doing here is we use regex to match all numbers in the string, then we replace those numbers with the string in the dict that has the corresponding key.

Body:
Hey guys how can I replace multiple numbers in a string for their values specified in a dict in one go? ex:

dic_lanches = {10:'Misto-Quente',11:'X-Burger',
               12:'X-Salada',
               13:'X-Egg',
               14:'X-Bacon',
               15:'X-Calabresa',
               16:'X-Frango',
               17:'X-Coração',
               18:'X-Casa'}

my_string = 11 12 13

after replace:

I want X-Burguer X-Salada X-Egg

But what I am getting is:

X-Burguer 12 13

11 X-Salada 13

11 12 X-Egg

now tried:

result = re.sub(r'\d', lambda x: dic_lanches[int(x.group())], myString)

but I'm getting KeyError 1

Body:
Using re:

import re
myString = "I want 11 12 13"
result = re.sub(r'\d', lambda x: dic_lanches[int(x.group())], myString)

What we are doing here is we use regex to match all numbers in the string, then we replace those numbers with the string in the dict that has the corresponding key.


问:
Authorize.net support for Bin number Check (card issuer identification number )feature
In my project I am using authorize.net AIM & CIM feature for payment processing, I want to implement real time verification of card holder during transaction using authorize.net & asp.net (C#) in order to provide higher level of security and avoid fraud transaction. </p>

<p>Today, I want confirm that ,
Is it possible to verify BIN number (Credit card Issuer Identification number) of credit card from card number using authorize.net ?
How can I check  BIN number of credit card with authorize.net  in  real time  from credit card number which will support for all types of credit card such Visa, Master Card, American Express, Discover etc. </p>

答: Here is a free tier BIN check: https://tripayments.com/bins/.  Threshold is 10 requests a second before an upgraded version is required.  I've used it in the past for detecting fraud.  Supports an array bins instead of singles.</p>

Body:
In my project I am using authorize.net AIM & CIM feature for payment processing, I want to implement real time verification of card holder during transaction using authorize.net & asp.net (C#) in order to provide higher level of security and avoid fraud transaction.

Today, I want confirm that ,
Is it possible to verify BIN number (Credit card Issuer Identification number) of credit card from card number using authorize.net ?
How can I check  BIN number of credit card with authorize.net  in  real time  from credit card number which will support for all types of credit card such Visa, Master Card, American Express, Discover etc.


问:
How can i make a the text bold which is stored in a string variable?
I want to make the text stored inside a string variable to bold.

String buttonText = t.getText().toString();
                String val = map.get(buttonText);

```<code>          new MaterialDialog.Builder(LearningMode.this)
                    .iconRes(BalloonColor.get(2))
                    .limitIconToDefaultSize()
                    .title("Meaning")

                    .content(buttonText+"\n"+val)

                    .positiveText("Continue")
                    .cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            mover.resume();
                        }
                    })

                    .show();
</code>```

at .content(buttonText+"\n"+val)
i want the string stored inside this to become bold.
i have tried html.fromhtml it is not working

like this Html.fromHtml("  "+buttonText+" ")

added space in the above  as it is converting to bold

and other methods like declaring in strings.xml with  wont work here as i'm dealing it programmatically here!

ultimately when the string button text is displayed in the output sholud be bold.

i have already referred this Set TextView text from html-formatted string resource in XML

Update:

There is no textview used.

Someone please help!

答:
The MaterialDialog.Builder class's content(CharSequence) method should work just fine for making text bold, as long as you pass in some CharSequence that supports bold text. I know you said Html.fromHtml() isn't working, but in my tests it works perfectly. Here's a really simple activity that's a proof of concept:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();

        String myString = "test";

        new MaterialDialog.Builder(this)
                .title("Hello world")
                .content(Html.fromHtml("this is a <b>" + myString + "</b>"))
                .positiveText("OK")
                .show();
    }
}
</code>```

Body:
I want to make the text stored inside a string variable to bold.

String buttonText = t.getText().toString();
                String val = map.get(buttonText);

          new MaterialDialog.Builder(LearningMode.this)
                    .iconRes(BalloonColor.get(2))
                    .limitIconToDefaultSize()
                    .title("Meaning")

                    .content(buttonText+"\n"+val)

                    .positiveText("Continue")
                    .cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            mover.resume();
                        }
                    })

                    .show();

at .content(buttonText+"\n"+val)
i want the string stored inside this to become bold.
i have tried html.fromhtml it is not working

like this Html.fromHtml("  "+buttonText+" ")

added space in the above  as it is converting to bold

and other methods like declaring in strings.xml with  wont work here as i'm dealing it programmatically here!

ultimately when the string button text is displayed in the output sholud be bold.

i have already referred this Set TextView text from html-formatted string resource in XML

Update:

There is no textview used.

Someone please help!

Body:
The MaterialDialog.Builder class's content(CharSequence) method should work just fine for making text bold, as long as you pass in some CharSequence that supports bold text. I know you said Html.fromHtml() isn't working, but in my tests it works perfectly. Here's a really simple activity that's a proof of concept:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();

        String myString = "test";

        new MaterialDialog.Builder(this)
                .title("Hello world")
                .content(Html.fromHtml("this is a <b>" + myString + "</b>"))
                .positiveText("OK")
                .show();
    }
}


问:
WPF Datagrid: MVVM friendly way to bind SelectedCells to my ViewModel
I'm using the WPF datagrid, and have SelectionUnit="Cell" and SelectionMode="Extended". I'm also trying to adhere to the MVVM principals as much as I can.

I need my ViewModel to keep track of the current SelectedCells.

Life would be easy if I could just Bind its SelectedCells property to my ViewModel. Oddly enough, SelectedCells is only raised once - when we first select any cell in the grid.

MS explains it here: http://social.msdn.microsoft.com/Forums/en/wpf/thread/737117f4-6d20-4232-88cf-e52cc44d4431

Can anyone think of an MVVM-friendly approach to get around it?

Thanks!

答:
I realized my last answer was for SelectedItems instead of SelectedCells, so I wrote a complete attached property class to do data binding for multiple SelectedCells which works as follows:

<controls:DataGrid ItemsSource="{StaticResource list}"
                   SelectionMode="Extended"
                 behaviors:DataGridSelectedCellsBehavior.SelectedCells="{Binding Path=SelectedGridCellCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
```
<p>I have a working source code and a demo project of it here.</p>
<p><strong>Attached property behavior Code :</strong></p>
<pre class="lang-cs prettyprint-override"><code>public class DataGridSelectedCellsBehavior
{
    // Source : https://archive.codeplex.com/?p=datagridthemesfromsl
    // Credit to : T. Webster, https://stackoverflow.com/users/266457/t-webster

    public static IList<DataGridCellInfo> GetSelectedCells(DependencyObject obj)
    {
        return (IList<DataGridCellInfo>)obj.GetValue(SelectedCellsProperty);
    }
    public static void SetSelectedCells(DependencyObject obj, IList<DataGridCellInfo> value)
    {
        obj.SetValue(SelectedCellsProperty, value);
    }

    public static readonly DependencyProperty SelectedCellsProperty = DependencyProperty.RegisterAttached("SelectedCells", typeof(IList<DataGridCellInfo>), typeof(DataGridSelectedCellsBehavior), new UIPropertyMetadata(null, OnSelectedCellsChanged));

    static SelectedCellsChangedEventHandler GetSelectionChangedHandler(DependencyObject obj)
    {
        return (SelectedCellsChangedEventHandler)obj.GetValue(SelectionChangedHandlerProperty);
    }
    static void SetSelectionChangedHandler(DependencyObject obj, SelectedCellsChangedEventHandler value)
    {
        obj.SetValue(SelectionChangedHandlerProperty, value);
    }

    static readonly DependencyProperty SelectionChangedHandlerProperty = DependencyProperty.RegisterAttached("SelectedCellsChangedEventHandler", typeof(SelectedCellsChangedEventHandler), typeof(DataGridSelectedCellsBehavior), new UIPropertyMetadata(null));

    //d is MultiSelector (d as ListBox not supported)
    static void OnSelectedCellsChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (GetSelectionChangedHandler(d) != null)
            return;

        if (d is DataGrid)//DataGrid
        {
            DataGrid datagrid = d as DataGrid;
            SelectedCellsChangedEventHandler selectionchanged = null;
            foreach (var selected in GetSelectedCells(d) as IList<DataGridCellInfo>)
                datagrid.SelectedCells.Add(selected);

            selectionchanged = (sender, e) =>
            {
                SetSelectedCells(d, datagrid.SelectedCells);
            };
            SetSelectionChangedHandler(d, selectionchanged);
            datagrid.SelectedCellsChanged += GetSelectionChangedHandler(d);
        }
        //else if (d is ListBox)
        //{
        //    ListBox listbox = d as ListBox;
        //    SelectionChangedEventHandler selectionchanged = null;

        //    selectionchanged = (sender, e) =>
        //    {
        //        SetSelectedCells(d, listbox.SelectedCells);
        //    };
        //    SetSelectionChangedHandler(d, selectionchanged);
        //    listbox.SelectionChanged += GetSelectionChangedHandler(d);
        //}
    }

}
</code>```

View Model Code :

class DemoViewModel : INotifyPropertyChanged
{
    private IList<DataGridCellInfo> selectedGridCellCollection = new List<DataGridCellInfo>();
    public IList<DataGridCellInfo> SelectedGridCellCollection
    {
        get { return selectedGridCellCollection; }
        set
        {
            selectedGridCellCollection = value;
            NotifyPropertyChanged();
        }
    }

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
```

Body:
I realized my last answer was for SelectedItems instead of SelectedCells, so I wrote a complete attached property class to do data binding for multiple SelectedCells which works as follows:

<controls:DataGrid ItemsSource="{StaticResource list}"
                   SelectionMode="Extended"
                 behaviors:DataGridSelectedCellsBehavior.SelectedCells="{Binding Path=SelectedGridCellCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

I have a working source code and a demo project of it here.

Attached property behavior Code :

public class DataGridSelectedCellsBehavior
{
    // Source : https://archive.codeplex.com/?p=datagridthemesfromsl
    // Credit to : T. Webster, https://stackoverflow.com/users/266457/t-webster

    public static IList<DataGridCellInfo> GetSelectedCells(DependencyObject obj)
    {
        return (IList<DataGridCellInfo>)obj.GetValue(SelectedCellsProperty);
    }
    public static void SetSelectedCells(DependencyObject obj, IList<DataGridCellInfo> value)
    {
        obj.SetValue(SelectedCellsProperty, value);
    }

    public static readonly DependencyProperty SelectedCellsProperty = DependencyProperty.RegisterAttached("SelectedCells", typeof(IList<DataGridCellInfo>), typeof(DataGridSelectedCellsBehavior), new UIPropertyMetadata(null, OnSelectedCellsChanged));

    static SelectedCellsChangedEventHandler GetSelectionChangedHandler(DependencyObject obj)
    {
        return (SelectedCellsChangedEventHandler)obj.GetValue(SelectionChangedHandlerProperty);
    }
    static void SetSelectionChangedHandler(DependencyObject obj, SelectedCellsChangedEventHandler value)
    {
        obj.SetValue(SelectionChangedHandlerProperty, value);
    }

    static readonly DependencyProperty SelectionChangedHandlerProperty = DependencyProperty.RegisterAttached("SelectedCellsChangedEventHandler", typeof(SelectedCellsChangedEventHandler), typeof(DataGridSelectedCellsBehavior), new UIPropertyMetadata(null));

    //d is MultiSelector (d as ListBox not supported)
    static void OnSelectedCellsChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (GetSelectionChangedHandler(d) != null)
            return;

        if (d is DataGrid)//DataGrid
        {
            DataGrid datagrid = d as DataGrid;
            SelectedCellsChangedEventHandler selectionchanged = null;
            foreach (var selected in GetSelectedCells(d) as IList<DataGridCellInfo>)
                datagrid.SelectedCells.Add(selected);

            selectionchanged = (sender, e) =>
            {
                SetSelectedCells(d, datagrid.SelectedCells);
            };
            SetSelectionChangedHandler(d, selectionchanged);
            datagrid.SelectedCellsChanged += GetSelectionChangedHandler(d);
        }
        //else if (d is ListBox)
        //{
        //    ListBox listbox = d as ListBox;
        //    SelectionChangedEventHandler selectionchanged = null;

        //    selectionchanged = (sender, e) =>
        //    {
        //        SetSelectedCells(d, listbox.SelectedCells);
        //    };
        //    SetSelectionChangedHandler(d, selectionchanged);
        //    listbox.SelectionChanged += GetSelectionChangedHandler(d);
        //}
    }

}

View Model Code :

class DemoViewModel : INotifyPropertyChanged
{
    private IList<DataGridCellInfo> selectedGridCellCollection = new List<DataGridCellInfo>();
    public IList<DataGridCellInfo> SelectedGridCellCollection
    {
        get { return selectedGridCellCollection; }
        set
        {
            selectedGridCellCollection = value;
            NotifyPropertyChanged();
        }
    }

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

ContentLicense: CC BY-SA 4.0


问:
Can bitcode still be disable on Xcode 9.2?
Can once still be able to disable bitcode on Xcode 9.2?  I looked into Build Settings tab under project.  But there was not one.</p>

答: In Xcode 9.2 also you can disable bitcode. Today I just disabled bitcode in Xcode 9.2 and successfully uploaded game to iTunesConnect.