问:
VBA For Each with nested For Each
I have written a For each loop that I want to go through the range and test for the first condition and add the value to a combobox. ONLY If it cannot find that condition then I want it to execute the second for each loop and add all the values that match the condition.

I have written the below code and it says

Else without If

even though there is an IF

```<code> Dim Keys As Range, cell As Range

 Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

   For Each cell In Keys
     If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Else
      For Each cell In Keys
      If cell.Offset(0, 4).Value = 1 And cell.Offset(0, 3) = "" Or cell.Value = "Spare" And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Next cell

 Next cell
 Set Keys = Nothing
</code>```

答:
Split this line into 2 lines like this

```<code> If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then
     Me.ComboBox1.AddItem cell.Value
</code>```

You will also need to use End If somewhere - something like this gets the structure right, but as for the functionality, I'm not sure what you are trying to do, so I guessed.

```<code>Dim Keys As Range, cell As Range, cell2 as Range

 Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

   For Each cell In Keys
     If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then
         Me.ComboBox1.AddItem cell.Value
     Else
        For Each cell2 In Keys
            If cell2.Offset(0, 4).Value = 1 And cell2.Offset(0, 3) = "" Or cell2.Value = "Spare" And cell2.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value
        Next
     End IF
 Next
 Set Keys = Nothing
</code>```

Title: VBA For Each with nested For Each

Body:
I have written a For each loop that I want to go through the range and test for the first condition and add the value to a combobox. ONLY If it cannot find that condition then I want it to execute the second for each loop and add all the values that match the condition.

I have written the below code and it says

Else without If

even though there is an IF

 Dim Keys As Range, cell As Range

 Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

   For Each cell In Keys
     If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Else
      For Each cell In Keys
      If cell.Offset(0, 4).Value = 1 And cell.Offset(0, 3) = "" Or cell.Value = "Spare" And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Next cell

 Next cell
 Set Keys = Nothing

Body:
Split this line into 2 lines like this

 If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then
     Me.ComboBox1.AddItem cell.Value

You will also need to use End If somewhere - something like this gets the structure right, but as for the functionality, I'm not sure what you are trying to do, so I guessed.

Dim Keys As Range, cell As Range, cell2 as Range

 Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

   For Each cell In Keys
     If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then
         Me.ComboBox1.AddItem cell.Value
     Else
        For Each cell2 In Keys
            If cell2.Offset(0, 4).Value = 1 And cell2.Offset(0, 3) = "" Or cell2.Value = "Spare" And cell2.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value
        Next
     End IF
 Next
 Set Keys = Nothing


来源: stackexchange

问:
fresh CentOS image in AWS
There are a lot of CentOS images in AWS for creating EC2 instance.
In most of them various application and services are pre-installed,for example:

I found most of them having apache, bind, postfix & even mysql is installed,
but, I want a fresh image, where I'll install the services whatever I need,
so which CentOS image is a fresh image, could anybody tell me?

Thanks.

答:
You should use this Official Centos Image from AWS Market Place.

Thanks

ContentLicense: CC BY-SA 3.0

Title: fresh CentOS image in AWS


问:
How to add a heading to a comment box?
I have a function to save in a comment box, the time&date and the username of who made a change in the cell, keeping in memory the last five changes.

When a sixth change is made, it deletes the oldest one, and saves the newest. I am also formatting the comment box with the code.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    Dim CommentBox As Object
    Dim CommentString As String
    Dim CommentTemp As String
    Dim LastDoubleDotPosition As Integer
    Dim LongestName As Integer
    Dim FinalComment As String

    If Range("A" & Target.Row).Value = "" Then GoTo EndeSub
    If Target.Row <= 2 Then GoTo EndeSub
    If Not Intersect(Range("C:JA"), Target) Is Nothing Then
        On Error GoTo EndeSub
        Application.EnableEvents = False
        Range("B" & Target.Row) = Now
    End If

    Application.Volatile

    Set CommentBox = Range("B" & Target.Row).Comment

    If Not CommentBox Is Nothing Then
        If CommentBox.Text <> "" Then
            CommentString = CommentBox.Text
            Range("B" & Target.Row).Comment.Delete
        End If
    Else
        CommentString = ""
    End If

    CommentTemp = CommentString
    LastDoubleDotPosition = 0
    LongestName = 0

    If InStr(CommentTemp, ":") > 0 Then StillTwoDoubleDots = True

    Do While InStr(CommentTemp, ":") > 0

        If InStr(CommentTemp, ":") > LongestName Then LongestName = InStr(CommentTemp, ":")
        CommentTemp = Right(CommentTemp, Len(CommentTemp) - InStr(CommentTemp, ":"))

    Loop

    count = CountChr(CommentString, ":")

    If count >= 6 Then

        LastDoubleDotPosition = Len(CommentString) - Len(CommentTemp) - 1
        CommentString = Left(CommentString, LastDoubleDotPosition - 13)

    End If

    'insert comment
    FinalComment = Format(Now(), "DD.MM.YYYY hh:mm") & " " & "by" & " " & Application.UserName & vbCrLf & CommentString 'newComment and the oldcomment
    FinalComment = Replace(FinalComment, CustomComment, vbNullString)
    FinalComment = CustomComment & FinalComment
    Range("B" & Target.Row).AddComment FinalComment

    Set CommentBox = Range("B" & Target.Row).Comment

    LongestName = LongestName * 5
    If LongestName < 150 Then LongestName = 150

    With CommentBox
        .Shape.Height = 70
        .Shape.Width = LongestName
    End With

EndeSub:
    Application.EnableEvents = True

End Sub

Public Function CountChr(Expression As String, Character As String) As Long

    Dim Result As Long
    Dim Parts() As String
    Parts = Split(Expression, Character)
    Result = UBound(Parts, 1)
    If (Result = -1) Then
    Result = 0
    End If
    CountChr = Result

End Function
</code>```

Is it possible also to add a headline for that comment box?

For example I have the following output:

```<code>13.11.2017 17:39 by user2

13.11.2017 17:35 by user1

13.11.2017 17:35 by user3

13.11.2017 17:34 by user1

13.11.2017 17:33 by user1
</code>```

I want to add a bold heading, let's say: "Updated on:", and the output will be:

```<code>Updated on:

    13.11.2017 17:39 by user2

    13.11.2017 17:35 by user1

    13.11.2017 17:35 by user3

    13.11.2017 17:34 by user1

    13.11.2017 17:33 by user1
</code>```

答:
Declare a public constant like this:

```<code>Public Const UPDATED_ON = "UPDATED ON" & vbCrLf
</code>```

When you are writing to the comment at the end, try to replace the value of UPDATED_ON with nothing like this:

```<code>FinalComment = Replace(FinalComment, UPDATED_ON, vbNullString)
</code>```

At the end add the UPDATED_ON on the top like this:

```<code>FinalComment = UPDATED_ON & FinalComment
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to add a heading to a comment box?

Body:
I have a function to save in a comment box, the time&date and the username of who made a change in the cell, keeping in memory the last five changes.

When a sixth change is made, it deletes the oldest one, and saves the newest. I am also formatting the comment box with the code.

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim CommentBox As Object
    Dim CommentString As String
    Dim CommentTemp As String
    Dim LastDoubleDotPosition As Integer
    Dim LongestName As Integer
    Dim FinalComment As String

    If Range("A" & Target.Row).Value = "" Then GoTo EndeSub
    If Target.Row <= 2 Then GoTo EndeSub
    If Not Intersect(Range("C:JA"), Target) Is Nothing Then
        On Error GoTo EndeSub
        Application.EnableEvents = False
        Range("B" & Target.Row) = Now
    End If

    Application.Volatile

    Set CommentBox = Range("B" & Target.Row).Comment

    If Not CommentBox Is Nothing Then
        If CommentBox.Text <> "" Then
            CommentString = CommentBox.Text
            Range("B" & Target.Row).Comment.Delete
        End If
    Else
        CommentString = ""
    End If

    CommentTemp = CommentString
    LastDoubleDotPosition = 0
    LongestName = 0

    If InStr(CommentTemp, ":") > 0 Then StillTwoDoubleDots = True

    Do While InStr(CommentTemp, ":") > 0

        If InStr(CommentTemp, ":") > LongestName Then LongestName = InStr(CommentTemp, ":")
        CommentTemp = Right(CommentTemp, Len(CommentTemp) - InStr(CommentTemp, ":"))

    Loop

    count = CountChr(CommentString, ":")

    If count >= 6 Then

        LastDoubleDotPosition = Len(CommentString) - Len(CommentTemp) - 1
        CommentString = Left(CommentString, LastDoubleDotPosition - 13)

    End If

    'insert comment
    FinalComment = Format(Now(), "DD.MM.YYYY hh:mm") & " " & "by" & " " & Application.UserName & vbCrLf & CommentString 'newComment and the oldcomment
    FinalComment = Replace(FinalComment, CustomComment, vbNullString)
    FinalComment = CustomComment & FinalComment
    Range("B" & Target.Row).AddComment FinalComment

    Set CommentBox = Range("B" & Target.Row).Comment

    LongestName = LongestName * 5
    If LongestName < 150 Then LongestName = 150

    With CommentBox
        .Shape.Height = 70
        .Shape.Width = LongestName
    End With

EndeSub:
    Application.EnableEvents = True

End Sub

Public Function CountChr(Expression As String, Character As String) As Long

    Dim Result As Long
    Dim Parts() As String
    Parts = Split(Expression, Character)
    Result = UBound(Parts, 1)
    If (Result = -1) Then
    Result = 0
    End If
    CountChr = Result

End Function

Is it possible also to add a headline for that comment box?

For example I have the following output:

13.11.2017 17:39 by user2

13.11.2017 17:35 by user1

13.11.2017 17:35 by user3

13.11.2017 17:34 by user1

13.11.2017 17:33 by user1

I want to add a bold heading, let's say: "Updated on:", and the output will be:

Updated on:

    13.11.2017 17:39 by user2

    13.11.2017 17:35 by user1

    13.11.2017 17:35 by user3

    13.11.2017 17:34 by user1

    13.11.2017 17:33 by user1

Body:
Declare a public constant like this:

