问:
Inserting blank rows in VBA excel
Final One:enter image description hereI want to insert blank row with a specific column range above a particular row.
For example:
There were 2 sets of data in a single sheet ,ie, 1st set col A to Col E and 2nd set Col F to Col J. I need to compare Column Ai with Column Fi  (where i indicates the position of row) and if both values are same then the comparison can be proceeded like Bi with Gi, Ci with Hi and so and so and if not, I need to shift that set of 2nd data Fi to Ji to next row..ie. if the whole set is in 6th position I need to shift them down to 7th position and make the 6th position of Fi to Ji blank....</p>

```<code> Sub Dcompare()
 Dim endRow As Long
 Dim lRow As Long
 Dim ws As Worksheet

 Set ws = ThisWorkbook.Worksheets(1)

 endRow = Sheet1.Range("A999999").End(xlUp).Row
 For i = 2 To endRow
 If Sheet1.Range("A" & i).Value = Sheet1.Range("F" & i).Value Then
    Sheet1.Range("K" & i).Value = "Yes"

 Else
 ws.Range("F" & i & ":J" & i).Offset(1, 0).Value = ws.Range("F" & i & ":J" &    i).Value
 ws.Range("F" & i & ":J" & i).Value = ""

 End If

 Next i

For j = 2 To endRow
If Sheet1.Range("K" & j).Value = "Yes" Then
If Sheet1.Range("B" & j).Value = Sheet1.Range("G" & j).Value Then
   Sheet1.Range("L" & j).Value = "Yes"
Else
    Sheet1.Range("L" & j).Value = "No"
End If
If Sheet1.Range("C" & j).Value = Sheet1.Range("H" & j).Value Then
   Sheet1.Range("M" & j).Value = "Yes"
Else
    Sheet1.Range("M" & j).Value = "No"
End If
If Sheet1.Range("D" & j).Value = Sheet1.Range("I" & j).Value Then
    Sheet1.Range("N" & j).Value = "Yes"
Else
    Sheet1.Range("N" & j).Value = "No"
End If
If Sheet1.Range("E" & j).Value = Sheet1.Range("J" & j).Value Then
     Sheet1.Range("O" & j).Value = "Yes"
Else
    Sheet1.Range("O" & j).Value = "No"
End If
End If
Next j
End Sub

------>Final Code Inserted---------

Sub Dcompare()
Dim endRow As Long
Dim ws As Worksheet
Dim dShift As Boolean
Set ws = ThisWorkbook.Worksheets(1)
endRow = ws.Range("A999999").End(xlUp).Row
For i = 2 To endRow + 1

If ws.Range("A" & i).Value = ws.Range("F" & i).Value Then
dShift = False
ws.Range("K" & i).Value = "Yes"
Else
If Not dShift Then
ws.Range("F" & i & ":J" & i).Insert Shift:=xlDown,               CopyOrigin:=xlFormatFromLeftOrAbove
ws.Range("A" & i + 1 & ":E" & i + 1).Insert Shift:=xlDown,   CopyOrigin:=xlFormatFromLeftOrAbove
     endRow = endRow + 1
     dShift = True
     Else
     dShift = False
     End If
     End If

 j = i
 If ws.Range("K" & j).Value = "Yes" Then
 If ws.Range("B" & j).Value = ws.Range("G" & j).Value Then
 ws.Range("L" & j).Value = "Yes"
 Else
     ws.Range("L" & j).Value = "No"
 End If
 If ws.Range("C" & j).Value = ws.Range("H" & j).Value Then
    ws.Range("M" & j).Value = "Yes"
 Else
     ws.Range("M" & j).Value = "No"
 End If
 If ws.Range("D" & j).Value = ws.Range("I" & j).Value Then
     ws.Range("N" & j).Value = "Yes"
 Else
     ws.Range("N" & j).Value = "No"
 End If
 If ws.Range("E" & j).Value = ws.Range("J" & j).Value Then
      ws.Range("O" & j).Value = "Yes"
 Else
     ws.Range("O" & j).Value = "No"
 End If
 Else
 End If

 Next i
 MsgBox "The value of endRow is : " & endRow, vbInformation

 End Sub
</code>```

答:
Based on your explanations, this is what I interpret your challenge as:

Evaluate Ai with Fi --> Ei with Ji from left to right, and indicate in helper-columns whether the evaluation succeeded or not

If the first evaluation is Not Equal, offset the range Fi:Ji downwards exactly one row

If a range has been shifted down, the loop should evaluate this line but never shift it again regardless of outcome of the evaluation

This code satisfies those conditions (change i and other row variables to your needs):

```<code>Sub Dcompare()
    Dim endRow As Long
    Dim ws As Worksheet
    Dim dShift As Boolean

    Set ws = ThisWorkbook.Worksheets(1)
    endRow = ws.Range("A999999").End(xlUp).Row

    ' Set initial value of helper columns to no - saves miniscule time and complexity in the loop
    ws.Range("L" & 1 & ":O" & endRow).Value = "No"

    For i = 1 To endRow
        If ws.Range("A" & i).Value = ws.Range("F" & i).Value Then
            dShift = False
            ws.Range("L" & i).Value = "Yes"
        Else
            If Not dShift Then
                ws.Range("F" & i & ":J" & i).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

                ' Remember that we just shifted a row
                dShift = True
            Else
                ' Reset shift counter
                dShift = False
            End If
        End If

        For j = 2 To 4
            If dShift Then Exit For
            If ws.Cells(i, j).Value = ws.Cells(i, j + 5).Value Then ws.Cells(i, j + 11).Value = "Yes"
        Next j
    Next i
End Sub
</code>```

However, it seems strange to me that you would want this functionality? Please confirm that it is correct. The behavior it yields in the worksheet is very strange.

Let me show with images. Orange background means the code will show the cell as a match. Green background means the code will show that the cell doesn't match.

Before the code it looks like this:

After the code it looks like this:

Title: Inserting blank rows in VBA excel

Body:
Final One:enter image description hereI want to insert blank row with a specific column range above a particular row.
For example:
There were 2 sets of data in a single sheet ,ie, 1st set col A to Col E and 2nd set Col F to Col J. I need to compare Column Ai with Column Fi  (where i indicates the position of row) and if both values are same then the comparison can be proceeded like Bi with Gi, Ci with Hi and so and so and if not, I need to shift that set of 2nd data Fi to Ji to next row..ie. if the whole set is in 6th position I need to shift them down to 7th position and make the 6th position of Fi to Ji blank....

 Sub Dcompare()
 Dim endRow As Long
 Dim lRow As Long
 Dim ws As Worksheet

 Set ws = ThisWorkbook.Worksheets(1)

 endRow = Sheet1.Range("A999999").End(xlUp).Row
 For i = 2 To endRow
 If Sheet1.Range("A" & i).Value = Sheet1.Range("F" & i).Value Then
    Sheet1.Range("K" & i).Value = "Yes"

 Else
 ws.Range("F" & i & ":J" & i).Offset(1, 0).Value = ws.Range("F" & i & ":J" &    i).Value
 ws.Range("F" & i & ":J" & i).Value = ""

 End If

 Next i

For j = 2 To endRow
If Sheet1.Range("K" & j).Value = "Yes" Then
If Sheet1.Range("B" & j).Value = Sheet1.Range("G" & j).Value Then
   Sheet1.Range("L" & j).Value = "Yes"
Else
    Sheet1.Range("L" & j).Value = "No"
End If
If Sheet1.Range("C" & j).Value = Sheet1.Range("H" & j).Value Then
   Sheet1.Range("M" & j).Value = "Yes"
Else
    Sheet1.Range("M" & j).Value = "No"
End If
If Sheet1.Range("D" & j).Value = Sheet1.Range("I" & j).Value Then
    Sheet1.Range("N" & j).Value = "Yes"
Else
    Sheet1.Range("N" & j).Value = "No"
End If
If Sheet1.Range("E" & j).Value = Sheet1.Range("J" & j).Value Then
     Sheet1.Range("O" & j).Value = "Yes"
Else
    Sheet1.Range("O" & j).Value = "No"
End If
End If
Next j
End Sub

------>Final Code Inserted---------

Sub Dcompare()
Dim endRow As Long
Dim ws As Worksheet
Dim dShift As Boolean
Set ws = ThisWorkbook.Worksheets(1)
endRow = ws.Range("A999999").End(xlUp).Row
For i = 2 To endRow + 1

If ws.Range("A" & i).Value = ws.Range("F" & i).Value Then
dShift = False
ws.Range("K" & i).Value = "Yes"
Else
If Not dShift Then
ws.Range("F" & i & ":J" & i).Insert Shift:=xlDown,               CopyOrigin:=xlFormatFromLeftOrAbove
ws.Range("A" & i + 1 & ":E" & i + 1).Insert Shift:=xlDown,   CopyOrigin:=xlFormatFromLeftOrAbove
     endRow = endRow + 1
     dShift = True
     Else
     dShift = False
     End If
     End If

 j = i
 If ws.Range("K" & j).Value = "Yes" Then
 If ws.Range("B" & j).Value = ws.Range("G" & j).Value Then
 ws.Range("L" & j).Value = "Yes"
 Else
     ws.Range("L" & j).Value = "No"
 End If
 If ws.Range("C" & j).Value = ws.Range("H" & j).Value Then
    ws.Range("M" & j).Value = "Yes"
 Else
     ws.Range("M" & j).Value = "No"
 End If
 If ws.Range("D" & j).Value = ws.Range("I" & j).Value Then
     ws.Range("N" & j).Value = "Yes"
 Else
     ws.Range("N" & j).Value = "No"
 End If
 If ws.Range("E" & j).Value = ws.Range("J" & j).Value Then
      ws.Range("O" & j).Value = "Yes"
 Else
     ws.Range("O" & j).Value = "No"
 End If
 Else
 End If

 Next i
 MsgBox "The value of endRow is : " & endRow, vbInformation

 End Sub

Body:
Based on your explanations, this is what I interpret your challenge as:

Evaluate Ai with Fi --> Ei with Ji from left to right, and indicate in helper-columns whether the evaluation succeeded or not

If the first evaluation is Not Equal, offset the range Fi:Ji downwards exactly one row

If a range has been shifted down, the loop should evaluate this line but never shift it again regardless of outcome of the evaluation

This code satisfies those conditions (change i and other row variables to your needs):

Sub Dcompare()
    Dim endRow As Long
    Dim ws As Worksheet
    Dim dShift As Boolean

    Set ws = ThisWorkbook.Worksheets(1)
    endRow = ws.Range("A999999").End(xlUp).Row

    ' Set initial value of helper columns to no - saves miniscule time and complexity in the loop
    ws.Range("L" & 1 & ":O" & endRow).Value = "No"

    For i = 1 To endRow
        If ws.Range("A" & i).Value = ws.Range("F" & i).Value Then
            dShift = False
            ws.Range("L" & i).Value = "Yes"
        Else
            If Not dShift Then
                ws.Range("F" & i & ":J" & i).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

                ' Remember that we just shifted a row
                dShift = True
            Else
                ' Reset shift counter
                dShift = False
            End If
        End If

        For j = 2 To 4
            If dShift Then Exit For
            If ws.Cells(i, j).Value = ws.Cells(i, j + 5).Value Then ws.Cells(i, j + 11).Value = "Yes"
        Next j
    Next i