Public Const UPDATED_ON = "UPDATED ON" & vbCrLf

When you are writing to the comment at the end, try to replace the value of UPDATED_ON with nothing like this:

FinalComment = Replace(FinalComment, UPDATED_ON, vbNullString)

At the end add the UPDATED_ON on the top like this:

FinalComment = UPDATED_ON & FinalComment


问:
error while running ionic ios build --prod --release
After installing Themeable browser plugin I am getting this error when I run :

```<code>ionic cordova build ios --prod --release
</code>```

I was able to build ios --prod --release without any error. Thanks :D

```<code>    Mac-Pro-de-chaker-2:cleantoufoulakids chakerkalai$ ionic cordova build ios --prod --realise
Running app-scripts build: --prod --platform ios --target cordova
[18:22:05]  build prod started ...
[18:22:07]  clean started ...
[18:22:07]  clean finished in 2 ms
[18:22:07]  copy started ...
[18:22:07]  ngc started ...
Error: Metadata version mismatch for module /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic-native/core/decorators.d.ts, found version 4, expected 3
    at StaticSymbolResolver.getModuleMetadata (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24474:34)
    at StaticSymbolResolver._createSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24260:46)
    at StaticSymbolResolver.getSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24241:14)
    at /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23023:30
    at Array.forEach (native)
    at extractProgramSymbols (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23022:79)
    at AotCompiler.compileAll (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:22720:47)
    at CodeGenerator.codegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/codegen.js:30:14)
    at Function.NgTools_InternalApi_NG_2.codeGen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/ngtools_api.js:61:30)
    at Object.doCodegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic/app-scripts/dist/aot/codegen.js:6:51)
[18:22:47]  copy finished in 40.10 s
</code>```

答:
Looks like the issue for me was with "@ionic-native/core": "4.4.0". When I downgraded to "@ionic-native/core": "4.3.3" I was able to do ionic cordova build ios --prod --release with "ionic-angular": "3.9.2" again.

```<code>"@angular/animations": "4.4.6",
"@angular/common": "4.4.6",
"@angular/compiler": "4.4.6",
"@angular/compiler-cli": "4.4.6",
"@angular/core": "4.4.6",
"@angular/forms": "4.4.6",
"@angular/http": "4.4.6",
"@angular/platform-browser": "4.4.6",
"@angular/platform-browser-dynamic": "4.4.6",
"@angular/platform-server": "4.4.6",

"@ionic-native/camera": "4.3.3",
"@ionic-native/core": "4.3.3",
"@ionic-native/device": "4.3.3",
"@ionic-native/diagnostic": "4.3.3",
"@ionic-native/file": "4.3.3",
"@ionic-native/http": "4.3.3",
"@ionic-native/media": "4.3.3",
"@ionic-native/media-capture": "4.3.3",
"@ionic-native/native-storage": "4.3.3",
"@ionic-native/social-sharing": "4.3.3",
"@ionic-native/splash-screen": "4.3.3",
"@ionic-native/status-bar": "4.3.3",
"@ionic-native/themeable-browser": "4.3.3"
</code>```

Unfortunately I couldn't upgrade to "@angular/core": "5.0.1" yet because "ionic-angular": "3.9.2" still is dependant on "@angular/core": "4.4.6".

Body:
After installing Themeable browser plugin I am getting this error when I run :

ionic cordova build ios --prod --release

I was able to build ios --prod --release without any error. Thanks :D

    Mac-Pro-de-chaker-2:cleantoufoulakids chakerkalai$ ionic cordova build ios --prod --realise
Running app-scripts build: --prod --platform ios --target cordova
[18:22:05]  build prod started ...
[18:22:07]  clean started ...
[18:22:07]  clean finished in 2 ms
[18:22:07]  copy started ...
[18:22:07]  ngc started ...
Error: Metadata version mismatch for module /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic-native/core/decorators.d.ts, found version 4, expected 3
    at StaticSymbolResolver.getModuleMetadata (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24474:34)
    at StaticSymbolResolver._createSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24260:46)
    at StaticSymbolResolver.getSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24241:14)
    at /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23023:30
    at Array.forEach (native)
    at extractProgramSymbols (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23022:79)
    at AotCompiler.compileAll (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:22720:47)
    at CodeGenerator.codegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/codegen.js:30:14)
    at Function.NgTools_InternalApi_NG_2.codeGen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/ngtools_api.js:61:30)
    at Object.doCodegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic/app-scripts/dist/aot/codegen.js:6:51)
[18:22:47]  copy finished in 40.10 s

Body:
Looks like the issue for me was with "@ionic-native/core": "4.4.0". When I downgraded to "@ionic-native/core": "4.3.3" I was able to do ionic cordova build ios --prod --release with "ionic-angular": "3.9.2" again.

"@angular/animations": "4.4.6",
"@angular/common": "4.4.6",
"@angular/compiler": "4.4.6",
"@angular/compiler-cli": "4.4.6",
"@angular/core": "4.4.6",
"@angular/forms": "4.4.6",
"@angular/http": "4.4.6",
"@angular/platform-browser": "4.4.6",
"@angular/platform-browser-dynamic": "4.4.6",
"@angular/platform-server": "4.4.6",

"@ionic-native/camera": "4.3.3",
"@ionic-native/core": "4.3.3",
"@ionic-native/device": "4.3.3",
"@ionic-native/diagnostic": "4.3.3",
"@ionic-native/file": "4.3.3",
"@ionic-native/http": "4.3.3",
"@ionic-native/media": "4.3.3",
"@ionic-native/media-capture": "4.3.3",
"@ionic-native/native-storage": "4.3.3",
"@ionic-native/social-sharing": "4.3.3",
"@ionic-native/splash-screen": "4.3.3",
"@ionic-native/status-bar": "4.3.3",
"@ionic-native/themeable-browser": "4.3.3"

Unfortunately I couldn't upgrade to "@angular/core": "5.0.1" yet because "ionic-angular": "3.9.2" still is dependant on "@angular/core": "4.4.6".


问:
Can facebook og:image dynamically pull image from a specific div
Is it possible to tell the facebook metatag og:image to pull the image from a specific div instead of using the image source.

Example: have the og:image automatically pull the image inside of #personal_page_image_div?

```<code><div class="tr-image-div" id="personal_page_image_div">
    <img src="../images/7237.1140778217.custom.jpg" alt="">
</div>
</code>```

答: No, this is not possible. You could use javascript to get the image URL and add it in as og:image, but since this happens after page load, Facebook will not recognise it when fetching the open graph data.


问:
Spring Integration: Persistent and transactional QueueChannel
In Spring Integration we have a Setup that looks something like this:

```<code>                                                     --->
                                                     --->
(dispatcher) Messages --> Gateway ----> QueueChannel ---> MessageHandler (worker)
                                                     --->
                                                     --->
</code>```

So we have one Dispatcher Thread that takes Messages from a MQTT-Broker and forwards them into the Queue. The Poller for the Queue is provided with a TaskExecuter, so the Consumer is multithreaded.
We managed to implement all the functionalities. So the just described setup is already implemented.

Now to guarantee no data loss we want to make two things:

1.:
We want our queue to persist the data, so when the Programm shuts down ungracefully, all the data in the queue will still be there.
This also worked for us, we are using MongoDB as a database because we read somewhere in your docs that this is the recommended way to do it.

2.:
The second thing we want to assure is that the worker threads are working transactional. So only if the worker threads return correctly the messages will permanently be deleted from the queue (and therefore the persistent MessageStore). If the program shuts down during the processing of a message (by the worker thread) the message will still be in the queue at the next startup.
Also if the worker, for example, thows an exception during the processing of the message, it will be put back into the queue.

Our implementation:

As explained before, the basic setup of the program is already implemented. We then extended the basic implementation with a message store implementation for the queue.

QueueChannel:

```<code>@Bean
public PollableChannel inputChannel(BasicMessageGroupStore mongoDbChannelMessageStore) {
    return new QueueChannel(new MessageGroupQueue(mongoDbChannelMessageStore, "inputChannel"));
}
</code>```

backed by a Messagestore:

```<code>@Bean
public BasicMessageGroupStore mongoDbChannelMessageStore(MongoDbFactory mongoDbFactory) {
    MongoDbChannelMessageStore store = new MongoDbChannelMessageStore(mongoDbFactory);
    store.setPriorityEnabled(true);
    return store;
}
</code>```

the matching Poller:

```<code>@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);
    return poll;
}
</code>```

Executor:

```<code>private Executor consumer = Executors.newFixedThreadPool(5);
</code>```

What we have tried?
As explained now we want to extend this implementation with a transactional functionality. We tried using the setTransactionSynchronizationFactory like explained here but it wasn't working (didn't get errors or anything but the behavior was still as it was before we added the TransactionSynchronizer):

```<code>@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);

    BeanFactory factory = mock(BeanFactory.class);
    ExpressionEvaluatingTransactionSynchronizationProcessor etsp = new ExpressionEvaluatingTransactionSynchronizationProcessor();
    etsp.setBeanFactory(factory);
    etsp.setAfterRollbackChannel(inputChannel());
    etsp.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#bix"));
    etsp.setAfterCommitChannel(inputChannel());
    etsp.setAfterCommitExpression(new SpelExpressionParser().parseExpression("#bix"));
    DefaultTransactionSynchronizationFactory dtsf = new DefaultTransactionSynchronizationFactory(etsp);

    poll.setTransactionSynchronizationFactory(dtsf);

    return poll;
}
</code>```

What would be the best way to realize our requirements in spring integration?

EDIT:
As recommended in the answer I chose to do this with the JdbcChannelMessageStore. So I tried converting the XML Implementation described here (18.4.2) into Java.  I wasn't quite sure on how to do it, this is what I have tried so far:

I created H2 database and run the script shown here on it.

Created JDBCChannelMessageStore Bean:

```<code>@Bean
public JdbcChannelMessageStore store() {
    JdbcChannelMessageStore ms =  new JdbcChannelMessageStore();
    ms.setChannelMessageStoreQueryProvider(queryProvider());
    ms.setUsingIdCache(true);
    ms.setDataSource(dataSource);
    return ms;
}
</code>```

Created H2ChannelMessageStoreQueryProvider

```<code>    @Bean
    public ChannelMessageStoreQueryProvider queryProvider() {
        return new H2ChannelMessageStoreQueryProvider();
    }
</code>```

Adapted the poller:

```<code>@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() throws Exception {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);
    poll.setAdviceChain(Collections.singletonList(transactionInterceptor()));

    return poll;
}
</code>```

Autowired my PlaatformTransactionManager:

```<code>@Autowired
PlatformTransactionManager transactionManager;
</code>```

And created TransactionInterceptor from the TransactonManager:

```<code>@Bean
public PollableChannel inputChannel(BasicMessageGroupStore mongoDbChannelMessageStore) {
    return new QueueChannel(new MessageGroupQueue(mongoDbChannelMessageStore, "inputChannel"));
}
</code>```0

答:
If you need to have queue as transactional, you definitely should take a look into the transactional MessageStore. And only JDBC one is like that. Just because only JDBC support transactions. So, when we perform DELETE, it is OK only if TX is committed.

The MongoDB, nor any other NoSQL DataBases, support such a model, therefore you only can push back the failed messages to the DB on rollback using TransactionSynchronizationFactory.

UPDATE

```<code>@RunWith(SpringRunner.class)
@DirtiesContext
public class So47264688Tests {

    private static final String MESSAGE_GROUP = "transactionalQueueChannel";

    private static EmbeddedDatabase dataSource;

    @BeforeClass
    public static void init() {
        dataSource = new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("classpath:/org/springframework/integration/jdbc/schema-drop-h2.sql")
                .addScript("classpath:/org/springframework/integration/jdbc/schema-h2.sql")
                .build();
    }

    @AfterClass
    public static void destroy() {
        dataSource.shutdown();
    }

    @Autowired
    private PollableChannel transactionalQueueChannel;

    @Autowired
    private JdbcChannelMessageStore jdbcChannelMessageStore;

    @Autowired
    private PollingConsumer serviceActivatorEndpoint;

    @Autowired
    private CountDownLatch exceptionLatch;

    @Test
    public void testTransactionalQueueChannel() throws InterruptedException {
        GenericMessage<String> message = new GenericMessage<>("foo");
        this.transactionalQueueChannel.send(message);

        assertTrue(this.exceptionLatch.await(10, TimeUnit.SECONDS));
        this.serviceActivatorEndpoint.stop();

        assertEquals(1, this.jdbcChannelMessageStore.messageGroupSize(MESSAGE_GROUP));
        Message<?> messageFromStore = this.jdbcChannelMessageStore.pollMessageFromGroup(MESSAGE_GROUP);

        assertNotNull(messageFromStore);
        assertEquals(message, messageFromStore);
    }

    @Configuration
    @EnableIntegration
    public static class ContextConfiguration {

        @Bean
        public PlatformTransactionManager transactionManager() {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        public ChannelMessageStoreQueryProvider queryProvider() {
            return new H2ChannelMessageStoreQueryProvider();
        }

        @Bean
        public JdbcChannelMessageStore jdbcChannelMessageStore() {
            JdbcChannelMessageStore jdbcChannelMessageStore = new JdbcChannelMessageStore(dataSource);
            jdbcChannelMessageStore.setChannelMessageStoreQueryProvider(queryProvider());
            return jdbcChannelMessageStore;
        }

        @Bean
        public PollableChannel transactionalQueueChannel() {
            return new QueueChannel(new MessageGroupQueue(jdbcChannelMessageStore(), MESSAGE_GROUP));
        }

        @Bean
        public TransactionInterceptor transactionInterceptor() {
            return new TransactionInterceptorBuilder()
                    .transactionManager(transactionManager())
                    .isolation(Isolation.READ_COMMITTED)
                    .propagation(Propagation.REQUIRED)
                    .build();
        }

        @Bean
        public TaskExecutor threadPoolTaskExecutor() {
            ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
            threadPoolTaskExecutor.setCorePoolSize(5);
            return threadPoolTaskExecutor;
        }

        @Bean(name = PollerMetadata.DEFAULT_POLLER)
        public PollerMetadata poller() {
            return Pollers.fixedDelay(10)
                    .advice(transactionInterceptor())
                    .taskExecutor(threadPoolTaskExecutor())
                    .get();
        }

        @Bean
        public CountDownLatch exceptionLatch() {
            return new CountDownLatch(2);
        }

        @ServiceActivator(inputChannel = "transactionalQueueChannel")
        public void handle(Message<?> message) {
            System.out.println(message);
            try {
                throw new RuntimeException("Intentional for rollback");
            }
            finally {
                exceptionLatch().countDown();
            }
        }

    }

}
</code>```

Body:
In Spring Integration we have a Setup that looks something like this:

                                                     --->
                                                     --->
(dispatcher) Messages --> Gateway ----> QueueChannel ---> MessageHandler (worker)
                                                     --->
                                                     --->

So we have one Dispatcher Thread that takes Messages from a MQTT-Broker and forwards them into the Queue. The Poller for the Queue is provided with a TaskExecuter, so the Consumer is multithreaded.
We managed to implement all the functionalities. So the just described setup is already implemented.

Now to guarantee no data loss we want to make two things:

1.:
We want our queue to persist the data, so when the Programm shuts down ungracefully, all the data in the queue will still be there.
This also worked for us, we are using MongoDB as a database because we read somewhere in your docs that this is the recommended way to do it.

2.:
The second thing we want to assure is that the worker threads are working transactional. So only if the worker threads return correctly the messages will permanently be deleted from the queue (and therefore the persistent MessageStore). If the program shuts down during the processing of a message (by the worker thread) the message will still be in the queue at the next startup.
Also if the worker, for example, thows an exception during the processing of the message, it will be put back into the queue.

Our implementation:

As explained before, the basic setup of the program is already implemented. We then extended the basic implementation with a message store implementation for the queue.

QueueChannel:

@Bean
public PollableChannel inputChannel(BasicMessageGroupStore mongoDbChannelMessageStore) {
    return new QueueChannel(new MessageGroupQueue(mongoDbChannelMessageStore, "inputChannel"));
}

backed by a Messagestore:

@Bean
public BasicMessageGroupStore mongoDbChannelMessageStore(MongoDbFactory mongoDbFactory) {
    MongoDbChannelMessageStore store = new MongoDbChannelMessageStore(mongoDbFactory);
    store.setPriorityEnabled(true);
    return store;
}

the matching Poller:

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);
    return poll;
}

Executor:

private Executor consumer = Executors.newFixedThreadPool(5);

What we have tried?
As explained now we want to extend this implementation with a transactional functionality. We tried using the setTransactionSynchronizationFactory like explained here but it wasn't working (didn't get errors or anything but the behavior was still as it was before we added the TransactionSynchronizer):

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);

    BeanFactory factory = mock(BeanFactory.class);
    ExpressionEvaluatingTransactionSynchronizationProcessor etsp = new ExpressionEvaluatingTransactionSynchronizationProcessor();
    etsp.setBeanFactory(factory);
    etsp.setAfterRollbackChannel(inputChannel());
    etsp.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#bix"));
    etsp.setAfterCommitChannel(inputChannel());
    etsp.setAfterCommitExpression(new SpelExpressionParser().parseExpression("#bix"));
    DefaultTransactionSynchronizationFactory dtsf = new DefaultTransactionSynchronizationFactory(etsp);

    poll.setTransactionSynchronizationFactory(dtsf);

    return poll;
}

What would be the best way to realize our requirements in spring integration?

EDIT:
As recommended in the answer I chose to do this with the JdbcChannelMessageStore. So I tried converting the XML Implementation described here (18.4.2) into Java.  I wasn't quite sure on how to do it, this is what I have tried so far:

I created H2 database and run the script shown here on it.

Created JDBCChannelMessageStore Bean:

@Bean
public JdbcChannelMessageStore store() {
    JdbcChannelMessageStore ms =  new JdbcChannelMessageStore();
    ms.setChannelMessageStoreQueryProvider(queryProvider());
    ms.setUsingIdCache(true);
    ms.setDataSource(dataSource);
    return ms;
}

Created H2ChannelMessageStoreQueryProvider

    @Bean
    public ChannelMessageStoreQueryProvider queryProvider() {
        return new H2ChannelMessageStoreQueryProvider();
    }

Adapted the poller:

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() throws Exception {
    PollerMetadata poll = Pollers.fixedDelay(10).get();
    poll.setTaskExecutor(consumer);
    poll.setAdviceChain(Collections.singletonList(transactionInterceptor()));

    return poll;
}

Autowired my PlaatformTransactionManager:

@Autowired
PlatformTransactionManager transactionManager;

And created TransactionInterceptor from the TransactonManager:

@Bean
public TransactionInterceptor transactionInterceptor() {
    return new TransactionInterceptorBuilder(true)
                .transactionManager(transactionManager)
                .isolation(Isolation.READ_COMMITTED)
                .propagation(Propagation.REQUIRED)
                .build();
}

Body:
If you need to have queue as transactional, you definitely should take a look into the transactional MessageStore. And only JDBC one is like that. Just because only JDBC support transactions. So, when we perform DELETE, it is OK only if TX is committed.

The MongoDB, nor any other NoSQL DataBases, support such a model, therefore you only can push back the failed messages to the DB on rollback using TransactionSynchronizationFactory.

UPDATE

@RunWith(SpringRunner.class)
@DirtiesContext
public class So47264688Tests {

    private static final String MESSAGE_GROUP = "transactionalQueueChannel";

    private static EmbeddedDatabase dataSource;

    @BeforeClass
    public static void init() {
        dataSource = new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("classpath:/org/springframework/integration/jdbc/schema-drop-h2.sql")
                .addScript("classpath:/org/springframework/integration/jdbc/schema-h2.sql")
                .build();
    }

    @AfterClass
    public static void destroy() {
        dataSource.shutdown();
    }

    @Autowired
    private PollableChannel transactionalQueueChannel;

    @Autowired
    private JdbcChannelMessageStore jdbcChannelMessageStore;

    @Autowired
    private PollingConsumer serviceActivatorEndpoint;

    @Autowired
    private CountDownLatch exceptionLatch;