End Sub

However, it seems strange to me that you would want this functionality? Please confirm that it is correct. The behavior it yields in the worksheet is very strange.

Let me show with images. Orange background means the code will show the cell as a match. Green background means the code will show that the cell doesn't match.

Before the code it looks like this:

After the code it looks like this:


来源: stackexchange

问:
macro that will insert a space between words in an array
I need to write a macro that will insert a space between each word in the final array. How could I achieve this and where must I initialize and call it.

Desired output: "Say Cheese Okay".

Output so far: "SayCheeseOkay"

My code so far:

```<code>INCLUDE Irvine32.inc

.data
seq1 byte 'Sequence1 : ', 0
seq2 byte 'Sequence2 : ', 0
seq3 byte 'Sequence3 : ', 0
fin_seq byte 'Final Sequence : ', 0
s1 byte 'Say', 0
s2 byte 'Cheese', 0
s3 byte 'Okay', 0
s4 byte 30 dup(?)

.code
main PROC
    cld
    mov edx, offset seq1
    call WriteString
    mov edx, offset s1
    call WriteString
    call Crlf

    mov edx, offset seq2
    call WriteString
    mov edx, offset s2
    call WriteString
    call Crlf

    mov edx, offset seq3
    call WriteString
    mov edx, offset s3
    call WriteString
    call Crlf

    mov ecx, LENGTHOF s1
    mov esi, offset s1
    mov edi, offset s4

copy1 : movsb
    loop copy1

    mov ecx, LENGTHOF s2
    mov esi, offset s2
    mov edi, offset s4
    add edi, LENGTHOF s1
    sub edi, 1

copy2: movsb
    loop copy2
    mov ecx, LENGTHOF s3
    mov esi, offset s3
    mov edi, offset s4
    add edi, LENGTHOF s1
    add edi, LENGTHOF s2
    sub edi, 2

copy3: movsb
    loop copy3
    mov edi, offset s4
    mov ecx, lengthof s4
    mov al, ' '
    cld

c1:
    scasb
    je c2
    cmp ecx, 0
    jz quit
    loop c1

c2:
    cld
    sub edi, 1
    stosb
    jmp c1

quit:
    mov ecx, LENGTHOF s4
    mov esi, OFFSET s4
    mov ebx, 0

cycle:
    mov al, [esi]
    jmp exl

exl:
    movsb
    loop cycle
    mov edx, offset fin_seq
    call WriteString
    mov edx, offset s4
    call WriteString

    call Crlf
    call ReadKey
    call ReadChar

exit
main ENDP
END main
</code>```

答:
The marco should look like this:

```<code>procedure MACRO ad1
    mov byte ptr [edi-1],' '

ENDM
</code>```

and just call it after the copy1 and copy2 methods. And delete sub edi, 1 in the copy1 method.

ContentLicense: CC BY-SA 3.0

Body:
I need to write a macro that will insert a space between each word in the final array. How could I achieve this and where must I initialize and call it.

Desired output: "Say Cheese Okay".

Output so far: "SayCheeseOkay"

My code so far:

INCLUDE Irvine32.inc

.data
seq1 byte 'Sequence1 : ', 0
seq2 byte 'Sequence2 : ', 0
seq3 byte 'Sequence3 : ', 0
fin_seq byte 'Final Sequence : ', 0
s1 byte 'Say', 0
s2 byte 'Cheese', 0
s3 byte 'Okay', 0
s4 byte 30 dup(?)

.code
main PROC
    cld
    mov edx, offset seq1
    call WriteString
    mov edx, offset s1
    call WriteString
    call Crlf

    mov edx, offset seq2
    call WriteString
    mov edx, offset s2
    call WriteString
    call Crlf

    mov edx, offset seq3
    call WriteString
    mov edx, offset s3
    call WriteString
    call Crlf

    mov ecx, LENGTHOF s1
    mov esi, offset s1
    mov edi, offset s4

copy1 : movsb
    loop copy1

    mov ecx, LENGTHOF s2
    mov esi, offset s2
    mov edi, offset s4
    add edi, LENGTHOF s1
    sub edi, 1

copy2: movsb
    loop copy2
    mov ecx, LENGTHOF s3
    mov esi, offset s3
    mov edi, offset s4
    add edi, LENGTHOF s1
    add edi, LENGTHOF s2
    sub edi, 2

copy3: movsb
    loop copy3
    mov edi, offset s4
    mov ecx, lengthof s4
    mov al, ' '
    cld

c1:
    scasb
    je c2
    cmp ecx, 0
    jz quit
    loop c1

c2:
    cld
    sub edi, 1
    stosb
    jmp c1

quit:
    mov ecx, LENGTHOF s4
    mov esi, OFFSET s4
    mov ebx, 0

cycle:
    mov al, [esi]
    jmp exl

exl:
    movsb
    loop cycle
    mov edx, offset fin_seq
    call WriteString
    mov edx, offset s4
    call WriteString

    call Crlf
    call ReadKey
    call ReadChar

exit
main ENDP
END main

Body:
The marco should look like this:

procedure MACRO ad1
    mov byte ptr [edi-1],' '

ENDM

and just call it after the copy1 and copy2 methods. And delete sub edi, 1 in the copy1 method.


问:
JUnit: compare two beans that contain a List regardless of list order
I have found a lot of questions and answers about comparing List objects regardless of the order of their elements, but my problem is more complex: I have two beans that contain, among other properties, a List.  I want to perform an assertEquals of the two beans regardless of the order of the elements in the inner lists.  Is there a simple way to do this?</p>

答:
I guess you can find an answer here. The idea is to use hamcrest asserts.</p>
```<code>import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;

public class CompareListTest {

    @Test
    public void compareList() {
        List<String> expected = Arrays.asList("String A", "String B");
        List<String> actual = Arrays.asList("String B", "String A");

        assertThat("List equality without order",
            actual, containsInAnyOrder(expected.toArray()));
    }

}
</code>```

Body:
I guess you can find an answer here. The idea is to use hamcrest asserts.

import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;

public class CompareListTest {

    @Test
    public void compareList() {
        List<String> expected = Arrays.asList("String A", "String B");
        List<String> actual = Arrays.asList("String B", "String A");

        assertThat("List equality without order",
            actual, containsInAnyOrder(expected.toArray()));
    }

}

ContentLicense: CC BY-SA 4.0


问:
Illegal 'sec-websocket-protocol' header: Invalid input 'EOI', expected sec-websocket-protocol
I'm trying to connect on Kubernetes websocket API but I get this error message:

```<code>java.lang.IllegalStateException: Message failed with status code 400 Bad Request; Error info: ErrorInfo(Illegal 'sec-websocket-protocol' header: Invalid input 'EOI', expected sec-websocket-protocol (line 1, column 1),
^)
    at akka.http.impl.engine.ws.WebSocketClientBlueprint$UpgradeStage$1$$anon$1.onPush(WebSocketClientBlueprint.scala:107)
    at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:747)
    at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:649)
    at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:471)
    at akka.stream.impl.fusing.GraphInterpreterShell.receive(ActorGraphInterpreter.scala:410)
    at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$processEvent(ActorGraphInterpreter.scala:603)
    at akka.stream.impl.fusing.ActorGraphInterpreter$$anonfun$receive$1.applyOrElse(ActorGraphInterpreter.scala:618)
    at akka.actor.Actor.aroundReceive(Actor.scala:502)
    at akka.actor.Actor.aroundReceive$(Actor.scala:500)
    at akka.stream.impl.fusing.ActorGraphInterpreter.aroundReceive(ActorGraphInterpreter.scala:529)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)
    at akka.actor.ActorCell.invoke(ActorCell.scala:495)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
    at akka.dispatch.Mailbox.run(Mailbox.scala:224)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
</code>```

I must be missing some configuration, do you knwo where this comes from?

Cheers

答:
Got over it by defining subprotocol to channel.k8s.io:

```<code>WebSocketRequest(
  uri,
  extraHeaders = List(token),
  subprotocol = Option("channel.k8s.io")
)
</code>```

Body:
I'm trying to connect on Kubernetes websocket API but I get this error message:

java.lang.IllegalStateException: Message failed with status code 400 Bad Request; Error info: ErrorInfo(Illegal 'sec-websocket-protocol' header: Invalid input 'EOI', expected sec-websocket-protocol (line 1, column 1),
^)
    at akka.http.impl.engine.ws.WebSocketClientBlueprint$UpgradeStage$1$$anon$1.onPush(WebSocketClientBlueprint.scala:107)
    at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:747)
    at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:649)
    at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:471)
    at akka.stream.impl.fusing.GraphInterpreterShell.receive(ActorGraphInterpreter.scala:410)
    at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$processEvent(ActorGraphInterpreter.scala:603)
    at akka.stream.impl.fusing.ActorGraphInterpreter$$anonfun$receive$1.applyOrElse(ActorGraphInterpreter.scala:618)
    at akka.actor.Actor.aroundReceive(Actor.scala:502)
    at akka.actor.Actor.aroundReceive$(Actor.scala:500)
    at akka.stream.impl.fusing.ActorGraphInterpreter.aroundReceive(ActorGraphInterpreter.scala:529)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)
    at akka.actor.ActorCell.invoke(ActorCell.scala:495)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
    at akka.dispatch.Mailbox.run(Mailbox.scala:224)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

I must be missing some configuration, do you knwo where this comes from?

Cheers

Body:
Got over it by defining subprotocol to channel.k8s.io:

WebSocketRequest(
  uri,
  extraHeaders = List(token),
  subprotocol = Option("channel.k8s.io")
)


问:
Need to Aggregate on the Last Month for a Grouped Report
I have a dataset that looks like the following:

```<code>| Location | Category |Item Name |   Month  | QTY |
| -------- | -------- | -------- | -------- | --- |
|    NY    | Hardware |   Screw  | Jan 2017 | 100 |
|    NY    | Hardware |   Screw  | Feb 2017 | 50  |
|    NY    | Hardware |   Screw  | Mar 2017 | 75  |
|    NY    | Hardware |    Bolt  | Jan 2017 | 30  |
|    NY    | Hardware |    Bolt  | Feb 2017 | 90  |
|    NY    | Hardware |    Bolt  | Mar 2017 | 50  |
|    CA    | Hardware |   Screw  | Jan 2017 | 100 |
|    CA    | Hardware |   Screw  | Feb 2017 | 50  |
|    CA    | Hardware |   Screw  | Mar 2017 | 75  |
|    CA    | Hardware |    Bolt  | Jan 2017 | 30  |
|    CA    | Hardware |    Bolt  | Feb 2017 | 90  |
|    CA    | Hardware |    Bolt  | Mar 2017 | 50  |
</code>```

My report needs to look like the following:

```<code>|      Hardware      | Screw |  Bolt |
|Current Month Total |  150  |  100  |
|Yearly Total        |  450  |  340  |
</code>```

I need a way to limit the current month total to ONLY the current month but aggregate the values for the yearly total. I've tried using LAST in the aggregate but you can't. I've tried the following for the current month total aggregate. My Date value is the 1st day of the month and my parameter is the last day of the month, so I needed a way to match the 2 that is why there is the date addition. The jist is to try and match the current month, which is a parameter to the date column:

=iif( DateAdd(dateinterval.Day,-1,DateAdd(dateinterval.Month,1,Fields!Sale_DATE.Value)) = Parameters!ReportingDate.Value, iif(isnothing(sum(Fields!Total.Value)),"",sum(Fields!Total.Value)),sum(0))

but it only works if the query that returns the dataset returns ONLY the current month. If the query returns all of the months in the year it shows 0's. I need a way to filter the cells so they aggregate the values correctly

If I limit my report to only the current month I can't get the yearly aggregate and if I select all of the months I can't get the current month total.

答:
Actually, using grouping as suggested alone doesn't work. I was already using groups in my matrix. The issue is that I needed a different form of grouping within the same column and I needed to restrict the grouping to different date ranges. My problem was that I had the SUM in the wrong position in my formula.

The expressions for the yearly total should have been:

```<code>=Sum(IIF(Fields!ItemName.Value="Screw",Fields!QTY.Value,0))
=Sum(IIF(Fields!ItemName.Value="Bolt",Fields!QTY.Value,0))
</code>```

Then, based on the dataset, if the current month is "Mar 2017" I can build the expression for Month Total as

```<code>=Sum(IIF(Fields!ItemName.Value="Screw" and Fields!Month.Value="Mar 2017",Fields!QTY.Value,0))``
=Sum(IIF(Fields!ItemName.Value="Bolt" and Fields!Month.Value="Mar 2017",Fields!QTY.Value,0))
</code>```

These examples are using my sample dataset in this question. Since I couldn't hard code dates, wanted to use parameters, and needed to do a calculation this is what I ACTUALLY used:

```<code>SUM(iif(DateAdd(dateinterval.Day,-1,DateAdd(dateinterval.Month,1,Fields!REL_DATE.Value))= Parameters!ReportingDate.Value,
Fields!Total_OnTime.Value,0))/SUM(iif(DateAdd(dateinterval.Day,-1,DateAdd(dateinterval.Month,1,Fields!REL_DATE.Value))= Parameters!ReportingDate.Value,
Fields!Total.Value,0))
</code>```

Hope this helps someone else.

Body:
I have a dataset that looks like the following:

| Location | Category |Item Name |   Month  | QTY |
| -------- | -------- | -------- | -------- | --- |
|    NY    | Hardware |   Screw  | Jan 2017 | 100 |
|    NY    | Hardware |   Screw  | Feb 2017 | 50  |
|    NY    | Hardware |   Screw  | Mar 2017 | 75  |
|    NY    | Hardware |    Bolt  | Jan 2017 | 30  |
|    NY    | Hardware |    Bolt  | Feb 2017 | 90  |
|    NY    | Hardware |    Bolt  | Mar 2017 | 50  |
|    CA    | Hardware |   Screw  | Jan 2017 | 100 |
|    CA    | Hardware |   Screw  | Feb 2017 | 50  |
|    CA    | Hardware |   Screw  | Mar 2017 | 75  |
|    CA    | Hardware |    Bolt  | Jan 2017 | 30  |
|    CA    | Hardware |    Bolt  | Feb 2017 | 90  |
|    CA    | Hardware |    Bolt  | Mar 2017 | 50  |

My report needs to look like the following:

|      Hardware      | Screw |  Bolt |
|Current Month Total |  150  |  100  |
|Yearly Total        |  450  |  340  |

I need a way to limit the current month total to ONLY the current month but aggregate the values for the yearly total. I've tried using LAST in the aggregate but you can't. I've tried the following for the current month total aggregate. My Date value is the 1st day of the month and my parameter is the last day of the month, so I needed a way to match the 2 that is why there is the date addition. The jist is to try and match the current month, which is a parameter to the date column:

=iif( DateAdd(dateinterval.Day,-1,DateAdd(dateinterval.Month,1,Fields!Sale_DATE.Value)) = Parameters!ReportingDate.Value, iif(isnothing(sum(Fields!Total.Value)),"",sum(Fields!Total.Value)),sum(0))

but it only works if the query that returns the dataset returns ONLY the current month. If the query returns all of the months in the year it shows 0's. I need a way to filter the cells so they aggregate the values correctly

If I limit my report to only the current month I can't get the yearly aggregate and if I select all of the months I can't get the current month total.

Body:
Actually, using grouping as suggested alone doesn't work. I was already using groups in my matrix. The issue is that I needed a different form of grouping within the same column and I needed to restrict the grouping to different date ranges. My problem was that I had the SUM in the wrong position in my formula.

The expressions for the yearly total should have been:

=Sum(IIF(Fields!ItemName.Value="Screw",Fields!QTY.Value,0))
=Sum(IIF(Fields!ItemName.Value="Bolt",Fields!QTY.Value,0))

Then, based on the dataset, if the current month is "Mar 2017" I can build the expression for Month Total as

=Sum(IIF(Fields!ItemName.Value="Screw" and Fields!Month.Value="Mar 2017",Fields!QTY.Value,0))``
=Sum(IIF(Fields!ItemName.Value="Bolt" and Fields!Month.Value="Mar 2017",Fields!QTY.Value,0))

These examples are using my sample dataset in this question. Since I couldn't hard code dates, wanted to use parameters, and needed to do a calculation this is what I ACTUALLY used:

SUM(iif(DateAdd(dateinterval.Day,-1,DateAdd(dateinterval.Month,1,Fields!REL_DATE.Value))= Parameters!ReportingDate.Value,
Fields!Total_OnTime.Value,0))/SUM(iif(DateAdd(dateinterval.Day,-1,DateAdd(dateinterval.Month,1,Fields!REL_DATE.Value))= Parameters!ReportingDate.Value,
Fields!Total.Value,0))

Hope this helps someone else.


问:
Use behavior in style
I have a behavior ,How can I use it in TextBlock Style so that it gets applied to all TextBlocks.

```<code><TextBlock Grid.Row="0"  Grid.Column="1" Text="{Binding Distance}" >
        <i:Interaction.Behaviors>
            <Behaviors:EmptyToNaBehaviour/>
        </i:Interaction.Behaviors>
</TextBlock>
</code>```

this is my attached behavior which is basically changing the empty value to N/A

```<code> public class EmptyToNaBehaviour : Behavior<TextBlock>
{
    protected override void OnAttached()
    {
        var txtblock = this.AssociatedObject as TextBlock;

        if (txtblock != null && string.IsNullOrEmpty(txtblock.Text))
        {
            txtblock.Text = "N/A";
        }
    }
}
</code>```

答:
There are basically two different ways of implementing behaviours in WPF, commonly referred to as attached behaviours and Blend behaviours.

An attached behaviour is simply an attached property with a PropertyChangedCallback change handler attached to it that performs some action on or extends the DependencyObject to which it is attached when the value of the dependency property changes.

You typically define an attached behaviour as a static class with a set of static methods that get and set the value of the dependency property and perform the desired logic as a result of the callback being invoked. You could easily set the value of any such properties in a Style:

```<code><Setter Property="local:EmptyToNaBehaviour.SomeProperty" Value="x"/>
</code>```

A Blend behaviour provides a better way of encapsulating the functionality of a behaviour compared to an ordinary attached behaviour. They are also more design friendly easily as they can be easily attached to visual elements in the UI via drag-drop functionality in Blend. But I am afraid you cannot really add a Blend behaviour to a Style setter:

How to add a Blend Behavior in a Style Setter

So if you want to be able to apply your behaviour in the context of a Style, you should write an attached behaviour instead of a Blend behaviour.

Edit: Your behaviour is a Blend behaviour. Replace it by an attached behaviour:

```<code>public class EmptyToNaBehaviour
{
    public static string GetText(TextBlock textBlock)
    {
        return (string)textBlock.GetValue(IsBroughtIntoViewWhenSelectedProperty);
    }

    public static void SetText(TextBlock textBlock, string value)
    {
        textBlock.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);
    }

    public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =
        DependencyProperty.RegisterAttached(
        "Text",
        typeof(string),
        typeof(EmptyToNaBehaviour),
        new UIPropertyMetadata(null, OnTextChanged));

    private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBlock txtblock = d as TextBlock;
        if(txtblock != null)
            txtblock.Loaded += Txtblock_Loaded;
    }

    private static void Txtblock_Loaded(object sender, RoutedEventArgs e)
    {
        TextBlock txtblock = sender as TextBlock;
        string text = GetText(txtblock);
        if (txtblock != null && !string.IsNullOrEmpty(text) && string.IsNullOrEmpty(txtblock.Text))
        {
            txtblock.Text = text;
        }
    }
}
</code>```

Usage:

```<code><TextBlock Grid.Row="0"  Grid.Column="1" Text="text"
           Behaviors:EmptyToNaBehaviour.Text="N/A">
</TextBlock>
</code>```

Or in a Style:

```<code><Style x:Key="style" TargetType="TextBlock">
    <Setter Property="Behaviors:EmptyToNaBehaviour.Text" Value="N/A" />
</Style>
</code>```

Title: Use behavior in style

Body:
I have a behavior ,How can I use it in TextBlock Style so that it gets applied to all TextBlocks.

<TextBlock Grid.Row="0"  Grid.Column="1" Text="{Binding Distance}" >

            <Behaviors:EmptyToNaBehaviour/>

</TextBlock>

this is my attached behavior which is basically changing the empty value to N/A

 public class EmptyToNaBehaviour : Behavior<TextBlock>
{
    protected override void OnAttached()
    {
        var txtblock = this.AssociatedObject as TextBlock;

        if (txtblock != null && string.IsNullOrEmpty(txtblock.Text))
        {
            txtblock.Text = "N/A";
        }
    }
}

Body:
There are basically two different ways of implementing behaviours in WPF, commonly referred to as attached behaviours and Blend behaviours.

An attached behaviour is simply an attached property with a PropertyChangedCallback change handler attached to it that performs some action on or extends the DependencyObject to which it is attached when the value of the dependency property changes.

You typically define an attached behaviour as a static class with a set of static methods that get and set the value of the dependency property and perform the desired logic as a result of the callback being invoked. You could easily set the value of any such properties in a Style:

<Setter Property="local:EmptyToNaBehaviour.SomeProperty" Value="x"/>

A Blend behaviour provides a better way of encapsulating the functionality of a behaviour compared to an ordinary attached behaviour. They are also more design friendly easily as they can be easily attached to visual elements in the UI via drag-drop functionality in Blend. But I am afraid you cannot really add a Blend behaviour to a Style setter:

How to add a Blend Behavior in a Style Setter

So if you want to be able to apply your behaviour in the context of a Style, you should write an attached behaviour instead of a Blend behaviour.