    @Test
    public void testTransactionalQueueChannel() throws InterruptedException {
        GenericMessage<String> message = new GenericMessage<>("foo");
        this.transactionalQueueChannel.send(message);

        assertTrue(this.exceptionLatch.await(10, TimeUnit.SECONDS));
        this.serviceActivatorEndpoint.stop();

        assertEquals(1, this.jdbcChannelMessageStore.messageGroupSize(MESSAGE_GROUP));
        Message<?> messageFromStore = this.jdbcChannelMessageStore.pollMessageFromGroup(MESSAGE_GROUP);

        assertNotNull(messageFromStore);
        assertEquals(message, messageFromStore);
    }

    @Configuration
    @EnableIntegration
    public static class ContextConfiguration {

        @Bean
        public PlatformTransactionManager transactionManager() {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        public ChannelMessageStoreQueryProvider queryProvider() {
            return new H2ChannelMessageStoreQueryProvider();
        }

        @Bean
        public JdbcChannelMessageStore jdbcChannelMessageStore() {
            JdbcChannelMessageStore jdbcChannelMessageStore = new JdbcChannelMessageStore(dataSource);
            jdbcChannelMessageStore.setChannelMessageStoreQueryProvider(queryProvider());
            return jdbcChannelMessageStore;
        }

        @Bean
        public PollableChannel transactionalQueueChannel() {
            return new QueueChannel(new MessageGroupQueue(jdbcChannelMessageStore(), MESSAGE_GROUP));
        }

        @Bean
        public TransactionInterceptor transactionInterceptor() {
            return new TransactionInterceptorBuilder()
                    .transactionManager(transactionManager())
                    .isolation(Isolation.READ_COMMITTED)
                    .propagation(Propagation.REQUIRED)
                    .build();
        }

        @Bean
        public TaskExecutor threadPoolTaskExecutor() {
            ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
            threadPoolTaskExecutor.setCorePoolSize(5);
            return threadPoolTaskExecutor;
        }

        @Bean(name = PollerMetadata.DEFAULT_POLLER)
        public PollerMetadata poller() {
            return Pollers.fixedDelay(10)
                    .advice(transactionInterceptor())
                    .taskExecutor(threadPoolTaskExecutor())
                    .get();
        }

        @Bean
        public CountDownLatch exceptionLatch() {
            return new CountDownLatch(2);
        }

        @ServiceActivator(inputChannel = "transactionalQueueChannel")
        public void handle(Message<?> message) {
            System.out.println(message);
            try {
                throw new RuntimeException("Intentional for rollback");
            }
            finally {
                exceptionLatch().countDown();
            }
        }

    }

}


问:
Scraping Value after Euro Symbol (Scrapy-Python)
i need the a selector to scrape the value after the euro symbol (\u20ac).

```<code><Selector xpath='//*[@class="col-sm-4"]/text()' data=u'\r\n\t\t            \u20ac 30.000,00'>
</code>```

I tried dozens of variations that i have found here on stackoverflow and elsewere but i cant get it.

Sides like https://regexr.com/ show me that something like this:

```<code>response.xpath('//*[@class="col-sm-4"]/text()').re('(\u20ac).\d*.\d*.\d*')
</code>```

should work, but it doesnt.

EDIT: Here a example link of Data that i would like to scrape: https://www.firmenabc.at/manfred-jungwirth-montagen_MoKY

Would appreciate help!

Michael

Body:
i need the a selector to scrape the value after the euro symbol (\u20ac).

<Selector xpath='//*[@class="col-sm-4"]/text()' data=u'\r\n\t\t            \u20ac 30.000,00'>

I tried dozens of variations that i have found here on stackoverflow and elsewere but i cant get it.

Sides like https://regexr.com/ show me that something like this:

response.xpath('//*[@class="col-sm-4"]/text()').re('(\u20ac).\d*.\d*.\d*')

should work, but it doesnt.

EDIT: Here a example link of Data that i would like to scrape: https://www.firmenabc.at/manfred-jungwirth-montagen_MoKY

Would appreciate help!

Michael

Body:
Try this:

response.xpath('//*[@class="col-sm-4"]/text()').re(u'\u20ac\s*(\d+[\d\.,]+)')


问:
Iterate through an array in wordpress php
I'm trying to iterate through this array with 'foreach' to get [post_title]. But unfortunately it's printing me nothing in my browser. Can anybody explain I can iterate through this array?

```<code>Array
(
[0] => WP_Post Object
    (
        [ID] => 6
        [post_author] => 1
        [post_date] => 2017-11-09 12:56:27
        [post_date_gmt] => 2017-11-09 12:56:27
        [post_content] =>
        [post_title] => Hi everybody
        [post_excerpt] =>
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] =>
        [post_name] => hi-everybody
        [to_ping] =>
        [pinged] =>
        [post_modified] => 2017-11-09 12:56:27
        [post_modified_gmt] => 2017-11-09 12:56:27
        [post_content_filtered] =>
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] =>
        [comment_count] => 0
        [filter] => raw
    )

[1] => WP_Post Object
    (
        [ID] => 1
        [post_author] => 1
        [post_date] => 2017-11-06 22:35:17
        [post_date_gmt] => 2017-11-06 22:35:17
        [post_content] => Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
        [post_title] => Hello world!
        [post_excerpt] =>
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] =>
        [post_name] => hello-world
        [to_ping] =>
        [pinged] =>
        [post_modified] => 2017-11-06 22:35:17
        [post_modified_gmt] => 2017-11-06 22:35:17
        [post_content_filtered] =>
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] =>
        [comment_count] => 1
        [filter] => raw
    )

)
</code>```

Here's my foreach loop code:

```<code>    $my_posts = new WP_Query;
    $myposts = $my_posts->query( array('post_type' => 'post'));

            foreach ($post as $myposts ) {

                        echo $post['post_title'];
                 }
}
</code>```

Again, I need to get the value of post_title but I get no output. Help is appreciated.

答:
You have an object inside an array. So you need to do something like

```<code>foreach ($array[WP_Post] as $item) {
  echo $item;
}
</code>```

Or what have you tried so far?

Body:
I'm trying to iterate through this array with 'foreach' to get [post_title]. But unfortunately it's printing me nothing in my browser. Can anybody explain I can iterate through this array?

Array
(
[0] => WP_Post Object
    (
        [ID] => 6
        [post_author] => 1
        [post_date] => 2017-11-09 12:56:27
        [post_date_gmt] => 2017-11-09 12:56:27
        [post_content] =>
        [post_title] => Hi everybody
        [post_excerpt] =>
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] =>
        [post_name] => hi-everybody
        [to_ping] =>
        [pinged] =>
        [post_modified] => 2017-11-09 12:56:27
        [post_modified_gmt] => 2017-11-09 12:56:27
        [post_content_filtered] =>
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] =>
        [comment_count] => 0
        [filter] => raw
    )

[1] => WP_Post Object
    (
        [ID] => 1
        [post_author] => 1
        [post_date] => 2017-11-06 22:35:17
        [post_date_gmt] => 2017-11-06 22:35:17
        [post_content] => Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
        [post_title] => Hello world!
        [post_excerpt] =>
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] =>
        [post_name] => hello-world
        [to_ping] =>
        [pinged] =>
        [post_modified] => 2017-11-06 22:35:17
        [post_modified_gmt] => 2017-11-06 22:35:17
        [post_content_filtered] =>
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] =>
        [comment_count] => 1
        [filter] => raw
    )

)

Here's my foreach loop code:

    $my_posts = new WP_Query;
    $myposts = $my_posts->query( array('post_type' => 'post'));

            foreach ($post as $myposts ) {

                        echo $post['post_title'];
                 }
}

Again, I need to get the value of post_title but I get no output. Help is appreciated.

Body:
You have an object inside an array. So you need to do something like

foreach ($array[WP_Post] as $item) {
  echo $item;
}

Or what have you tried so far?


问:
Python/Outlook Attachment: "cannot find this file..verify exists"
I wrote the following to use Outlook to send an email, but it is not able to locate the file I want to reference:

```<code>import win32com.client as win32
import glob
import os
import datetime

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'xx@ii.ca'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>'# this field is optional

#In case you want to attach a file to the email

newestfile  = max(glob.iglob('*.csv'), key=os.path.getctime))
mail.Attachments.Add(newestfile)

mail.Send()
</code>```

if i try to print(max(glob.iglob('*.csv'), key=os.path.getctime))) it returns the right path. Directly writing the path in newestfile also works fine. How come it doesn't attach in its current form?

I also tried converting the path to a string, that did not work

答:
From the Attachments.Add Method (Outlook) docs, the first argument is:

The source of the attachment. This can be a file (represented by the
  full file system path with a file name) or an Outlook item that
  constitutes the attachment.

Body:
I wrote the following to use Outlook to send an email, but it is not able to locate the file I want to reference:

import win32com.client as win32
import glob
import os
import datetime

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'xx@ii.ca'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '
HTML Message body
'# this field is optional

#In case you want to attach a file to the email

newestfile  = max(glob.iglob('*.csv'), key=os.path.getctime))
mail.Attachments.Add(newestfile)

mail.Send()

if i try to print(max(glob.iglob('*.csv'), key=os.path.getctime))) it returns the right path. Directly writing the path in newestfile also works fine. How come it doesn't attach in its current form?

I also tried converting the path to a string, that did not work


问:
replace text multiple file vb.net
I want multiple files with a name and in a different format
I will replace some of the text

To do this, use the following command:

```<code> Dim sb As New StringBuilder(File.ReadAllText("tmp\boot_root\initrd\fstab.*"))
        sb.Replace("ro,barrier", "ro,noatime,barrier")
        sb.Replace("ro,errors", "ro,noatime,errors")
</code>```

But this does not work. I need a better command to do this

help please

答:
To get a list of all files matching a pattern in a given directory use Directory.Getfiles(path, pattern). Example:</p>

```<code>Dim list as String()
Dim path as String = "C:\tmp\"
Dim filename as String = "fstab"

list = Directory.GetFiles(path, filename & ".*")

For Each file As String In list
    'Logic goes here.
Next
</code>```

Title: replace text multiple file vb.net

Body:
I want multiple files with a name and in a different format
I will replace some of the text