Edit: Your behaviour is a Blend behaviour. Replace it by an attached behaviour:

public class EmptyToNaBehaviour
{
    public static string GetText(TextBlock textBlock)
    {
        return (string)textBlock.GetValue(IsBroughtIntoViewWhenSelectedProperty);
    }

    public static void SetText(TextBlock textBlock, string value)
    {
        textBlock.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);
    }

    public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =
        DependencyProperty.RegisterAttached(
        "Text",
        typeof(string),
        typeof(EmptyToNaBehaviour),
        new UIPropertyMetadata(null, OnTextChanged));

    private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBlock txtblock = d as TextBlock;
        if(txtblock != null)
            txtblock.Loaded += Txtblock_Loaded;
    }

    private static void Txtblock_Loaded(object sender, RoutedEventArgs e)
    {
        TextBlock txtblock = sender as TextBlock;
        string text = GetText(txtblock);
        if (txtblock != null && !string.IsNullOrEmpty(text) && string.IsNullOrEmpty(txtblock.Text))
        {
            txtblock.Text = text;
        }
    }
}

Usage:

<TextBlock Grid.Row="0"  Grid.Column="1" Text="text"
           Behaviors:EmptyToNaBehaviour.Text="N/A">
</TextBlock>

Or in a Style:

<Style x:Key="style" TargetType="TextBlock">
    <Setter Property="Behaviors:EmptyToNaBehaviour.Text" Value="N/A" />
</Style>


问:
On logout invalidate flask-JWT
I have generated Flask-JWT token for user authentication, but on logout i want to invalidate token. Now it's allowing to access route after logout.</p>

```<code>@app.route('/logout', methods=['POST'])
@jwt_required
def logout():
    user = current_user
    user.authenticated = False
    db.session.commit()
    logout_user()
    return jsonify({'success': True})
</code>```

答:
As it has already been answered blacklist is one of the basic ways to invalidate JWT tokens. However, it should be noted that the blacklisted tokens should be kept in DB or anywhere else until their expiry date unless you need to keep all tokens for some reason.

Also, it's important to make the time of validity of JWT token as short as possible so that in majority of the cases they will be quickly invalidated by the flask-jwt itself. For example, it might make sense to make expiry time for a token - 30 minutes like a session time-out for some web-sites (definitely not days and months etc).

Title: On logout invalidate flask-JWT

Body:
I have generated Flask-JWT token for user authentication, but on logout i want to invalidate token. Now it's allowing to access route after logout.

@app.route('/logout', methods=['POST'])
@jwt_required
def logout():
    user = current_user
    user.authenticated = False
    db.session.commit()
    logout_user()
    return jsonify({'success': True})


问:
Adding Mutliple Row Effected properly but not Updating (C#, Entity Framework 6)
As you can see below, I'm trying to update the "active" and "version" fields, which are properties of the templateData object.

When I want to add a new record, it works fine and meets the needs. But when I try to update the state.modified line, the error is:

Attaching an entity of type '...' failed because another entity already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Although I have tried many ways of crashing (as you noticed) I have not been successful.

What is the cause of this error? And how can I handle it?

Thank you for your help.

Service:

```<code>public ResultObject<TemplateData> SaveTemplateData(TemplateData oTemplateData)
    {
        var oResult = new ResultObject<TemplateData>();

        using (var contextTransaction = _context.Database.BeginTransaction())
        {
            try
            {
                var listTempDatas = _context.TemplateDatas.Where(td => td.TemplateRID == oTemplateData.TemplateRID)
                    .ToList();

                #region active/version

                oTemplateData.Active = true;

                if (listTempDatas.Count > 0)
                {
                    #region resetActives
                    listTempDatas.ForEach(ltd => ltd.Active = false);
                    #endregion

                    #region getMaxVersion

                    var maxVersionValue = listTempDatas.Max(ltd => ltd.TemplateVersion);
                    //var maxVersionValue2 = listTempDatas.OrderByDescending(ltd => ltd.TemplateVersion).Select(ltd => ltd.TemplateVersion).First();

                    oTemplateData.TemplateVersion = maxVersionValue + 1;

                    #endregion
                }
                else if (listTempDatas.Count == 0)
                {
                    oTemplateData.TemplateVersion = 1;
                }

                #endregion

                if (oTemplateData.ID > 0)
                {
                    var oldTempData = _context.TemplateDatas.AsNoTracking()
                        .FirstOrDefault(td => td.ID == oTemplateData.ID);
                    if (oldTempData != null)
                        _context.Entry(oTemplateData).State = EntityState.Modified;// and there it is
                }
                else if (oTemplateData.ID == 0)
                {
                    _context.Entry(oTemplateData).State = EntityState.Added;
                }

                _context.SaveChanges();

                oResult.ResulObject = oTemplateData;
                contextTransaction.Commit();
            }
            catch (Exception e)
            {
                contextTransaction.Rollback();
                oResult.AddError("TemplateService.SaveTemplateData", e.ToString());
            }
        }

        return oResult;
    }
</code>```

Entity:

```<code>public class TemplateData
{
    ...

    public int ID { get; set; }

    public int? TemplateRID { get; set; }

    ...

    public int? TemplateVersion { get; set; }

    public bool? Active { get; set; }

    ...

    public virtual Template Template { get; set; }
}
</code>```

DataContextExtension:

```<code>public static ApplicationDbContext BulkInsert<T>(this ApplicationDbContext context, T entity, int count,
        int batchSize) where T : class
    {
        context.Set<T>().Add(entity);

        if (count % batchSize == 0)
        {
            context.SaveChanges();
            context.Dispose();
            context = new ApplicationDbContext();

            // This is optional
            context.Configuration.AutoDetectChangesEnabled = false;
        }
        return context;
    }
</code>```

答:
The problem is that the line

```<code>var listTempDatas = _context.TemplateDatas.Where(td => td.TemplateRID == oTemplateData.TemplateRID)
    .ToList();
</code>```

already loads (tracks)  in the context the existing entity you are trying to update.

So first you can try to find it in that list (instead of with a separate database query):

```<code>var oldTempData = listTempDatas.FirstOrDefault(td => td.ID == oTemplateData.ID);
</code>```

and then simply update the properties of the existing entity rather than trying to mark the detached entity as modified:

```<code>if (oldTempData != null)
    _context.Entry(oldTempData).CurrentValues.SetValues(oTemplateData); // and there you go
</code>```

Body:
As you can see below, I'm trying to update the "active" and "version" fields, which are properties of the templateData object.

When I want to add a new record, it works fine and meets the needs. But when I try to update the state.modified line, the error is:

Attaching an entity of type '...' failed because another entity already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Although I have tried many ways of crashing (as you noticed) I have not been successful.

What is the cause of this error? And how can I handle it?

Thank you for your help.

Service:

public ResultObject<TemplateData> SaveTemplateData(TemplateData oTemplateData)
    {
        var oResult = new ResultObject<TemplateData>();

        using (var contextTransaction = _context.Database.BeginTransaction())
        {
            try
            {
                var listTempDatas = _context.TemplateDatas.Where(td => td.TemplateRID == oTemplateData.TemplateRID)
                    .ToList();

                #region active/version

                oTemplateData.Active = true;

                if (listTempDatas.Count > 0)
                {
                    #region resetActives
                    listTempDatas.ForEach(ltd => ltd.Active = false);
                    #endregion

                    #region getMaxVersion

                    var maxVersionValue = listTempDatas.Max(ltd => ltd.TemplateVersion);
                    //var maxVersionValue2 = listTempDatas.OrderByDescending(ltd => ltd.TemplateVersion).Select(ltd => ltd.TemplateVersion).First();

                    oTemplateData.TemplateVersion = maxVersionValue + 1;

                    #endregion
                }
                else if (listTempDatas.Count == 0)
                {
                    oTemplateData.TemplateVersion = 1;
                }

                #endregion

                if (oTemplateData.ID > 0)
                {
                    var oldTempData = _context.TemplateDatas.AsNoTracking()
                        .FirstOrDefault(td => td.ID == oTemplateData.ID);
                    if (oldTempData != null)
                        _context.Entry(oTemplateData).State = EntityState.Modified;// and there it is
                }
                else if (oTemplateData.ID == 0)
                {
                    _context.Entry(oTemplateData).State = EntityState.Added;
                }

                _context.SaveChanges();

                oResult.ResulObject = oTemplateData;
                contextTransaction.Commit();
            }
            catch (Exception e)
            {
                contextTransaction.Rollback();
                oResult.AddError("TemplateService.SaveTemplateData", e.ToString());
            }
        }

        return oResult;
    }

Entity:

public class TemplateData
{
    ...

    public int ID { get; set; }

    public int? TemplateRID { get; set; }

    ...

    public int? TemplateVersion { get; set; }

    public bool? Active { get; set; }

    ...

    public virtual Template Template { get; set; }
}

DataContextExtension:

public static ApplicationDbContext BulkInsert<T>(this ApplicationDbContext context, T entity, int count,
        int batchSize) where T : class
    {
        context.Set<T>().Add(entity);

        if (count % batchSize == 0)
        {
            context.SaveChanges();
            context.Dispose();
            context = new ApplicationDbContext();

            // This is optional
            context.Configuration.AutoDetectChangesEnabled = false;
        }
        return context;
    }

Body:
The problem is that the line

var listTempDatas = _context.TemplateDatas.Where(td => td.TemplateRID == oTemplateData.TemplateRID)
    .ToList();

already loads (tracks)  in the context the existing entity you are trying to update.

So first you can try to find it in that list (instead of with a separate database query):

var oldTempData = listTempDatas.FirstOrDefault(td => td.ID == oTemplateData.ID);

and then simply update the properties of the existing entity rather than trying to mark the detached entity as modified:

if (oldTempData != null)
    _context.Entry(oldTempData).CurrentValues.SetValues(oTemplateData); // and there you go


问:
How to handle default alert when using OpenUrl with tel://2373829239
After running this i am getting alert with two button as call and cancel.
Call button will navigate to dialer pad and place the call which is fine. But i want to perform some action on the click of Cancel button.

Here is my code.

enter image description here

```<code>NSString *urlString = [NSString stringWithFormat:@"tel:123"];
NSString *escaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:escaped]];
</code>```

答:
From the above comments i got the answer.
   //For iPhone use this:</p>

```<code>        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]])
        {

            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]] options:@{} completionHandler:^(BOOL success)
            {
                {
                    if (success)
                    {
                        NSLog(@"inside call clikced");
                    }
                    else
                    {
                        NSLog(@"inside cancel clicked");
                    }
                }
            }];
        }

   // For iPad use this:

 CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier1 = [info subscriberCellularProvider];

    if (carrier1.mobileCountryCode.length == 0 || carrier1.mobileCountryCode.length == nil)
{
// false for iPad Air 2(which doesn't have cellular Provider)
}
</code>```

Body:
After running this i am getting alert with two button as call and cancel.
Call button will navigate to dialer pad and place the call which is fine. But i want to perform some action on the click of Cancel button.

Here is my code.

enter image description here

NSString *urlString = [NSString stringWithFormat:@"tel:123"];
NSString *escaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:escaped]];

Body:
From the above comments i got the answer.
   //For iPhone use this:

        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]])
        {

            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]] options:@{} completionHandler:^(BOOL success)
            {
                {
                    if (success)
                    {
                        NSLog(@"inside call clikced");
                    }
                    else
                    {
                        NSLog(@"inside cancel clicked");
                    }
                }
            }];
        }

   // For iPad use this:

 CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier1 = [info subscriberCellularProvider];

    if (carrier1.mobileCountryCode.length == 0 || carrier1.mobileCountryCode.length == nil)
{
// false for iPad Air 2(which doesn't have cellular Provider)
}


问:
Passing a variable to a form in Edge Animate
I need to pass a variable to a form from Edge Animate.
I have the following instruction:

```<code>sym.$("form").append('<iframe width="100%" height="100%" src="login_PRA.php?v_id="vidn frameborder="0" scrolling="no"></iframe>');
</code>```

vidn is a variable but used as I did it has passed as a value
so when I need to access the value contained by the variable vidn
I just get "vidn". Please can you help me to write correctly instruction?

答:
I've found the correct solution and I had already posted it yesterday and I don't know why I can't see it here. the correct solution is: </p>

```<code>sym.$("form").append('<iframe width="100%" height="100%" src="login_PRA.php?v_id=' + vidn + '" frameborder="0" scrolling="no"></iframe>');
</code>```

Body:
I need to pass a variable to a form from Edge Animate.
I have the following instruction:

sym.$("form").append('');

vidn is a variable but used as I did it has passed as a value
so when I need to access the value contained by the variable vidn
I just get "vidn". Please can you help me to write correctly instruction?

Body:
I've found the correct solution and I had already posted it yesterday and I don't know why I can't see it here. the correct solution is:

sym.$("form").append('<iframe width="100%" height="100%" src="login_PRA.php?v_id=' + vidn + '" frameborder="0" scrolling="no"></iframe>');


问:
Is there a way to alias tmux commands?
tmux has a command mode that can be accessed via C-b : and I'm wondering if there is a way to alias commands in my .tmux.conf file like split-window to something I use more often like vsp in vim.

I know I can bind keyboard shortcuts with bind but can I alias commands as well?

答:
You can use bind. Here is an example alias for turning mouse-mode on and off:

```<code>bind m \
    set -g mode-mouse on \;\
    set -g mouse-resize-pane on \;\
    set -g mouse-select-pane on \;\
    set -g mouse-select-window on \;\
    display 'Mouse mode ON'

bind M \
    set -g mode-mouse off \;\
    set -g mouse-resize-pane off \;\
    set -g mouse-select-pane off \;\
    set -g mouse-select-window off \;\
    display 'Mouse mode OFF'
</code>```

Now you can easily use Ctrl+B m to turn it on, and Ctrl+B M to turn it off (assuming Ctrl+B is your prefix)

Title: Is there a way to alias tmux commands?

Body:
You can use bind. Here is an example alias for turning mouse-mode on and off:

bind m \
    set -g mode-mouse on \;\
    set -g mouse-resize-pane on \;\
    set -g mouse-select-pane on \;\
    set -g mouse-select-window on \;\
    display 'Mouse mode ON'

bind M \
    set -g mode-mouse off \;\
    set -g mouse-resize-pane off \;\
    set -g mouse-select-pane off \;\
    set -g mouse-select-window off \;\
    display 'Mouse mode OFF'

Now you can easily use Ctrl+B m to turn it on, and Ctrl+B M to turn it off (assuming Ctrl+B is your prefix)


问:
Improving the readability of the scatterplot in ggpairs, ggplot
I am using the Auto dataset from the ISLR library and the function ggpairs() from gpairs library to create a scatterplot of all possible combinations of variables.  My code is the following:

```<code>data(Auto)
setDT(Auto)
ggpairs(Auto[, -c("name"), with = FALSE] ,
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
                     combo = wrap("box", color = "orange", alpha = 0.3),
                     discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
                    diag = list(continuous = wrap("densityDiag",  color = "blue", alpha = 0.5) ))+
     theme(axis.text.x = element_text(angle = 90, hjust = 1))
</code>```

The plot is the one below:

There are some issues with this plot:

The axes tick labels are not readable.  How could I remove the numbers and possibly rotate the tick lables to be vertical to the axes?

How could I enforce different colors for the combo pairs (categorical - continuous)

Your advice will be appreciated.

答:
Very tricky stuff, the comb wrapper uses factor levels as input to change colors (as shown in the example by @KoenV) and not discrete which is a bit of a misnomer. Changing the class however changes the upper/diag part.

The only alternative I found was manually changing plots using putPlot.

```<code># remove ticks (I don't get labels when plotting it)

p = ggpairs(Auto[, -c("name"), with = FALSE] ,
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
                     combo = wrap("box", color = "orange", alpha = 0.3),
                     discrete = wrap("facetbar", color = "yellow", alpha = 0.3)),
        diag = list(continuous = wrap("densityDiag",  color = "blue", alpha = 0.5) ))+
        theme(axis.text = element_blank(),axis.ticks = element_blank())
</code>```

And change a individual plot and adding a boxplot/ + color (perhaps loop over the desired plots

```<code>cp = ggplot(Auto) +
  geom_boxplot(aes(as.factor(cylinders), mpg),color="orange")
putPlot(p, cp, 2,1)
</code>```

Body:
I am using the Auto dataset from the ISLR library and the function ggpairs() from gpairs library to create a scatterplot of all possible combinations of variables.  My code is the following:

data(Auto)
setDT(Auto)
ggpairs(Auto[, -c("name"), with = FALSE] ,
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
                     combo = wrap("box", color = "orange", alpha = 0.3),
                     discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
                    diag = list(continuous = wrap("densityDiag",  color = "blue", alpha = 0.5) ))+
     theme(axis.text.x = element_text(angle = 90, hjust = 1))

The plot is the one below:

There are some issues with this plot:

The axes tick labels are not readable.  How could I remove the numbers and possibly rotate the tick lables to be vertical to the axes?

How could I enforce different colors for the combo pairs (categorical - continuous)

Your advice will be appreciated.

Body:
Very tricky stuff, the comb wrapper uses factor levels as input to change colors (as shown in the example by @KoenV) and not discrete which is a bit of a misnomer. Changing the class however changes the upper/diag part.

The only alternative I found was manually changing plots using putPlot.

# remove ticks (I don't get labels when plotting it)

p = ggpairs(Auto[, -c("name"), with = FALSE] ,
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
                     combo = wrap("box", color = "orange", alpha = 0.3),
                     discrete = wrap("facetbar", color = "yellow", alpha = 0.3)),
        diag = list(continuous = wrap("densityDiag",  color = "blue", alpha = 0.5) ))+
        theme(axis.text = element_blank(),axis.ticks = element_blank())

And change a individual plot and adding a boxplot/ + color (perhaps loop over the desired plots

cp = ggplot(Auto) +
  geom_boxplot(aes(as.factor(cylinders), mpg),color="orange")
putPlot(p, cp, 2,1)


问:
Help with Delphi 7, ADO, & MS Access SQL Statement
I have three tables (in a MS Access Database 2000 file *.mdb)

Knowledge

id

question

answer

Knowledge_Keywords

id

knowledgeid

keywordsid

Keywords

id

keyword

Need to get all the keywords for a knowledge

Select distinct keyword from keywords KW

Join knowledge_keywords KKW on KKW.keywordid = KW.id

Join Knowledge K on K.id = KKW.knowledgeid

Where k.id =  10

of course 10 is a example, i actually use a parameter there

Where k.id = :AKnowId';

and fill it in in code

qry.Parameters.ParamByName('AKnowId').Value:= AKnowledgeId;

anyway, i think the SQL is qrong, any help would be greatly appreciated

答: Get the SQL working properly within Access itself (make a query, try your SQL, see if it returns anything). THEN worry about Delphi.</p>

ContentLicense: CC BY-SA 2.5


问:
how to download image / files from ftp server via url in android?
```<code>   private String ftpUrl = "ftp://%s:%s@%s/%s;";
   private static String host = "www.krishnas.com.np";
   private static String user = "tryagn@krishnas.com.np";
   private static String pass = "technology_krixnas";
   private static String filePath = "112.jpg";

   private static String savePath =
   Environment.getExternalStorageDirectory() + "/" +
   Environment.DIRECTORY_DCIM +"/abe.jpg";
</code>```

My doInBackground() in asynctask is:

```<code>   protected String doInBackground(String... f_url) {
    int count;
    try {

    ftpUrl = String.format(ftpUrl, user, pass, host, filePath);

        //System.out.println("URL: " + ftpUrl)
                Log.d("-----------", ""+ftpUrl);

   //            try {
            //URL url = new URL(ftpUrl);
            //URLConnection conn = url.openConnection();
     //                InputStream inputStream = conn.getInputStream();

        URL url = new URL(f_url[0]);
        URLConnection conection = url.openConnection();
        conection.connect();
        // this will be useful so that you can show a tipical 0-100% progress bar
        int lenghtOfFile = conection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream
        OutputStream output = new FileOutputStream(savePath);

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            i=(int)((total*100)/lenghtOfFile);
            publishProgress(""+(int)((total*100)/lenghtOfFile));

   //                i = (int)((total*100)/lenghtOfFile);

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // c
        // losing streams
        output.close();
        input.close();

    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

    return null;
    }
</code>```

I want to download a file/image from my FTP server, it shows image in link but does not download in internal storage. I am learning ftp server downloader not the http request!! Don't know where it goes wrong??

答:
You are using external storage to store file Environment.getExternalStorageDirectory()

So if you want to store it in internal storage,
You can use getFilesDir() or getCacheDir():

```<code>File file = new File(context.getFilesDir(), filename);
</code>```

For more Information refer this link:

Body:
   private String ftpUrl = "ftp://%s:%s@%s/%s;";
   private static String host = "www.krishnas.com.np";
   private static String user = "tryagn@krishnas.com.np";
   private static String pass = "technology_krixnas";
   private static String filePath = "112.jpg";

   private static String savePath =
   Environment.getExternalStorageDirectory() + "/" +
   Environment.DIRECTORY_DCIM +"/abe.jpg";

My doInBackground() in asynctask is:

   protected String doInBackground(String... f_url) {
    int count;
    try {

    ftpUrl = String.format(ftpUrl, user, pass, host, filePath);

        //System.out.println("URL: " + ftpUrl)
                Log.d("-----------", ""+ftpUrl);

   //            try {
            //URL url = new URL(ftpUrl);
            //URLConnection conn = url.openConnection();
     //                InputStream inputStream = conn.getInputStream();

        URL url = new URL(f_url[0]);
        URLConnection conection = url.openConnection();
        conection.connect();
        // this will be useful so that you can show a tipical 0-100% progress bar
        int lenghtOfFile = conection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream
        OutputStream output = new FileOutputStream(savePath);

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            i=(int)((total*100)/lenghtOfFile);
            publishProgress(""+(int)((total*100)/lenghtOfFile));

   //                i = (int)((total*100)/lenghtOfFile);

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // c
        // losing streams
        output.close();
        input.close();

    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

    return null;
    }

I want to download a file/image from my FTP server, it shows image in link but does not download in internal storage. I am learning ftp server downloader not the http request!! Don't know where it goes wrong??

Body:
You are using external storage to store file Environment.getExternalStorageDirectory()

So if you want to store it in internal storage,
You can use getFilesDir() or getCacheDir():

File file = new File(context.getFilesDir(), filename);

For more Information refer this link:


问:
MongoDB Stored Procedure Equivalent
I have a large CSV file containing a list of stores, in which one of the field is ZipCode.
I have a separate MongoDB database called ZipCodes, which stores the latitude and longitude for any given zip code.

In SQL Server, I would execute a stored procedure called InsertStore which would do a look up on the ZipCodes table to get corresponding latitude and longitude and insert the data into the Stores table.

Is there something similar to the concept of stored procedures in MongoDB for this?
Basically, for each insert I need to look up the latitude and longitude for that store and save that as well.

I am not too familiar with the concept of Map/Reduce, but would that be relevant here?
Thank you!

答:
NOTE that according to the reference:

Do not store application logic in the database. There are performance
  limitations to running JavaScript inside of MongoDB. Application code
  also is typically most effective when it shares version control with
  the application itself.

So there is not any equivalent for stored procedure in mongodb.

Title: MongoDB Stored Procedure Equivalent


问:
How to get cURL information
I have a cURL script that makes connection to a page:

```<code><?php
// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "example.com");

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);
?>
</code>```

And that page gives an output like:

```<code>{
  "status" : "fail",
  "data" : {
    "error_message" : "Destination address 37428963298746238 is invalid for Network=BTC."
  }
}
</code>```

How do I get "error_message" to $error_message with PHP?

答:
This might help you: Pass your output to json_decode

```<code><?php

$json = '{
  "status" : "fail",
  "data" : {
    "error_message" : "Destination address 37428963298746238 is invalid for Network=BTC."
  }
}';

$obj = json_decode($json);

foreach($obj as $value){

echo $value->error_message;

}

?>
</code>```

http://codepad.org/hiDYWlxR

Title: How to get cURL information

Body:
I have a cURL script that makes connection to a page:

<?php
// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "example.com");

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);
?>

And that page gives an output like:

{
  "status" : "fail",
  "data" : {
    "error_message" : "Destination address 37428963298746238 is invalid for Network=BTC."
  }
}

How do I get "error_message" to $error_message with PHP?

Body:
This might help you: Pass your output to json_decode

<?php

$json = '{
  "status" : "fail",
  "data" : {
    "error_message" : "Destination address 37428963298746238 is invalid for Network=BTC."
  }
}';