To do this, use the following command:

 Dim sb As New StringBuilder(File.ReadAllText("tmp\boot_root\initrd\fstab.*"))
        sb.Replace("ro,barrier", "ro,noatime,barrier")
        sb.Replace("ro,errors", "ro,noatime,errors")

But this does not work. I need a better command to do this

help please

Body:
To get a list of all files matching a pattern in a given directory use Directory.Getfiles(path, pattern). Example:

Dim list as String()
Dim path as String = "C:\tmp\"
Dim filename as String = "fstab"

list = Directory.GetFiles(path, filename & ".*")

For Each file As String In list
    'Logic goes here.
Next


问:
Design Questions regarding Building CordApps Application
I'm new to corda and getting my head around it. So what I understand is only important data should go to the block chain. example in an exchange of physical contract that's to be shared. I should only create the State of the contract. because that's important and should be immutable.

```<code>// From the example on CORDA site
flowProgressHandle<SignedTransaction> flowHandle = rpcOps
                    .startTrackedFlowDynamic(TestFlow.Initiator.class, iouValue, otherParty);
 //so this is  how flow would begin I'll pass the value of the otherParty and and I'll get my node information in the TestFlow.Initiator class something like this
IOUState iouState = new IOUState(iouValue, getServiceHub().getMyInfo().getLegalIdentities().get(0), otherParty);
</code>```

now getServiceHub().getMyInfo().getLegalIdentities().get(0) -> this gives me my own node as a party as IOUstate constructor takes in lender and owner.

how can I get more information about the owner? Like what is his occupation or hobbies where can I store that to get it?. In the CORDA example I see they provided name in here it doesn't make sense to put hobbies and occupation in here. how to tackle this. I want send and receive Singed

```<code>node {
        name "O=PartyA,L=London,C=GB"
        advertisedServices = []
        p2pPort 10005
        rpcPort 10006
        webPort 10007
        cordapps = ["net.corda:corda-finance:$corda_release_version"]
    }
</code>```

now another question is how to initialize CordaRPCOps rpcOps explicitly ??? because it seems that's required to begin things.

now if I want to get all the contracts which below to partyA do a query on the STATE so that I get the result from H2 DB? Can't I store the parties as well on the block chain with one to many relationship with the STATE of the contract that's being shared? how do I do that?

答:
So there's a few questions there... but I'll answer the one that is "How to initialize CordaRPCOps rpcOps explicitly?" - and the answer is that you can't (and you shouldn't) create an instance of this explicitly. You will either get one if you have connected to a running corda node via the RPC interface or you are in a Corda "Flow".

I am guessing you'd like to connect to a node and get an instance that way - here's how I do it in https://github.com/ragmondo/cordaftp/blob/3d1fd9f636d85803206cae18b522b0c4884d2453/src/main/kotlin/net/corda/cordaftp/Sender.kt#L21

```<code>import net.corda.client.rpc.CordaRPCClient
import net.corda.core.messaging.CordaRPCOps
import net.corda.core.utilities.NetworkHostAndPort

fun loginToCordaNode(args: Array<String>): CordaRPCOps {
    val nodeAddress = NetworkHostAndPort.parse(args[0])
    val client = CordaRPCClient(nodeAddress)
    return client.start("user1", "test").proxy
}
</code>```

Obviously change user1 and test appropriately, but as you can see this returns an object of type CordaRPCOps

Body:
I'm new to corda and getting my head around it. So what I understand is only important data should go to the block chain. example in an exchange of physical contract that's to be shared. I should only create the State of the contract. because that's important and should be immutable.

// From the example on CORDA site
flowProgressHandle<SignedTransaction> flowHandle = rpcOps
                    .startTrackedFlowDynamic(TestFlow.Initiator.class, iouValue, otherParty);
 //so this is  how flow would begin I'll pass the value of the otherParty and and I'll get my node information in the TestFlow.Initiator class something like this
IOUState iouState = new IOUState(iouValue, getServiceHub().getMyInfo().getLegalIdentities().get(0), otherParty);

now getServiceHub().getMyInfo().getLegalIdentities().get(0) -> this gives me my own node as a party as IOUstate constructor takes in lender and owner.

how can I get more information about the owner? Like what is his occupation or hobbies where can I store that to get it?. In the CORDA example I see they provided name in here it doesn't make sense to put hobbies and occupation in here. how to tackle this. I want send and receive Singed

node {
        name "O=PartyA,L=London,C=GB"
        advertisedServices = []
        p2pPort 10005
        rpcPort 10006
        webPort 10007
        cordapps = ["net.corda:corda-finance:$corda_release_version"]
    }

now another question is how to initialize CordaRPCOps rpcOps explicitly ??? because it seems that's required to begin things.

now if I want to get all the contracts which below to partyA do a query on the STATE so that I get the result from H2 DB? Can't I store the parties as well on the block chain with one to many relationship with the STATE of the contract that's being shared? how do I do that?

Body:
So there's a few questions there... but I'll answer the one that is "How to initialize CordaRPCOps rpcOps explicitly?" - and the answer is that you can't (and you shouldn't) create an instance of this explicitly. You will either get one if you have connected to a running corda node via the RPC interface or you are in a Corda "Flow".

I am guessing you'd like to connect to a node and get an instance that way - here's how I do it in https://github.com/ragmondo/cordaftp/blob/3d1fd9f636d85803206cae18b522b0c4884d2453/src/main/kotlin/net/corda/cordaftp/Sender.kt#L21

import net.corda.client.rpc.CordaRPCClient
import net.corda.core.messaging.CordaRPCOps
import net.corda.core.utilities.NetworkHostAndPort

fun loginToCordaNode(args: Array<String>): CordaRPCOps {
    val nodeAddress = NetworkHostAndPort.parse(args[0])
    val client = CordaRPCClient(nodeAddress)
    return client.start("user1", "test").proxy
}

Obviously change user1 and test appropriately, but as you can see this returns an object of type CordaRPCOps


问:
Console Application with ASP.NET Authentication
Here's the situation, I've got a console application that needs to run once a day and make a few requests to pages that require authentication to view. The pages are hosted in a really basic ASP.Net Web Application.

So, I know that in order for the requests to go through successfully I have to authenticate with the server. So I've hooked up the console application to the ASP.Net Membership Provider I'm using for the web app and it successfully determines if a set of a credentials are valid. However, after calling Membership.ValidateUser() any requests I make just get the login screen. After doing some reading it seems that this is because I'm missing the important cookie information that persists my login or what-have-you.

I'm using a basic WebClient to make the requests and then reading/discarding the result.

So the meat of the question is this: Is there a simple way to validate the login information and hold on to it so that I can make the requests successfully, or is this the exact same case as the other two questions I found that require the WebClient to make a "manual" login request to the login.aspx page and try to hold on to the cookie from there?

The questions I'm referencing are:

Authenticating ASP.NET MVC user from a WPF application

and

Login to website and use cookie to get source for another page

答:
If the intent is to send data to the server and/or get data from the server, then the most logical architecture is probably to create a web service using either ASMX or WCF.  Then configure the service to use a security token, such as a username token or a SAML token.  This will make the client less likely to break when the server code changes its data model.

Otherwise, if you wish to use only a basic WebClient, then you will have to find a way to pass your credentials to the login page and retain the login cookie that is returned from the login request.  Then, make sure that the login cookie is included on all subsequent requets, similar to the Stack Overflow question that you referenced, "Login to website and use cookie to get source for another page".

ContentLicense: CC BY-SA 2.5


问:
Set EntityImage Using JavaScript Dynamics CRM
I need to add an image that is already in web resources (jpg)
and according to the name of the product in my entity the entityimage is filled.

I'm using the following Script but it's not working; the result that is returning is empty, causing an error.

The event is triggered on change of the product name field and is calling the function SetImage().

Any suggestion on how to achieve this?

//Hook this method to the "OnChange" event of "creditlimit" field
     function SetImage()
     {
 debugger;
    var productId = Xrm.Page.data.entity.getId();
    var productName = Xrm.Page.getAttribute("name").getValue();

    if (productName != null)
    {

        //retrieve image onecoinpile.jpg and update product record "EntityImage" attribute
        this.UpdateproductRecordWithNewImage(productId, "new_BurgerGift.jpg");

    }
}

 function UpdateproductRecordWithNewImage(productId, webResourceName)
 {

 debugger;
    this.GetImageWebResource
    (
        productId,
        webResourceName,
        this.UpdateProductRecord
    );

}