$obj = json_decode($json);

foreach($obj as $value){

echo $value->error_message;

}

?>

http://codepad.org/hiDYWlxR


问:
And condition for jQuery doesn't work
I am developing a multipage form. I am trying to write an if condition:

```<code>$('.next').click(function() {
    if ($('input[required]:visible').each().val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});
</code>```

jsFiddle

This works fine with input type=text. Then I am trying to add the same condition for <textarea>:

```<code>$('.next').click(function() {
    if ($('input[required]:visible').val() == false && $('textarea[required]:visible').val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});
</code>```

jsFiddle for this

Now it requires textarea OR input to be filled, but should work with both, shouldn't it? What am I doing wrong?

答:
jQuery .val() gives you the content of Textbox or Textarea, not Boolean. So you can use jQuery .trim().length. It will first remove the white space and then it counts the length of Textbox or Textarea.This ensures that even space is there, it will work. Working fiddle

```<code>$('.next').click(function(){

    if($('input[required]:visible').val().trim().length==0 || $('textarea[required]:visible').val().trim().length==0) {
        alert('Not all required fields are filled');
    }
    else{
         alert('All required fields are filled');
    }
});
</code>```

Title: And condition for jQuery doesn't work

Body:
I am developing a multipage form. I am trying to write an if condition:

$('.next').click(function() {
    if ($('input[required]:visible').each().val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});

jsFiddle

This works fine with input type=text. Then I am trying to add the same condition for <textarea>:

$('.next').click(function() {
    if ($('input[required]:visible').val() == false && $('textarea[required]:visible').val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});

jsFiddle for this

Now it requires textarea OR input to be filled, but should work with both, shouldn't it? What am I doing wrong?

Body:
jQuery .val() gives you the content of Textbox or Textarea, not Boolean. So you can use jQuery .trim().length. It will first remove the white space and then it counts the length of Textbox or Textarea.This ensures that even space is there, it will work. Working fiddle

$('.next').click(function(){

    if($('input[required]:visible').val().trim().length==0 || $('textarea[required]:visible').val().trim().length==0) {
        alert('Not all required fields are filled');
    }
    else{
         alert('All required fields are filled');
    }
});


问:
Get the name of instance as string in Javascript
Im working with Three.js and javascript.
When my code executes this:

```<code>console.log(this.scene.children[1])
</code>```

I get this in my console of Chrome:

How can I get the name of the object ('WidgetsRuler') as a string?
I dont see any attribute that saves this information.

答:
I believe you should be able to use prototype to achieve this:

```<code>Object.prototype.toString
</code>```

eg:

```<code>Console.Log(this.scene.children[1].prototype.toString())
</code>```

Failing that, you can try constructor:

```<code>console.log(this.scene.children[1].constructor.name)
</code>```

Body:
Im working with Three.js and javascript.
When my code executes this:

console.log(this.scene.children[1])

I get this in my console of Chrome:

How can I get the name of the object ('WidgetsRuler') as a string?
I dont see any attribute that saves this information.

Body:
I believe you should be able to use prototype to achieve this:

Object.prototype.toString

eg:

Console.Log(this.scene.children[1].prototype.toString())

Failing that, you can try constructor:

console.log(this.scene.children[1].constructor.name)


问:
Replacing outlier with second minimum value group by in R
I am new to R, I have a data.table dt

```<code>> library(data.table)
> dt <- data.table(A = c(1,2,3,4,74,6, 7, 8, 9, 75, 11, 12),
+                  B=c("P","P","P","P", "P", "P" ,"Q","Q","Q", "Q", "Q", "Q"),
+                  C=c("a","b","c","d","e","f", "g", "h", "i", "j", "k", "l"))
> dt
     A B C
 1:  1 P a
 2:  2 P b
 3:  3 P c
 4:  4 P d
 5: 74 P e
 6:  6 P f
 7:  7 Q g
 8:  8 Q h
 9:  9 Q i
 10: 75 Q j
 11: 11 Q k
 12: 12 Q l
</code>```

I computed the outlier in the values of A, with standard deviation using following

```<code>> #Outlier Identification by customer_count
> dt[,out := ifelse((A > (mean(A)+2*sd(A))|A < (mean(A)-2*sd(A))),1,0) ]
> dt
     A B C out
 1:  1 P a   0
 2:  2 P b   0
 3:  3 P c   0
 4:  4 P d   0
 5: 74 P e   1
 6:  6 P f   0
 7:  7 Q g   0
 8:  8 Q h   0
 9:  9 Q i   0
10: 75 Q j   1
11: 11 Q k   0
12: 12 Q l   0
</code>```

The column "out" indicates my outlier, Now I want to replace that outlier value in A, with the second minimum value by each group by "B". How can I do this.

My final outcome should look like:

```<code>> dt
     A B C out
 1:  1 P a   0
 2:  2 P b   0
 3:  3 P c   0
 4:  4 P d   0
 5:  2 P e   1
 6:  6 P f   0
 7:  7 Q g   0
 8:  8 Q h   0
 9:  9 Q i   0
10:  8 Q j   1
11: 11 Q k   0
12: 12 Q l   0
</code>```

Body:
I am new to R, I have a data.table dt

> library(data.table)
> dt <- data.table(A = c(1,2,3,4,74,6, 7, 8, 9, 75, 11, 12),
+                  B=c("P","P","P","P", "P", "P" ,"Q","Q","Q", "Q", "Q", "Q"),
+                  C=c("a","b","c","d","e","f", "g", "h", "i", "j", "k", "l"))
> dt
     A B C
 1:  1 P a
 2:  2 P b
 3:  3 P c
 4:  4 P d
 5: 74 P e
 6:  6 P f
 7:  7 Q g
 8:  8 Q h
 9:  9 Q i
 10: 75 Q j
 11: 11 Q k
 12: 12 Q l

I computed the outlier in the values of A, with standard deviation using following

> #Outlier Identification by customer_count
> dt[,out := ifelse((A > (mean(A)+2*sd(A))|A < (mean(A)-2*sd(A))),1,0) ]
> dt
     A B C out
 1:  1 P a   0
 2:  2 P b   0
 3:  3 P c   0
 4:  4 P d   0
 5: 74 P e   1
 6:  6 P f   0
 7:  7 Q g   0
 8:  8 Q h   0
 9:  9 Q i   0
10: 75 Q j   1
11: 11 Q k   0
12: 12 Q l   0

The column "out" indicates my outlier, Now I want to replace that outlier value in A, with the second minimum value by each group by "B". How can I do this.

My final outcome should look like:

> dt
     A B C out
 1:  1 P a   0
 2:  2 P b   0
 3:  3 P c   0
 4:  4 P d   0
 5:  2 P e   1
 6:  6 P f   0
 7:  7 Q g   0
 8:  8 Q h   0
 9:  9 Q i   0
10:  8 Q j   1
11: 11 Q k   0
12: 12 Q l   0

Body:
We can do with replace

dt[, A := replace(A, out ==1, sort(A)[2]) , by = B]
dt
#     A B C out
# 1:  1 P a   0
# 2:  2 P b   0
# 3:  3 P c   0
# 4:  4 P d   0
# 5:  2 P e   1
# 6:  6 P f   0
# 7:  7 Q g   0
# 8:  8 Q h   0
# 9:  9 Q i   0
#10:  8 Q j   1
#11: 11 Q k   0
#12: 12 Q l   0

Or another option is

dt[, A := pmax((out==1)*sort(A)[2], (out==0)*A), B]


问:
Parse plain email address into 2 parts
How do I get the username and the domain from an email address of:

```<code>string email = "hello@example.com";
//Should parse into:
string username = "hello";
string domain = "example.com";
</code>```

I'm seeking the shortest code to do this, not necessarily efficient.

Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.

答:
Use the MailAddress class

```<code>MailAddress addr = new MailAddress("hello@site.example");
string username = addr.User;
string domain = addr.Host;
</code>```

This method has the benefit of also parsing situations like this (and others you may not be expecting):

```<code>MailAddress addr = new MailAddress("\"Mr. Hello\" <hello@site.example>");
string username = addr.User;
string host = addr.Host;
</code>```

In both cases above:

```<code>Debug.Assert(username.Equals("hello"));
Debug.Assert(host.Equals("site.example"));
</code>```

At the top of your file with the rest of your using directives add:

```<code>using System.Net.Mail;
</code>```

Title: Parse plain email address into 2 parts

Body:
How do I get the username and the domain from an email address of:

string email = "hello@example.com";
//Should parse into:
string username = "hello";
string domain = "example.com";

I'm seeking the shortest code to do this, not necessarily efficient.

Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.

Body:
Use the MailAddress class

MailAddress addr = new MailAddress("hello@site.example");
string username = addr.User;
string domain = addr.Host;

This method has the benefit of also parsing situations like this (and others you may not be expecting):

MailAddress addr = new MailAddress("\"Mr. Hello\" <hello@site.example>");
string username = addr.User;
string host = addr.Host;

In both cases above:

Debug.Assert(username.Equals("hello"));
Debug.Assert(host.Equals("site.example"));

At the top of your file with the rest of your using directives add:

using System.Net.Mail;


问:
How can i make database connection open in JDBCTemplate spring 4
I am using JDBCTemplate in spring4 for executing select query which returns a Blob object. Now i am trying to convert Blob object into string using following code

```<code>Blob image;
ImageScanningBean imageScanningBean = new ImageScanningBean();
image = rs.getBlob("IMAGEOUT");
StringBuffer strOut = new StringBuffer();
try
{
    String aux;
   BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));
   while ((aux=br.readLine())!=null)
   {
        strOut.append(aux);
   }
   strOut.toString();
   imageScanningBean.setImageOutBase64(strOut.toString());
}
 catch(Exception e){
   e.printStackTrace();
}
</code>```

But i am getting error at following line as Connection Closed

```<code>BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));
</code>```

How can i make database connection open in JDBCTemplate

答:
Before i have used queryForObject() which automatically closes the connection when operation is done
    bean = jdbcTemplate.queryForObject("select * from tablename", new Object[]{tokenId,tellerId},new BeanPropertyRowMapper(TokenDetailsBean.class));

So to keep connection alive i have just added  mapRow()

```<code>try
    {
        imageScanningBean = jdbcTemplate.queryForObject("select * from tablename", new Object[]{imageScanningBean.getTellerId()},new BeanPropertyRowMapper<ImageScanningBean>(){
            public ImageScanningBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                Blob image;
                ImageScanningBean imageScanningBean = new ImageScanningBean();
                image = rs.getBlob("IMAGEOUT");
                StringBuffer strOut = new StringBuffer();
                try
                {
                    String aux;
                    BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));
                    while ((aux=br.readLine())!=null)
                    {
                        strOut.append(aux);
                    }
                    strOut.toString();
                    imageScanningBean.setImageOutBase64(strOut.toString());
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
                return imageScanningBean;
            }
        });
    }
    catch(EmptyResultDataAccessException er)
    {
        er.printStackTrace();
        return imageScanningBean;
    }
</code>```

Body:
I am using JDBCTemplate in spring4 for executing select query which returns a Blob object. Now i am trying to convert Blob object into string using following code

Blob image;
ImageScanningBean imageScanningBean = new ImageScanningBean();
image = rs.getBlob("IMAGEOUT");
StringBuffer strOut = new StringBuffer();
try
{
    String aux;
   BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));
   while ((aux=br.readLine())!=null)
   {
        strOut.append(aux);
   }
   strOut.toString();
   imageScanningBean.setImageOutBase64(strOut.toString());
}
 catch(Exception e){
   e.printStackTrace();
}

But i am getting error at following line as Connection Closed

BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));

How can i make database connection open in JDBCTemplate

Body:
Before i have used queryForObject() which automatically closes the connection when operation is done
    bean = jdbcTemplate.queryForObject("select * from tablename", new Object[]{tokenId,tellerId},new BeanPropertyRowMapper(TokenDetailsBean.class));

So to keep connection alive i have just added  mapRow()

try
    {
        imageScanningBean = jdbcTemplate.queryForObject("select * from tablename", new Object[]{imageScanningBean.getTellerId()},new BeanPropertyRowMapper<ImageScanningBean>(){
            public ImageScanningBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                Blob image;
                ImageScanningBean imageScanningBean = new ImageScanningBean();
                image = rs.getBlob("IMAGEOUT");
                StringBuffer strOut = new StringBuffer();
                try
                {
                    String aux;
                    BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));
                    while ((aux=br.readLine())!=null)
                    {
                        strOut.append(aux);
                    }
                    strOut.toString();
                    imageScanningBean.setImageOutBase64(strOut.toString());
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
                return imageScanningBean;
            }
        });
    }
    catch(EmptyResultDataAccessException er)
    {
        er.printStackTrace();
        return imageScanningBean;
    }


问:
In Angular 2 reactive form doesn't update values using ngModel and formArrayName
I have a simple Reactive Form in Angular 2 and my form doesn't detect change of cells of a primeng data table. The html is:

```<code><form [formGroup]="myForm" novalidate (ngSubmit)="onSubmit()">
<p-dataTable [value]="dataMenu" [editable]="true" formArrayName="menu">
    <p-column field="menu" header="Menu"></p-column>
    <p-column field="price" header="Price" [editable]="true">
        <template let-row="rowData" let-i="rowIndex" pTemplate="body">
            {{row.price}}
        </template>
        <template let-row="rowData" let-i="rowIndex" pTemplate="editor">
            <input type="number" pInputText [(ngModel)]="row.price" name="test" [ngModelOptions]="{standalone: true}"/>
        </template>
    </p-column>
</p-dataTable>
</code>```

and the .ts file is:

```<code>this.myForm = this.fb.group( { //fb is FormBuilder
    menu: this.fb.array([]),
});

this.setDataMenu(this.dataMenu);
...
setDataMenu( menu: Array<any> ) {
    const control = <FormArray>this.myForm.controls['menu'];
    for ( let m of menu ) {
        control.push( this.fb.control(m, validatePrices) );
    }
}

function validatePrices( c: FormControl ) {

    return ( c.value != null && c.value.price) ? null : {
        validatePrices: {
            valid: false
        }
    };
}
</code>```

The problem is that the validation fires only at the beginning and when the value of "dataMenu" changes, the form does not detect this change.

答:
Not sure why you would want to use two-way binding, [(ngModel)] with Reactive Forms?

You should use the formControlName attribute with your input tag.

Example :

Create your form

```<code>this.myForm = this.fb.group( { //fb is FormBuilder
    menu: this.fb.array([]),
});
</code>```

Subscribe to the formGroup or individual controls to listen for values.

```<code>this.myForm.get('menu').valueChanges(val => this.menuValue = val);
</code>```

In your template make this simple change.

```<code><input type="number" pInputText formControlName="menu" name="test" [ngModelOptions]="{standalone: true}"/>
</code>```

As you can see I have removed [(ngModel)] and added formControlName instead.

Validation

You can then easily validate changes made to the controls. One simple method would be to just pass the val returned from the subscription callback into a validation method.

The preferred approach would be to use ValidatorFn though

Body:
I have a simple Reactive Form in Angular 2 and my form doesn't detect change of cells of a primeng data table. The html is:

<form [formGroup]="myForm" novalidate (ngSubmit)="onSubmit()">

        <template let-row="rowData" let-i="rowIndex" pTemplate="body">
            {{row.price}}
        </template>
        <template let-row="rowData" let-i="rowIndex" pTemplate="editor">
            <input type="number" pInputText [(ngModel)]="row.price" name="test" [ngModelOptions]="{standalone: true}"/>
        </template>

and the .ts file is:

this.myForm = this.fb.group( { //fb is FormBuilder
    menu: this.fb.array([]),
});

this.setDataMenu(this.dataMenu);
...
setDataMenu( menu: Array<any> ) {
    const control = <FormArray>this.myForm.controls['menu'];
    for ( let m of menu ) {
        control.push( this.fb.control(m, validatePrices) );
    }
}

function validatePrices( c: FormControl ) {

    return ( c.value != null && c.value.price) ? null : {
        validatePrices: {
            valid: false
        }
    };
}

The problem is that the validation fires only at the beginning and when the value of "dataMenu" changes, the form does not detect this change.

Body:
Not sure why you would want to use two-way binding, [(ngModel)] with Reactive Forms?

You should use the formControlName attribute with your input tag.

Example :

Create your form

this.myForm = this.fb.group( { //fb is FormBuilder
    menu: this.fb.array([]),
});

Subscribe to the formGroup or individual controls to listen for values.

this.myForm.get('menu').valueChanges(val => this.menuValue = val);

In your template make this simple change.

<input type="number" pInputText formControlName="menu" name="test" [ngModelOptions]="{standalone: true}"/>

As you can see I have removed [(ngModel)] and added formControlName instead.

Validation

You can then easily validate changes made to the controls. One simple method would be to just pass the val returned from the subscription callback into a validation method.

The preferred approach would be to use ValidatorFn though


问:
Text Selection is not working on Single Cell - ng2-table
Here is Data Table for angular2, written by Valor software.

http://valor-software.com/ng2-table/

And this is Demo.

I tried to select text in single cell by mouse click and drag (!important - inside single cell. on multiple cell is working)
It was working on Chrome and not working on Mozila FireFox. But now its is not works on Chrome too.

Further information is below.

```<code><tr *ngFor="let row of rows">
   <td (click)="cellClick(row, column.name)" *ngFor="let column of columns" [innerHtml]="sanitize(getData(row, column.name))"></td>
</tr>

public cellClick(row:any, column:any):void {
   this.cellClicked.emit({row, column});
}
</code>```

This is the function for table cell clicked.
User mouse down, and mouse move, and finally mouseup.
At this time, this function is triggered and selection is disappearing.

Please help me to solve this issue.

答:
I solved this issue by updating this part.

```<code><td (click)="cellClick(row, column.name)" *ngFor="let column of columns" [innerHtml]="getData(row, column.name)"></td>
</code>```

It was using Sanitize for building html inline code.

Body:
Here is Data Table for angular2, written by Valor software.

http://valor-software.com/ng2-table/

And this is Demo.

I tried to select text in single cell by mouse click and drag (!important - inside single cell. on multiple cell is working)
It was working on Chrome and not working on Mozila FireFox. But now its is not works on Chrome too.

Further information is below.

public cellClick(row:any, column:any):void {
   this.cellClicked.emit({row, column});
}

This is the function for table cell clicked.
User mouse down, and mouse move, and finally mouseup.
At this time, this function is triggered and selection is disappearing.

Please help me to solve this issue.

Body:
I solved this issue by updating this part.

<td (click)="cellClick(row, column.name)" *ngFor="let column of columns" [innerHtml]="getData(row, column.name)"></td>

It was using Sanitize for building html inline code.


问:
Realistic use case for cursors?
I read both the Microsoft Docs and this article. I however can't seem to find where I could only use cursors and not something else so I'd appreciate If someone could give a few examples.

I also came across this answer on stackoverflow and Jeffrey Hantin gave me more doubts.

答:
I find I only ever use cursors for administration tasks. For example I have a script that runs through my high activity large tables. That rebuilds the indexes overnight that query itself is pretty set based. However I have multiple customer databases on the same box with the same structure. I would wrap the maintenance script in a cursor that pulls out the database names and loops through them.