function GetImageWebResource(productId, imageName, successCallback)
{
   debugger;

    //OData URI to get address information from parent account record
    var oDataURI = Xrm.Page.context.getClientUrl()
        + "/XRMServices/2011/OrganizationData.svc/"
        + "WebResourceSet"
        + "?$filter="
        + "Name eq '" + imageName + "'"
        + "&$select=Name,Content";

    //Synchronous XMLHttpRequest to retrieve account record
    var req = new XMLHttpRequest();
    req.open("GET", encodeURI(oDataURI), false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function ()
    {
        debugger;
        if (this.readyState == 4 /* complete */)
        {
            req.onreadystatechange = null; //avoids memory leaks
            if (this.status == 200)
            {
                //parse the response string as a JSON object into the successCallback method.
                successCallback(productId, JSON.parse(this.responseText).d);
            }
            else
            {
               alert("error");
                var errorMsg1 = "GetImageWebResource Error: cannot retrieve image with name = " + imageName + ".";
                //display a non-blocking alert dialog
                Xrm.Utility.alertDialog(errorMsg1, function () { });
            }
        }
    };
    req.send();
}

 function UpdateProductRecord(recordId, webResource)
 {
   debugger;

 try{
    //var product = {EntityImage:""};
    var product = webResource.results[0].Content; //byte[] content of the web resource

    alert(product);

    var jsonproduct= JSON.stringify(product);
    alert(jsonproduct);
   }catch(ex){
      console.log(ex);
   }

    //OData URI
    var oDataURI = Xrm.Page.context.getClientUrl()
        + "/XRMServices/2011/OrganizationData.svc/"
        + "productSet(guid'" + recordId + "')";
    alert(oDataURI);
    //Synchronous post
    var req = new XMLHttpRequest();
    req.open("POST", encodeURI(oDataURI), false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("X-HTTP-Method", "MERGE");
    req.onreadystatechange = function ()
    {
        debugger;
        if (this.readyState == 4 /* complete */)
        {
            req.onreadystatechange = null;
            if (this.status == 204 || this.status == 1223)
            {
                //reloads the product record
                window.location.reload(false);
            }
            else
            {
               alert("error");
                var errorMsg2 = "UpdateProductRecord Error: Cannot update product record with productId = " + recordId + ".";
                //display a non-blocking alert dialog
                Xrm.Utility.alertDialog(errorMsg2, function () { });
            }
        }
    };
    req.send(jsonproduct);
    alert(jsonproduct);
}```

答:
Your code looks fine, it should be working when you change the below lines.

```<code>var product = {};
product.EntityImage = webResource.results[0].Content;
</code>```

You mentioned, result is empty. Can you verify by placing small case new_burgergift.jpg instead of new_BurgerGift.jpg.

Always check before accessing child elements like:

```<code>if(webResource.results[0])
    product.EntityImage = webResource.results[0].Content;
</code>```

Body:
Your code looks fine, it should be working when you change the below lines.

var product = {};
product.EntityImage = webResource.results[0].Content;

You mentioned, result is empty. Can you verify by placing small case new_burgergift.jpg instead of new_BurgerGift.jpg.

Always check before accessing child elements like:

if(webResource.results[0])
    product.EntityImage = webResource.results[0].Content;


问:
image resolution for banner and logo
I have a problem with image size and resolution on my app I need to upload an image then I want to resize it to all screen, which is the best image size and width/height for banner and logo and I need a good tool that resizes image?</p>

答:
You will want to remake the logo in a vector format, this relies on positions rather than individual pixels.

In other words no matter how big you make the image, it will always be crisp and sharp.

If I remember to back when I dabbled in Android development I seem to remember android making different sized versions of the logo and banner... Therefore what I would do is create the logo in a vector program such as Inkscape or Adobe Illustrator, and exporting it as a high quality png, this way if you need to resize it in the future, you just export it at a different size and you're good to go.

Title: image resolution for banner and logo


问:
Accessing Eloquent Relationship Automatically when loaded
I am working on  a project which requires me to get all the list of all information from a table --Just like in  a blog, i used the all() method to do this but when i try to get the method i declared in my Model i get an error, saying

the collection instance does not exists

But when i use The
Model::find($id)->relationship()->name;

it works fine. Is there any way to load all relationship with the all() function in laravel.

Thanks for your help..

答:
You should use relationship without brackets to access the model:

```<code>Model::find($id)->relationship->name;
</code>```

And use "with()" to populate the relationships:

```<code>Model::where('published', 1)->with('relationship')
</code>```

Body:
You should use relationship without brackets to access the model:

Model::find($id)->relationship->name;

And use "with()" to populate the relationships:

Model::where('published', 1)->with('relationship')


问:
Bi-directional communication using sockets via ssh tunnel
I have a server host (S) and a bunch of clients (C1, C2, C3, ...). I would like to open connection between S and C1, C2, C3 respectively for bi-directional communication. Ideally using sockets. SSH for authorisation purposes is preferred.

Ideally:

Client C1 creates SSH reverse tunnel to S, forwarding C1's port so it is accessible on S as it's own port.

Client program running on C1 creates a socket and binds to forwarded port.

Server program running on S creates a socket and binds to forwarded port.

Client and server can exchange data.

Is something like that possible? I tried coding up a draft using Python but to no avail:

Firstly, I run on C1: ssh -N -R 9999:localhost:15432 root@example.com - OK

Secondly, on server I run:

```<code>import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 9999))
serversocket.listen(5)

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break
</code>```

Thirdly, on client I run:

```<code>import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 15432))
clientsocket.send('hello')
</code>```

But I'm getting socket.error: [Errno 111] Connection refused on client. Also if I set up tunnel first and then launch server program, I'm getting [Errno 98] Address already in use. It only works when I first start the program, then set up a tunnel.

If aforementioned concept does not make sense, what would you suggest to create sort of synchronisation tool so any client listens for queries from the server and can respond with data? (preferrably in Python).

Thanks in advance.

答:
-N doesn't do what you seem to think it does: it's intended for the ssh-destination to be able to connect back to the originator. But that would make the originating side the server.

It sounds like you should be using -L to simply create a connection from the client through the ssh tunnel to the server.

To demonstrate: I have a local server named 'bree'. On that machine, I execute (this could also be your python server listening on port 9999):

```<code>nc -l 9999
</code>```

Now on my client machine, I execute this in one window (or could put it in the background):

```<code>ssh -N -L 9999:bree:9999 bree
</code>```

This says: listen on the local (client) machine to port 9999, and when a connection to it is made, forward the request through the tunnel, and connect to port 9999 on bree.

Now, in a second window on the client machine, I execute:

```<code>nc localhost 9999
</code>```

The two nc instances are connected.

Body:
I have a server host (S) and a bunch of clients (C1, C2, C3, ...). I would like to open connection between S and C1, C2, C3 respectively for bi-directional communication. Ideally using sockets. SSH for authorisation purposes is preferred.

Ideally:

Client C1 creates SSH reverse tunnel to S, forwarding C1's port so it is accessible on S as it's own port.

Client program running on C1 creates a socket and binds to forwarded port.

Server program running on S creates a socket and binds to forwarded port.

Client and server can exchange data.

Is something like that possible? I tried coding up a draft using Python but to no avail:

Firstly, I run on C1: ssh -N -R 9999:localhost:15432 root@example.com - OK

Secondly, on server I run:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 9999))
serversocket.listen(5)

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Thirdly, on client I run:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 15432))
clientsocket.send('hello')

But I'm getting socket.error: [Errno 111] Connection refused on client. Also if I set up tunnel first and then launch server program, I'm getting [Errno 98] Address already in use. It only works when I first start the program, then set up a tunnel.

If aforementioned concept does not make sense, what would you suggest to create sort of synchronisation tool so any client listens for queries from the server and can respond with data? (preferrably in Python).

Thanks in advance.

Body:
-N doesn't do what you seem to think it does: it's intended for the ssh-destination to be able to connect back to the originator. But that would make the originating side the server.

It sounds like you should be using -L to simply create a connection from the client through the ssh tunnel to the server.

To demonstrate: I have a local server named 'bree'. On that machine, I execute (this could also be your python server listening on port 9999):

nc -l 9999

Now on my client machine, I execute this in one window (or could put it in the background):

ssh -N -L 9999:bree:9999 bree

This says: listen on the local (client) machine to port 9999, and when a connection to it is made, forward the request through the tunnel, and connect to port 9999 on bree.

Now, in a second window on the client machine, I execute:

nc localhost 9999

The two nc instances are connected.


问:
Building rocket.chat on heroku server faced error
I wanted to deploy the rocket.chat project on heroku, following the deployment instruction, I have encountered the following error:

"
Can't open /tmp/build_29c97eef7e456d21231bc9eb4751ca67/ringelco-racket-chat-a864ad48b50652f34205d656e8e6d93976ce69e3/packages/rocketchat-livechat/plugin/build.sh
/app/tmp/cache/meteor/.meteor/packages/tap_i18n/.1.8.2.10lihy6.24zh++os+web.browser+web.cordova/plugin.tap-i18n-compiler.os/npm/node_modules/meteor/promise/node_modules/meteor-promise/promise_server.js:116
      throw error;
"

I have noticed that some other issues are related to such error (this and this), but nobody has answered it yet!

It would be appreciative if you could help me.
Thanks in advance,

答:
Issue fixed.
I just pulled the latest code from Rocket.Chat.
Followed the step to deploy it on Heroku Rocket.Chat Herokyu Deployment.
You have to use buildpack  https://github.com/RocketChat/meteor-buildpack-horse.git.</p>


问:
How to Add Smooth Scrolling Back To Top Button using react js?
I have implemented this using jquery but want to create a component in react to do the same

```<code><script>
jQuery(document).ready(function() {
    var offset = 220;
    var duration = 500;
    jQuery(window).scroll(function() {
        if (jQuery(this).scrollTop() > offset) {
            jQuery('.move-top').fadeIn(duration);
        } else {
            jQuery('.move-top').fadeOut(duration);
        }
    });

    jQuery('.move-top').click(function(event) {
        event.preventDefault();
        jQuery('html, body').animate({scrollTop: 0}, duration);
        return false;
    })
});
</script>
</code>```

In my page footer

```<code><a href="#" class="move-top">↑</a>
</code>```

答:
I think react-scroll is worth being mentioned, add this to your component's click handler (onClick={this.handleClick})

```<code>import Scroll from 'react-scroll'

...
Scroll.animateScroll.scrollToTop({options})
...
</code>```

With options being an object specified as per Props/Options

Body:
I have implemented this using jquery but want to create a component in react to do the same

In my page footer

↑

Body:
I think react-scroll is worth being mentioned, add this to your component's click handler (onClick={this.handleClick})

import Scroll from 'react-scroll'

...
Scroll.animateScroll.scrollToTop({options})
...

With options being an object specified as per Props/Options


问:
Why gst_app_src_get_size always return -1 but in general everything works well?
I have app in C, that uses gstreamer lib
and I push GstBuffer to appsrc - it works, video is playing, but I can not get the size of appsrc element ?
I am doing this:

```<code>  GstElement* element = gst_bin_get_by_name (GST_BIN (mybin), "binname");

     gst_app_src_push_buffer (GST_APP_SRC (element), buffer);
     printf("  SIZE OF APPSRC = %d \n", gst_app_src_get_size(GST_APP_SRC (element)));