I find this reduces the amount of work I have to do, as the list of databases to work through is generated by the cursor. If I add customers/ delete customers the maintenance is unaffected. If I run up a new box I can add that as part of the set up process so when I get round to setting up a customer system on the new box it is automatically being maintained.

Here is a sample of somebody using the same concept to backup all of their databases. https://www.mssqltips.com/sqlservertip/1070/simple-script-to-backup-all-sql-server-databases/

Same benefits that I've mentioned in that it is defined once and whether you add remove or move databases they are already automatically in the backup plan

Title: Realistic use case for cursors?


问:
How to properly mask a numpy 2D array?
Say I have a two dimensional array of coordinates that looks something like

x = array([[1,2],[2,3],[3,4]])

Previously in my work so far, I generated a mask that ends up looking something like

mask = [False,False,True]

When I try to use this mask on the 2D coordinate vector, I get an error

```<code>newX = np.ma.compressed(np.ma.masked_array(x,mask))

>>>numpy.ma.core.MaskError: Mask and data not compatible: data size
   is 6, mask size is 3.`
</code>```

which makes sense, I suppose. So I tried to simply use the following mask instead:

```<code>mask2 = np.column_stack((mask,mask))
newX = np.ma.compressed(np.ma.masked_array(x,mask2))
</code>```

And what I get is close:

>>>array([1,2,2,3])

to what  I would expect (and want):

>>>array([[1,2],[2,3]])

There must be an easier way to do this?

答:
Since none of these solutions worked for me, I thought to write down what solution did, maybe it will useful for somebody else. I use python 3.x and I worked on two 3D arrays. One, which I call data_3D contains float values of recordings in a brain scan, and the other, template_3D contains integers which represent regions of the brain. I wanted to choose those values from data_3D corresponding to an integer region_code as per template_3D:

```<code>my_mask = np.in1d(template_3D, region_code).reshape(template_3D.shape)
data_3D_masked = data_3D[my_mask]
</code>```

which gives me a 1D array of only relevant recordings.

Title: How to properly mask a numpy 2D array?

Body:
Say I have a two dimensional array of coordinates that looks something like

x = array([[1,2],[2,3],[3,4]])

Previously in my work so far, I generated a mask that ends up looking something like

mask = [False,False,True]

When I try to use this mask on the 2D coordinate vector, I get an error

newX = np.ma.compressed(np.ma.masked_array(x,mask))

>>>numpy.ma.core.MaskError: Mask and data not compatible: data size
   is 6, mask size is 3.`

which makes sense, I suppose. So I tried to simply use the following mask instead:

mask2 = np.column_stack((mask,mask))
newX = np.ma.compressed(np.ma.masked_array(x,mask2))

And what I get is close:

>>>array([1,2,2,3])

to what  I would expect (and want):

>>>array([[1,2],[2,3]])

There must be an easier way to do this?

Body:
Since none of these solutions worked for me, I thought to write down what solution did, maybe it will useful for somebody else. I use python 3.x and I worked on two 3D arrays. One, which I call data_3D contains float values of recordings in a brain scan, and the other, template_3D contains integers which represent regions of the brain. I wanted to choose those values from data_3D corresponding to an integer region_code as per template_3D:

my_mask = np.in1d(template_3D, region_code).reshape(template_3D.shape)
data_3D_masked = data_3D[my_mask]

which gives me a 1D array of only relevant recordings.


问:
Is it possible to have overlapping views with auto layout?
I'm trying to have to views overlap as shown in the picture below, but I couldn't figure out how would I go about doing it with auto layout.

I tried doing the bottom view programmatically, and it worked fine except for the button which I had laid out using interface builder.

If it's possible to have views overlap what are the constraints needed, and is there a way to let the button show on top of the view in the bottom without doing programmatically?

答:
You can do something like this.

make the second view uplift with minus value:

Here is the output. SecondView(green) has been uplifted to -50


问:
Python: Adding Fields to Objects Dynamically
I am wondering whether it is possible to add fields to objects dynamically. For example, I want to be able to add something like:

```<code>user = object()
user.first_name = 'John'
user.last_name = 'Smith'
</code>```

When I execute that in Python command line interpretor I get:

```<code>AttributeError: 'object' object has no attribute 'first_name'
</code>```

Any idea?

答: You cannot assign to attributes of object instances like this. Derive from object, and use an instance of that class.

Body:
I am wondering whether it is possible to add fields to objects dynamically. For example, I want to be able to add something like:

user = object()
user.first_name = 'John'
user.last_name = 'Smith'

When I execute that in Python command line interpretor I get:

AttributeError: 'object' object has no attribute 'first_name'

Any idea?


答:
You should trim the value before comparing.

Below is the code to handle required inputs (for checkbox, radio button different handling will require).

```<code>$('.next').click(function() {
      var valid = true;
      $.each($('[required]:visible'), function() {
         if (!$.trim($(this).val())) {
             valid = false;
             return false;
         }
     });

     if (!valid) {
         alert('Not all required fields are filled');
     } else {
         alert('All required fields are filled');
     }
 });
</code>```

Title: And condition for jQuery doesn't work

Body:
I am developing a multipage form. I am trying to write an if condition:

$('.next').click(function() {
    if ($('input[required]:visible').each().val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});

jsFiddle

This works fine with input type=text. Then I am trying to add the same condition for <textarea>:

$('.next').click(function() {
    if ($('input[required]:visible').val() == false && $('textarea[required]:visible').val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});

jsFiddle for this

Now it requires textarea OR input to be filled, but should work with both, shouldn't it? What am I doing wrong?

Body:
You should trim the value before comparing.

Below is the code to handle required inputs (for checkbox, radio button different handling will require).

$('.next').click(function() {
      var valid = true;
      $.each($('[required]:visible'), function() {
         if (!$.trim($(this).val())) {
             valid = false;
             return false;
         }
     });

     if (!valid) {
         alert('Not all required fields are filled');
     } else {
         alert('All required fields are filled');
     }
 });


问:
Visual Studio 2015 Update 3 Offline Installer (ISO)
After digging around for Visual Studio IDE 2015 update 3 offline installer, aka ISO file, I found it and I am sharing the url.

And, I know this may be posted elsewhere. But I also do know that many people try to find it on StackOverflow.

答:
Its better to go through the Recommended Microsoft's Way to download Visual Studio 2015 Update 3 ISO (Community Edition).

The instructions below will help you to download any version of Visual Studio or even SQL Server etc provided by Microsoft in an easy to remember way. Though I recommend people using VS 2017 as there are not much big differences between 2015 and 2017.

Please follow the steps as mentioned below.

Visit the standard URL www.visualstudio.com/downloads

Scroll down and click on encircled below as shown in snapshot down

After that join Visual Studio Web Dev essentials for Free as shown below. Try loggin in with your microsoft account and see that if it works otherwise click on Join

Click on Downloads ICON on the encircled as shown below.

Now Type Visual Studio Community in the Search Box as shown below in the snapshot .

From the drowdown select the DVD type and start downloading


问:
Why does an interface get emitted at the IL level as an "abstract interface"?
I've been trying to learn more about the CLR and while doing so noticed that the following interface in C# will be compiled to IL that contains some kind of "abstract interface".

Given that declaring an interface as abstract in C# is not valid, what does it mean to allow an abstract interface at the IL level? Initially I wondered if this was how the runtime internally represents an interface, by declaring an abstract class thus preventing it being new-ed up.

It does appear to be following this idea, as shown by the .class. However, following that is interface. So the idea of needing to actually create an abstract class appears to be moot when the runtime already seems to support the concept of an interface.

This leads me to a couple of questions:

What is the purpose of the abstract interface, and why is an abstract interface valid at the IL level?

Why is .class and interface necessary, and why is this valid at the IL level?

If the runtime supports the concept of an interface, why is the .class or abstract required at all?

C#:

```<code>public interface IExample
{
    void SomeMethod(int number);
}
</code>```

IL:

```<code>.class interface public auto ansi abstract IExample
{
    // Methods
    .method public hidebysig newslot abstract virtual
        instance void SomeMethod (
            int32 number
        ) cil managed
    {
    } // end of method IExample::SomeMethod

}
</code>```

答:
If you look at how metadata (PDF) is defined at the IL level, all types are introduced by a .class header (even value types).

interface is described as a "Type semantic attribute" (10.1.3) and is used to distinguish whether what is being defined is, indeed, an interface, as opposed to an abstract class in which all members are abstract.

abstract is described as a "Inheritance attribute" (10.1.4) and specifically means the type cannot be instantiated.

That covers the intended meanings. As to why they're necessary (i.e. why interface doesn't automatically imply abstract), I believe it was done to make everything explicit at this level. Since you don't often have to write IL yourself, having some overlap between some of these flags isn't harmful.

Body:
I've been trying to learn more about the CLR and while doing so noticed that the following interface in C# will be compiled to IL that contains some kind of "abstract interface".

Given that declaring an interface as abstract in C# is not valid, what does it mean to allow an abstract interface at the IL level? Initially I wondered if this was how the runtime internally represents an interface, by declaring an abstract class thus preventing it being new-ed up.

It does appear to be following this idea, as shown by the .class. However, following that is interface. So the idea of needing to actually create an abstract class appears to be moot when the runtime already seems to support the concept of an interface.

This leads me to a couple of questions:

What is the purpose of the abstract interface, and why is an abstract interface valid at the IL level?

Why is .class and interface necessary, and why is this valid at the IL level?

If the runtime supports the concept of an interface, why is the .class or abstract required at all?

C#:

public interface IExample
{
    void SomeMethod(int number);
}

IL:

.class interface public auto ansi abstract IExample
{
    // Methods
    .method public hidebysig newslot abstract virtual
        instance void SomeMethod (
            int32 number
        ) cil managed
    {
    } // end of method IExample::SomeMethod

}


问:
Can't set proper path to app.js
I'm developing webapp in Java with angularjs. My problem is that I'm getting 404 on app.js and app.css files.

path to index.html

```<code>webapp/WEB-INF/app/pages/index.html
</code>```

path to app.js

```<code>webapp/WEB-INF/app/js/app.js
</code>```

path to app.css

```<code>webapp/WEB-INF/app/css/app.css
</code>```

connecting css and script in html:

```<code><link rel="stylesheet" type="text/css" href="/css/app.css" media="all" />
<script type="text/javascript" src="/js/app.js"></script>
</code>```

what should be the proper path?

答: I've fonud the solution. I was using lineman and lineman creates the real index.html in "generated" folder.</p>

Title: Can't set proper path to app.js

Body:
I'm developing webapp in Java with angularjs. My problem is that I'm getting 404 on app.js and app.css files.

path to index.html

webapp/WEB-INF/app/pages/index.html

path to app.js

webapp/WEB-INF/app/js/app.js

path to app.css

webapp/WEB-INF/app/css/app.css

connecting css and script in html:

<link rel="stylesheet" type="text/css" href="/css/app.css" media="all" />

what should be the proper path?