</code>```

I always see -1

答: I think that is an informational value. Appsrc does not know how much data you will feed to it before the stream is EOS. Therefore it tells you it is 'unknown'. If you set it via gst_app_src_set_size() it will probably return the same result here. Similar to gst_app_src_set/get_duration(). AppSrc gives your app control over the feed to the pipeline therefore you cannot expect the pipeline to figure out these things for you.

Body:
I have app in C, that uses gstreamer lib
and I push GstBuffer to appsrc - it works, video is playing, but I can not get the size of appsrc element ?
I am doing this:

  GstElement* element = gst_bin_get_by_name (GST_BIN (mybin), "binname");

     gst_app_src_push_buffer (GST_APP_SRC (element), buffer);
     printf("  SIZE OF APPSRC = %d \n", gst_app_src_get_size(GST_APP_SRC (element)));

I always see -1


问:
Page Links in Magento 2
I have created a About us page from backend and trying to link that page to the About-us at the footer. I am using:

```<code><a href="<?php echo $this->getUrl(''); ?>about-us"></a>
</code>```

After clicking on About Us It's working. URL: http://localhost/magento2/about-us but there is a blank page, no header and footer.

答:
you can do it by using Mage:</p>

```<code><a href="<?php echo Mage::getUrl('about-us'); ?>">About Us</a>
</code>```

Title: Page Links in Magento 2

Body:
I have created a About us page from backend and trying to link that page to the About-us at the footer. I am using:

<a href="<?php echo $this->getUrl(''); ?>about-us">

After clicking on About Us It's working. URL: http://localhost/magento2/about-us but there is a blank page, no header and footer.

Body:
you can do it by using Mage:

<a href="<?php echo Mage::getUrl('about-us'); ?>">About Us</a>


问:
CUDA function call-able by either the device or host
I have a re-useable function in some CUDA code that needs to be called from both the device and the host. Is there an appropriate qualifier for this?

e.g. what's the correct definition for func1 in this case:

```<code>int func1 (int a, int b) {
    return a+b;
}

__global__ devicecode (float *A) {
    int i = blockDim.x * blockIdx.x + threadIdx.x;
    A[i] = func1(i,i);
}

void main() {
    // Normal cuda memory set-up

    // Call func1 from inside main:
    int j = func1(2,4)

    // Normal cuda memory copy / program run / retrieve data
}
</code>```

So far I can only get this to work by having the function twice: once explicitly for the device and once for the host. Is there a better way?

答:
From the CUDA Programming Guide:

The __device__ and __host__ qualifiers can be used together however, in
  which case the function is compiled for both the host and the device.

Body:
I have a re-useable function in some CUDA code that needs to be called from both the device and the host. Is there an appropriate qualifier for this?

e.g. what's the correct definition for func1 in this case:

int func1 (int a, int b) {
    return a+b;
}

__global__ devicecode (float *A) {
    int i = blockDim.x * blockIdx.x + threadIdx.x;
    A[i] = func1(i,i);
}

void main() {
    // Normal cuda memory set-up

    // Call func1 from inside main:
    int j = func1(2,4)

    // Normal cuda memory copy / program run / retrieve data
}

So far I can only get this to work by having the function twice: once explicitly for the device and once for the host. Is there a better way?


问:
Convert plain text URLs into HTML hyperlinks in PHP
I have a simple commenting system where people can submit hyperlinks inside the plain text field. When I display these records back from the database and into the web page, what RegExp in PHP can I use to convert these links into HTML-type anchor links?

I don't want the algorithm to do this with any other kind of link, just http and https.

答:
Try this one:

```<code>$s = preg_replace('/(?<!href="|">)(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/is', '<a href="\\1" target="_blank">\\1</a>', $s);
</code>```

It skips the existing links (if we already have a href, it won't add a href inside of a href). Otherwise it will add the a href with blank target.

Body:
Try this one:

$s = preg_replace('/(?<!href="|">)(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/is', '<a href="\\1" target="_blank">\\1</a>', $s);

It skips the existing links (if we already have a href, it won't add a href inside of a href). Otherwise it will add the a href with blank target.


问:
Selenium java testNG: Is it possible to use dataprovider data partially in testng test method
I am new to Page-Object model automation using selenium and java. I am using the Page Object model and have each page as a single class and the actions in that page as methods.Using excel to keep read test data. I have a test for searching for client using various parameters like client number, policy number, surname, firstname, webrefernce, email eand many more...... Now I have to provide all parameters in method signature otherwise test is failing with dataprovider mismatch error. I have a GetData method which provide string array from excelsheet specified.

Is it possible to make parameters optional so that I can specify only the parameters required for that particular test in the test method's signature.? In actual test there  are 15 parameters and additional combinations. (If this is not possible, I have to split the data in to 16 different tab and define data providers for each tests separately). Or any other way to achieve this? Thanks

Current code:

@DataProvider(name="ClientSearchData")
 public String[][] getTestData() {
  String[][] testRecords = getData("TestData_igo4.xlsx","ClientSearch");
  return testRecords;
 }

 @BeforeTest
 public void setUp() {
  init();
 }

 @Test(dataProvider="ClientSearchData")
 public void verifyClientSearchByClientNumber(String clientnumber, String policynumber, String surname, String webreference, String email) {

 //code for search by clientnumber

 }

 @Test(dataProvider="ClientSearchData")

 public void verifyClientSearchByPolicyNumber(String clientnumber, String policynumber, String surname, String webreference, String email) {

 //Code for search by policynumber

 }```
</div>
</div>
</p>

<p>I want something like the following to avoid unnecessary parameters for each tests..</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> @DataProvider(name="ClientSearchData")
 public String[][] getTestData() {
  String[][] testRecords = getData("TestData.xlsx","ClientSearch");
  return testRecords;
 }

 @BeforeTest
 public void setUp() {
  init();
 }
 @Test(dataProvider="ClientSearchData")
 public void verifyClientSearchByClientNumber(String clientnumber) {

 //code for search by clientnumber

 }

 @Test(dataProvider="ClientSearchData")

 public void verifyClientSearchByPolicyNumber(String policynumber) {

 //Code for search by policynumber

 }</code>```

答:
I think what you are looking is Varargs.
You can simply do like below

```<code>@DataProvider(name = "testData")
  public static Object[][] testDataProvider() {

      return new Object[][] {new String[]{"a","b","c"}};
  }

 @Test(priority=3,dataProvider = "testData")
  public void test1(String... str1) {
      System.out.println("first string"+" "+str1[0]);

  }

  @Test(priority=4,dataProvider = "testData")
  public  void test2(String... str2) {
      System.out.println("second string"+" " + str2[1]);

  }
</code>```

The above prints

```<code>first string a
second string b
</code>```

In above code just adjust data provider according to your getTestData
 Three dots ... is the key here

EDIT:

You can actually do it without Varargs. The below also prints same

```<code> @Test(priority=3,dataProvider = "testData")
  public void test1(String str1[] ) {
      System.out.println("first string"+" "+str1[0]);

  }

  @Test(priority=4,dataProvider = "testData")
  public  void test2(String str2[]) {
      System.out.println("second string"+" " + str2[1]);

  }
</code>```

Body:
I am new to Page-Object model automation using selenium and java. I am using the Page Object model and have each page as a single class and the actions in that page as methods.Using excel to keep read test data. I have a test for searching for client using various parameters like client number, policy number, surname, firstname, webrefernce, email eand many more...... Now I have to provide all parameters in method signature otherwise test is failing with dataprovider mismatch error. I have a GetData method which provide string array from excelsheet specified.

Is it possible to make parameters optional so that I can specify only the parameters required for that particular test in the test method's signature.? In actual test there  are 15 parameters and additional combinations. (If this is not possible, I have to split the data in to 16 different tab and define data providers for each tests separately). Or any other way to achieve this? Thanks

Current code:

@DataProvider(name="ClientSearchData")
 public String[][] getTestData() {
  String[][] testRecords = getData("TestData_igo4.xlsx","ClientSearch");
  return testRecords;
 }

 @BeforeTest
 public void setUp() {
  init();
 }

 @Test(dataProvider="ClientSearchData")
 public void verifyClientSearchByClientNumber(String clientnumber, String policynumber, String surname, String webreference, String email) {

 //code for search by clientnumber

 }

 @Test(dataProvider="ClientSearchData")

 public void verifyClientSearchByPolicyNumber(String clientnumber, String policynumber, String surname, String webreference, String email) {

 //Code for search by policynumber

 }

I want something like the following to avoid unnecessary parameters for each tests..

 @DataProvider(name="ClientSearchData")
 public String[][] getTestData() {
  String[][] testRecords = getData("TestData.xlsx","ClientSearch");
  return testRecords;
 }

 @BeforeTest
 public void setUp() {
  init();
 }
 @Test(dataProvider="ClientSearchData")
 public void verifyClientSearchByClientNumber(String clientnumber) {

 //code for search by clientnumber

 }

 @Test(dataProvider="ClientSearchData")

 public void verifyClientSearchByPolicyNumber(String policynumber) {

 //Code for search by policynumber

 }

Body:
I think what you are looking is Varargs.
You can simply do like below

@DataProvider(name = "testData")
  public static Object[][] testDataProvider() {

      return new Object[][] {new String[]{"a","b","c"}};
  }

 @Test(priority=3,dataProvider = "testData")
  public void test1(String... str1) {
      System.out.println("first string"+" "+str1[0]);

  }

  @Test(priority=4,dataProvider = "testData")
  public  void test2(String... str2) {
      System.out.println("second string"+" " + str2[1]);

  }

The above prints

first string a
second string b

In above code just adjust data provider according to your getTestData
 Three dots ... is the key here

EDIT:

You can actually do it without Varargs. The below also prints same

 @Test(priority=3,dataProvider = "testData")
  public void test1(String str1[] ) {
      System.out.println("first string"+" "+str1[0]);

  }

  @Test(priority=4,dataProvider = "testData")
  public  void test2(String str2[]) {
      System.out.println("second string"+" " + str2[1]);

  }


问:
How to move Child Package logs to different log File in logback?
```<code>    <?xml version="1.0" encoding="UTF-8"?>
<configuration>

<appender name="appLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--See also http://logback.qos.ch/manual/appenders.html#RollingFileAppender-->
<File>${appLogFile}</File>
<encoder>
   <Pattern>%d{dd-MM-yy HH:mm:ss.SSS}\t%X{reqId}\t%thread\t%level\t%logger{36}\t%M\t%line\t%msg%n</Pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
   <fileNamePattern>${appLogFile}.%i</fileNamePattern>
   <minIndex>1</minIndex>
   <maxIndex>3</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
   <maxFileSize>50MB</maxFileSize>
</triggeringPolicy>
</appender>

<appender name="REPORT-XYZ-LOG-APPENDER"
class="ch.qos.logback.core.rolling.RollingFileAppender">

<file>${appLogFile}.reports_xyz.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
  <Pattern>%d{dd-MM-yy HH:mm:ss.SSS}\t%X{reqId}\t%23thread\t%-5level\t%-38logger{36}\t%-25M\t%4line\t%msg%n</Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  <!-- rollover daily -->
  <fileNamePattern>${appLogFile}.reports_xyz.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
  <timeBasedFileNamingAndTriggeringPolicy   class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
    <maxFileSize>10MB</maxFileSize>
  </timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>

<appender name="REPORT-LOG-APPENDER"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${appLogFile}.reports.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
  <Pattern>
            %d{dd-MM-yy HH:mm:ss.SSS}\t%X{reqId}\t%thread\t%level\t%logger{36}\t%M\t%line\t%msg%n
        </Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  <!-- rollover daily -->
  <fileNamePattern>${appLogFile}.reports.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
  <timeBasedFileNamingAndTriggeringPolicy   class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
    <maxFileSize>10MB</maxFileSize>
  </timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>

</appender>

<logger name="com.xyz.a.b.c" level="INFO" additivity="false">
<appender-ref ref="REPORT-XYZ-LOG-APPENDER" />
</logger>

<logger name="com.xyz" level="INFO" additivity="false">
  <appender-ref ref="appLog"/>
</logger>

<root level="INFO">
<appender-ref ref="REPORT-LOG-APPENDER" />
</root>

</configuration>
</code>```

I want to move the logs for package "com.xyz.a.b.c" to different file in place of where package "com.xyz" logs are going. But after using above logback.xml file, logs are still going to ${appLogFile} ( appLogFile is system Property  and have absolute file path) for both parent as well as child packages. Can someone help me what i am doing wrong here ?

I want to move logs for com.xyz.a.b.c --> File1
                        com.xyz       --> File2

答: I got the answer. it was my mistake only. changed the logback.xml file to move it</p>

Body:
    <?xml version="1.0" encoding="UTF-8"?>
<configuration>

<appender name="appLog" class="ch.qos.logback.core.rolling.RollingFileAppender">

<File>${appLogFile}</File>
<encoder>
   <Pattern>%d{dd-MM-yy HH:mm:ss.SSS}\t%X{reqId}\t%thread\t%level\t%logger{36}\t%M\t%line\t%msg%n</Pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
   <fileNamePattern>${appLogFile}.%i</fileNamePattern>
   <minIndex>1</minIndex>
   <maxIndex>3</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
   <maxFileSize>50MB</maxFileSize>
</triggeringPolicy>
</appender>

<appender name="REPORT-XYZ-LOG-APPENDER"
class="ch.qos.logback.core.rolling.RollingFileAppender">

<file>${appLogFile}.reports_xyz.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
  <Pattern>%d{dd-MM-yy HH:mm:ss.SSS}\t%X{reqId}\t%23thread\t%-5level\t%-38logger{36}\t%-25M\t%4line\t%msg%n</Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

  <fileNamePattern>${appLogFile}.reports_xyz.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
  <timeBasedFileNamingAndTriggeringPolicy   class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
    <maxFileSize>10MB</maxFileSize>
  </timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>

<appender name="REPORT-LOG-APPENDER"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${appLogFile}.reports.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
  <Pattern>
            %d{dd-MM-yy HH:mm:ss.SSS}\t%X{reqId}\t%thread\t%level\t%logger{36}\t%M\t%line\t%msg%n
        </Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

  <fileNamePattern>${appLogFile}.reports.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
  <timeBasedFileNamingAndTriggeringPolicy   class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
    <maxFileSize>10MB</maxFileSize>
  </timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>

</appender>

<logger name="com.xyz.a.b.c" level="INFO" additivity="false">
<appender-ref ref="REPORT-XYZ-LOG-APPENDER" />
</logger>

<logger name="com.xyz" level="INFO" additivity="false">
  <appender-ref ref="appLog"/>
</logger>

<root level="INFO">
<appender-ref ref="REPORT-LOG-APPENDER" />
</root>

</configuration>

I want to move the logs for package "com.xyz.a.b.c" to different file in place of where package "com.xyz" logs are going. But after using above logback.xml file, logs are still going to ${appLogFile} ( appLogFile is system Property  and have absolute file path) for both parent as well as child packages. Can someone help me what i am doing wrong here ?

I want to move logs for com.xyz.a.b.c --> File1
                        com.xyz       --> File2


问:
Access Stage name during the build in Jenkins pipeline
Let's say we have the following Jenkinsfile:

```<code>stage name: "Cool stage"
    sh 'whoami'
stage name: "Better stage"
    def current_stage = getCurrentStageName()
    echo "CONGRATULATIONS, you are on stage: $current_stage"
</code>```

The question is how to implement getCurrentStageName(). I know, that I can get an access to build run-time using currentBuild.rawBuild.
But how to get stage name from that point?

I need this for some customization in email notifications, so that I can always catch failed stage name and include it into email body.

答:
You can now do this in a built-in manner, since Jenkins 2.3. Like so:

```<code>steps {
    updateGitlabCommitStatus name: STAGE_NAME, state: 'running'
    echo '${STAGE_NAME}'
}
</code>```

For more information see: https://issues.jenkins-ci.org/browse/JENKINS-44456

Body:
Let's say we have the following Jenkinsfile:

stage name: "Cool stage"
    sh 'whoami'
stage name: "Better stage"
    def current_stage = getCurrentStageName()
    echo "CONGRATULATIONS, you are on stage: $current_stage"

The question is how to implement getCurrentStageName(). I know, that I can get an access to build run-time using currentBuild.rawBuild.
But how to get stage name from that point?

I need this for some customization in email notifications, so that I can always catch failed stage name and include it into email body.

Body:
You can now do this in a built-in manner, since Jenkins 2.3. Like so:

steps {
    updateGitlabCommitStatus name: STAGE_NAME, state: 'running'
    echo '${STAGE_NAME}'
}

For more information see: https://issues.jenkins-ci.org/browse/JENKINS-44456


问:
Shell Script writing output to a file
I have a shell script that extracts certain values from a text file (input to it via the terminal). The script does the extraction as intended except, it doesn't print the output to the file correctly.

The script is:

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

input_file=$1
while read -r LINE
do
IFS="=" read -r -a params <<< "$LINE"
if [ -n "${params[2]}" ]
    then
    IFS=" " read -r -a param_opcode <<< "${params[2]}"
    echo "${param_opcode}"
fi
done < "$input_file"
</code>```

The output on the terminal is as follows:

```<code>0xd2800140
0xd2800061
0x8b010000
0x8b000042
0xd1000821
0xd28001e5
0xd28000a6
0x9ac608a5
0xe7ff0010
0xe7ff0010
</code>```

However, when I try to write this to a text file bu doing:

```<code>echo "${param_opcodes}" > log.txt
</code>```

It prints only this to the file:

```<code>0xe7ff0010
</code>```

I tried >> but I don't want to append to it. I want the file to be overwritten every time, I run the script.

答:
Your redirection to log file isn't right because it's inside the while loop.
Use the redirection at the end of the while loop:

```<code>while read -r LINE; do
...
done < "$input_file" > "log.txt"
</code>```

Title: Shell Script writing output to a file

Body:
I have a shell script that extracts certain values from a text file (input to it via the terminal). The script does the extraction as intended except, it doesn't print the output to the file correctly.

The script is:

#!/bin/bash

input_file=$1
while read -r LINE
do
IFS="=" read -r -a params <<< "$LINE"
if [ -n "${params[2]}" ]
    then
    IFS=" " read -r -a param_opcode <<< "${params[2]}"
    echo "${param_opcode}"
fi
done < "$input_file"

The output on the terminal is as follows:

0xd2800140
0xd2800061
0x8b010000
0x8b000042
0xd1000821
0xd28001e5
0xd28000a6
0x9ac608a5
0xe7ff0010
0xe7ff0010

However, when I try to write this to a text file bu doing:

echo "${param_opcodes}" > log.txt

It prints only this to the file:

0xe7ff0010

I tried >> but I don't want to append to it. I want the file to be overwritten every time, I run the script.

Body:
Your redirection to log file isn't right because it's inside the while loop.
Use the redirection at the end of the while loop:

while read -r LINE; do
...
done < "$input_file" > "log.txt"


问:
PostgreSQL DB performance issues with thousands of connections and distributed transactions
We are trying to evaluate PostgreSQL DB as an alternative to Oracle database in our application. We use PostgreSQL 9.5 which is installed on a Linux machine with 128 GBs of memory, 32 CPU cores and SSD storage. Connection pools and distributed transactions are managed by JBoss 7 application server, SQL queries are generated/executed by Hibernate 4. Most tables have tens millions rows, one of them has hundreds millions rows. In total around 3,000 database connections (they are pooled by the application server) are active and used concurrently. We modified some queries, created indexes for slow ones, tuned DB and OS settings based on documentation, etc. However, throughput is few times slower and eventually DB response time increases 10-20 times.

I've done some googling and I couldn't find information about anyone else (ab)using PostgreSQL DB the same way:

using thousands of active database connections

using this high number of distributed transactions (PREPARED TRANSACTIONS)

storing billions of rows in one table

Oracle doesn't have any problem handling even higher load. I would appreciate sharing your experience, suggestions, links, etc.

Thanks

答:
The solution was upgrading the Linux kernel and decreasing the number of DB connections in our Java connection pools from 3000 to 300. After this change we could handle the same traffic as we could with Oracle DB.

By accident I have discovered a precious piece of information which lead to problem resolution in comments section for the post  Did I Say 32 Cores? How about 64? written by Robert Haas
(VP, Chief Architect, Database Server @ EnterpriseDB, PostgreSQL Major Contributor and Committer):

No, I'm saying that to get good performance on a 64-core server, you're going to need PostgreSQL >= 9.2 and Linux >= 3.2. Most of the changes are actually on the PostgreSQL side, but the lseek scaling stuff in the Linux kernel was important, too.