问:
Executing JavaScript present in a web page through Selenium
I am working on an automated script for filling up the details of the address of a person in a webpage. Note that I did not create this webpage. So while filling up the address, there is an option for Inserting the COUNTRY. I inspected this element and found that it had the "< input= .. " tag with the class name being "ComboSelect". So it is basically a dropdown menu but it populates as I type using a JavaScript file that has been linked to it (I did not write this JS File either).

My problem is I need to ensure that the country I type has to be present in the drop-down. Now here is the interesting thing: I inspected the element, clicked on "Console" and typed the following JavaScript method:

```<code>ns.Fields.isFieldValid("FieldName")
</code>```

This returns true if an only if the value I type the name of a country that is there in the list and returns false otherwise. However, I tried executing this by using the following code in Selenium:

```<code>FirefoxDriver driver = new FirefoxDriver();
driver.get(URL);
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("ns.Fields.isFieldValid("FieldName");
</code>```

This gave me a reference error saying that "ns" is not defined. Now I understand that the above JS code is considered to be a new Script written by me and here ns is not defines and hence I am getting this error.

So my question is how do I get to execute the code using the already present JS in the webpage because the code works in the browser console but does not work through selenium. Is there a way for me to run the above code in the Firefox's Console and get the result of true or false from it?

Firefox : 46.0.1

Selenium : 3.4.0

答:
Discalaimer

I create an answer since it would be too long for a comment though I think your question is an example of a X/Y problem and your question is not clear enough to be answered precisely or without spending too much effort (what I probably did) and at the risk of down-/closevotes since my answer is off the actual topic (but I do this deliberately).

Why is the scripting approach a bad idea?

Here are some reasons why is the scripting approach a bad idea for acceptance testing:

The application may change any time

Especially in the case you mentioned:

Note that I did not create this webpage.

Method/functions you call may have side effects (even though the name sounds clear a function might do something else when being called)

Real users won't interact in the way you do with scripting, you may miss

bugs or

bad user experience

(All aspects may also apply when using Selenium for non-testing automation.)

Attempt to help

Let me summarize what I think is unclear so far:

how does the interaction of that element look like (I'll make some assumptions)

how does the DOM look like during interaction (I'll make some assumptions)

what is the Selenium program used for: automation/scripting of form submission to massively create records or real end user / acceptance testing (I assume read testing)

But let me start assuming it's all about acceptance testing (many things also apply to pure automation too) ...

You wrote:

I am working on an automated script for filling up the details of the address of a person in a webpage. [...] So while filling up the address, there is an option for Inserting the COUNTRY. I inspected this element and found that it had the "< input= .. " tag with the class name being "ComboSelect".

And:

So it is basically a dropdown menu but it populates as I type [...]

I assume the interaction looks like this:

```<code>Country
[|            ]      Step 1 (empty input with cursor)

Country
[B|           ]      Step 2 (letter "B" entered)

Country
[Br|          ]      Step 3 (a proposal box opened)
+-------------+
|Braunschweig |
|Bremen       |
|Brandenburg  |
+-------------+

Country
[Bra|         ]      Step 4 (the proposals limited even more)
+-------------+
|Braunschweig |
|Brandenburg  |
+-------------+
</code>```

Assumption: that combobox is either realized via a <select> element with <option> elements or via a
,
 or other elements containg the list entries. (This is what you should clarify in you question actually.)

Let's assume it looks like this when "Braunschweig" was entered:

```<code><input type="text" />
<div class="search-proposals country">
    <ul>
        <li>Braunschweig</li>
    </ul>
</div>
</code>```

My problem is I need to ensure that the country I type has to be present in the drop-down.

I don't see why you can't just type the country ...

```<code>Country
[Zoesville    ]
</code>```

Assuming "Zoesville" does not exist.

Thus there's no entry in the proposals list. It's either empty

```<code><input type="text" />
<div class="search-proposals country">
    <ul>
    </ul>
</div>
</code>```

Or no proposal element at all is present:

```<code><input type="text" />
</code>```

You should now be able to detect the presence of By.cssSelector(".search-proposals.country li").

Of course, the application may also react with an empty or no proposal list if the entered country is correct. In this case that proposal element gives no indication/distinction of an correct/wrong input. The same counts for real users too: they will have a bad user experience.

Ususally there's some indication like a green check either when a valid value has been entered or at least when the field was blurred while focussing the next input. This is another element you can check for.

In case of real acceptance testing a missing validity indicator element would be worth a bug report / improvement.

But since this is speculation and so far only you know how that page works, I'll stop here.

Some words on your comments

In the comments you wrote:

[...] From what I saw there, I think the JS method is pulling the details from a JSON file resource (not available to me again) and choosing those countries that match to the letter I have typed.

and:

[...] Sometimes, Even after I type in my data, the page is still loading because of which the JS script at times gets skipped. So sometimes, the list populates but on rare occasions, the list does not populate at all so there is actually no way to determine if the country I have typed in is actually valid or not.

How can you be sure that the Javascript method will give you correct results when you can't rely on the UI either? In my opinion: you can't. You should either wait for an indication that the page finished loading or attempt to interact with it just like real users would do.

Warranty

I hope you have enough guidance now how to deal with such a situation without using scripting.

I'll not edit/update this answer if the problem description changes one-eighty. I consider adding updates for details on the mentioned unclear points though.

Body:
I am working on an automated script for filling up the details of the address of a person in a webpage. Note that I did not create this webpage. So while filling up the address, there is an option for Inserting the COUNTRY. I inspected this element and found that it had the "< input= .. " tag with the class name being "ComboSelect". So it is basically a dropdown menu but it populates as I type using a JavaScript file that has been linked to it (I did not write this JS File either).

My problem is I need to ensure that the country I type has to be present in the drop-down. Now here is the interesting thing: I inspected the element, clicked on "Console" and typed the following JavaScript method:

ns.Fields.isFieldValid("FieldName")

This returns true if an only if the value I type the name of a country that is there in the list and returns false otherwise. However, I tried executing this by using the following code in Selenium:

FirefoxDriver driver = new FirefoxDriver();
driver.get(URL);
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("ns.Fields.isFieldValid("FieldName");

This gave me a reference error saying that "ns" is not defined. Now I understand that the above JS code is considered to be a new Script written by me and here ns is not defines and hence I am getting this error.

So my question is how do I get to execute the code using the already present JS in the webpage because the code works in the browser console but does not work through selenium. Is there a way for me to run the above code in the Firefox's Console and get the result of true or false from it?

Firefox : 46.0.1

Selenium : 3.4.0

Body:
Discalaimer

I create an answer since it would be too long for a comment though I think your question is an example of a X/Y problem and your question is not clear enough to be answered precisely or without spending too much effort (what I probably did) and at the risk of down-/closevotes since my answer is off the actual topic (but I do this deliberately).

Why is the scripting approach a bad idea?

Here are some reasons why is the scripting approach a bad idea for acceptance testing:

The application may change any time

Especially in the case you mentioned:

Note that I did not create this webpage.

Method/functions you call may have side effects (even though the name sounds clear a function might do something else when being called)

Real users won't interact in the way you do with scripting, you may miss

bugs or

bad user experience

(All aspects may also apply when using Selenium for non-testing automation.)

Attempt to help

Let me summarize what I think is unclear so far:

how does the interaction of that element look like (I'll make some assumptions)

how does the DOM look like during interaction (I'll make some assumptions)

what is the Selenium program used for: automation/scripting of form submission to massively create records or real end user / acceptance testing (I assume read testing)

But let me start assuming it's all about acceptance testing (many things also apply to pure automation too) ...

You wrote:

I am working on an automated script for filling up the details of the address of a person in a webpage. [...] So while filling up the address, there is an option for Inserting the COUNTRY. I inspected this element and found that it had the "< input= .. " tag with the class name being "ComboSelect".

And:

So it is basically a dropdown menu but it populates as I type [...]

I assume the interaction looks like this:

Country
[|            ]      Step 1 (empty input with cursor)

Country
[B|           ]      Step 2 (letter "B" entered)

Country
[Br|          ]      Step 3 (a proposal box opened)
+-------------+
|Braunschweig |
|Bremen       |
|Brandenburg  |
+-------------+

Country
[Bra|         ]      Step 4 (the proposals limited even more)
+-------------+
|Braunschweig |
|Brandenburg  |
+-------------+

Assumption: that combobox is either realized via a <select> element with <option> elements or via a <div>, <ul> or other elements containg the list entries. (This is what you should clarify in you question actually.)

Let's assume it looks like this when "Braunschweig" was entered:

<input type="text" />
<div class="search-proposals country">
    <ul>
        <li>Braunschweig</li>
    </ul>
</div>

My problem is I need to ensure that the country I type has to be present in the drop-down.

I don't see why you can't just type the country ...

Country
[Zoesville    ]

Assuming "Zoesville" does not exist.

Thus there's no entry in the proposals list. It's either empty

<input type="text" />
<div class="search-proposals country">
    <ul>
    </ul>
</div>

Or no proposal element at all is present:

<input type="text" />

You should now be able to detect the presence of By.cssSelector(".search-proposals.country li").

Of course, the application may also react with an empty or no proposal list if the entered country is correct. In this case that proposal element gives no indication/distinction of an correct/wrong input. The same counts for real users too: they will have a bad user experience.

Ususally there's some indication like a green check either when a valid value has been entered or at least when the field was blurred while focussing the next input. This is another element you can check for.

In case of real acceptance testing a missing validity indicator element would be worth a bug report / improvement.

But since this is speculation and so far only you know how that page works, I'll stop here.

Some words on your comments

In the comments you wrote:

[...] From what I saw there, I think the JS method is pulling the details from a JSON file resource (not available to me again) and choosing those countries that match to the letter I have typed.

and:

[...] Sometimes, Even after I type in my data, the page is still loading because of which the JS script at times gets skipped. So sometimes, the list populates but on rare occasions, the list does not populate at all so there is actually no way to determine if the country I have typed in is actually valid or not.

How can you be sure that the Javascript method will give you correct results when you can't rely on the UI either? In my opinion: you can't. You should either wait for an indication that the page finished loading or attempt to interact with it just like real users would do.

Warranty

I hope you have enough guidance now how to deal with such a situation without using scripting.

I'll not edit/update this answer if the problem description changes one-eighty. I consider adding updates for details on the mentioned unclear points though.


来源: stackexchange

问:
Preview not Showing in Android 3.0 Canary
I have started using Latest Android Studio 3.0 but I am having a problem with Preview. It's not showing Preview in Preview Tab.
Here is what I have done

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white">

            <include
                android:id="@+id/activePlanCard"
                layout="@layout/layout_item_activated_plan" />

            <TextView
                android:id="@+id/DashView"
                android:layout_width="match_parent"
                android:layout_height="10dp"
                android:layout_below="@id/activePlanCard"
                android:background="@drawable/drw_dash_line" />

            <TextView
                android:id="@+id/provideAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/DashView"
                android:layout_margin="10dp"
                android:text="Provide Address Detail :" />
      </RelativeLayout>
    </ScrollView>
</layout>
</code>```

Your assistance in this matter will be greatly appreciated

Thanks..

答:
hey I had the same problem and i solved it like this:
in build.gradle(app) edit the following lines like this:

```<code>compileSdkVersion 25
buildToolsVersion '25.0.0'

targetSdkVersion 25

compile 'com.android.support:appcompat-v7:25.3.1'
</code>```

Hope it works for you!

ContentLicense: CC BY-SA 3.0

Body:
I have started using Latest Android Studio 3.0 but I am having a problem with Preview. It's not showing Preview in Preview Tab.
Here is what I have done

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white">

            <include
                android:id="@+id/activePlanCard"
                layout="@layout/layout_item_activated_plan" />

            <TextView
                android:id="@+id/DashView"
                android:layout_width="match_parent"
                android:layout_height="10dp"
                android:layout_below="@id/activePlanCard"
                android:background="@drawable/drw_dash_line" />

            <TextView
                android:id="@+id/provideAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/DashView"
                android:layout_margin="10dp"
                android:text="Provide Address Detail :" />
      </RelativeLayout>
    </ScrollView>
</layout>

Your assistance in this matter will be greatly appreciated

Thanks..

Body:
hey I had the same problem and i solved it like this:
in build.gradle(app) edit the following lines like this:

compileSdkVersion 25
buildToolsVersion '25.0.0'

targetSdkVersion 25

compile 'com.android.support:appcompat-v7:25.3.1'

Hope it works for you!


问:
How to Match a Regular Expression to Any Word in a String
I need to be able to search for the first name OR possible middle name and last name of a user and have it pop up in the search results. If my user in a test case is "Alicia Henderson", currently with the following code, I can grab anything from the letter A onward (i.e. Alic, Alicia Hen). However, I would like to be able to type in "H" and get Alicia Henderson (and all other cases in any other word in that may be in the users name. Similar to how Facebook, Twitter, and many other fantastic search engines have. Thanks in advance!</p>

```<code>    $("input[name='search_users']").keyup(function(){

        // Retrieve the input field text and reset the count to zero
        var filter = "^" + $(this).val(), itemsFound = 0;

        // Loop through each user
        $(".send_to .messages .message_username").each(function(){

            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).parent().css("display","none");

            // Show the list user if the phrase matches and increase the count by 1
            } else {
                $(this).parent().show();
                itemsFound++;
            }

        });

    });
</code>```

答:
You need to replace the start of string anchor with another pattern that will allow matching any whitespace or start of string anchor, OR - if you only work with ASCII letters - a word boundary \b.

The regex you need may also be necessary to escape properly (if it contains (, ), or other special regex chars. So, this is how the regex should be declared:

```<code> new RegExp( "(?:^|\\s)" + this.value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i" )
</code>```

Here, (?:^|\\s) is a non-capturing group (?:...) that matches either a string start position (^) or any whitespace (\\s) and the this.value special regex chars are escaped with escaping regex. The "i"  modifier makes the pattern case insensitive.

Here is a snippet showing how this regex works:

function filterUsers() {
    var rgx = new RegExp( "(?:^|\\s)" + this.value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i" );
    var $el = $(".message_username").hide().filter(function() {
      return  rgx.test( $(this).text() );
    }).show();
    $(this).next("span").text("Results:"+ $el.length);
}

$("input[name='search_users']").on("input", filterUsers);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" name="search_users"> <span></span>
<ul>
  <li class="message_username">Alicia Barson</li>
  <li class="message_username">Brittney Halley</li>
  <li class="message_username">Alicia Henderson</li>
  <li class="message_username">Sten Tong</li>
  <li class="message_username">Bung Gang</li>
  <li class="message_username">Jin Jang</li>
  <li class="message_username">John Supreme</li>
  <li class="message_username">Super Man</li>
  <li class="message_username">Man Chester</li>
  <li class="message_username">Super Alicia</li>
</ul>

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

Body:
I need to be able to search for the first name OR possible middle name and last name of a user and have it pop up in the search results. If my user in a test case is "Alicia Henderson", currently with the following code, I can grab anything from the letter A onward (i.e. Alic, Alicia Hen). However, I would like to be able to type in "H" and get Alicia Henderson (and all other cases in any other word in that may be in the users name. Similar to how Facebook, Twitter, and many other fantastic search engines have. Thanks in advance!

    $("input[name='search_users']").keyup(function(){

        // Retrieve the input field text and reset the count to zero
        var filter = "^" + $(this).val(), itemsFound = 0;

        // Loop through each user
        $(".send_to .messages .message_username").each(function(){

            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).parent().css("display","none");

            // Show the list user if the phrase matches and increase the count by 1
            } else {
                $(this).parent().show();
                itemsFound++;
            }

        });

    });

Body:
You need to replace the start of string anchor with another pattern that will allow matching any whitespace or start of string anchor, OR - if you only work with ASCII letters - a word boundary \b.

The regex you need may also be necessary to escape properly (if it contains (, ), or other special regex chars. So, this is how the regex should be declared:

 new RegExp( "(?:^|\\s)" + this.value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i" )

Here, (?:^|\\s) is a non-capturing group (?:...) that matches either a string start position (^) or any whitespace (\\s) and the this.value special regex chars are escaped with escaping regex. The "i"  modifier makes the pattern case insensitive.

Here is a snippet showing how this regex works:

function filterUsers() {
    var rgx = new RegExp( "(?:^|\\s)" + this.value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i" );
    var $el = $(".message_username").hide().filter(function() {
      return  rgx.test( $(this).text() );
    }).show();
    $(this).next("span").text("Results:"+ $el.length);
}

$("input[name='search_users']").on("input", filterUsers);

<input type="text" name="search_users"> <span></span>
<ul>
  <li class="message_username">Alicia Barson</li>
  <li class="message_username">Brittney Halley</li>
  <li class="message_username">Alicia Henderson</li>
  <li class="message_username">Sten Tong</li>
  <li class="message_username">Bung Gang</li>
  <li class="message_username">Jin Jang</li>
  <li class="message_username">John Supreme</li>
  <li class="message_username">Super Man</li>
  <li class="message_username">Man Chester</li>
  <li class="message_username">Super Alicia</li>
</ul>

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


问:
What is the purpose of using -pedantic in the GCC/G++ compiler?
This note says:

-ansi: tells the compiler to implement the ANSI language option. This turns
off certain "features" of GCC which
are incompatible with the ANSI
standard.

-pedantic: used in conjunction with -ansi, this tells the compiler to be adhere strictly to the ANSI standard,
rejecting any code which is not
compliant.

First things first:

What is the purpose of the -pedantic and -ansi options of the GCC/G++ compiler (I couldn't understand the above description)?

What are the right circumstances for using these two options?

When should I use them?

Are they important?

答:
GCC compilers always try to compile your program if this is at all possible. However, in some
cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers
such as GCC or g++ must issue a diagnostic when these extensions are encountered.

For example, the GCC compiler’s -pedantic option causes GCC to issue warnings in such cases. Using the stricter -pedantic-errors option converts such diagnostic warnings into errors that will cause compilation to fail at such points. Only those non-ISO constructs that are required to be flagged by a conforming compiler will generate warnings or errors.

ContentLicense: CC BY-SA 4.0


问:
Have text displayed instead of numerical values on y axis
Is it possible to display text instead of numerical values in the y axis of a line graph with Chart.JS?

Say that we have, for example, the following text-to-value mapping.

```<code> 0 = "sedentary"
 1 = "under-active"
 2 = "active"
 ....
</code>```

How can we display the words "sedentary", "under-active", etc instead of the numerical values in the following graph:

答:
Yes, it is possible, and you can achieve that using the userCallback function for y-axis ticks.

var mapText = ['sedentary', 'under-active', 'active', 'inactive'];
var chart = new Chart(canvas, {
   type: 'line',
   data: {
      labels: ['January', 'February', 'March', 'April'],
      datasets: [{
         label: 'Statistics',
         data: [3, 1, 2, 0],
         backgroundColor: 'rgba(0, 119, 204, 0.1)',
         borderColor: 'rgba(0, 119, 204, 0.8)',
         borderWidth: 1,
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               maxTicksLimit: 4, //set as the 'mapText' array length
               stepSize: 1,
               userCallback: function(t, i) {
                  return mapText[mapText.length - (i + 1)];
               }
            }
         }]
      }
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas></code>```

Body:
Is it possible to display text instead of numerical values in the y axis of a line graph with Chart.JS?

Say that we have, for example, the following text-to-value mapping.

 0 = "sedentary"
 1 = "under-active"
 2 = "active"
 ....

How can we display the words "sedentary", "under-active", etc instead of the numerical values in the following graph:

Body:
Yes, it is possible, and you can achieve that using the userCallback function for y-axis ticks.

var mapText = ['sedentary', 'under-active', 'active', 'inactive'];
var chart = new Chart(canvas, {
   type: 'line',
   data: {
      labels: ['January', 'February', 'March', 'April'],
      datasets: [{
         label: 'Statistics',
         data: [3, 1, 2, 0],
         backgroundColor: 'rgba(0, 119, 204, 0.1)',
         borderColor: 'rgba(0, 119, 204, 0.8)',
         borderWidth: 1,
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               maxTicksLimit: 4, //set as the 'mapText' array length
               stepSize: 1,
               userCallback: function(t, i) {
                  return mapText[mapText.length - (i + 1)];
               }
            }
         }]
      }
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>


问:
How to generate stats for a GitHub project?
Is there an easy/efficient way to generate some high-level reports for a particular GitHub project?

e.g. lines of code committed over time, top contributors, etc

答: I am the author of weave-gitstats. Its opensource and based on weave. Most git statistics generators like gitstats or the statistics provided by github are "static", they don't have drilldown functionality, filtering and are limited to some default graphs. Weave-gistats provides a lot of dynamic dashboards that allow you to filter on eg year, author and allow you to create your own graphs using your own criteria.</p>


问:
Insert a symbol ">" between the characters in a list of strings
I have a column in Excel like this:

```<code>ABC
BCD
BA
</code>```

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

```<code>A>B>C
B>C>D
B>A
</code>```

Or could we do this in Matlab ?

答:
In MATLAB (requires 17a for double quotes and 16b for strip/replace)

```<code>>> str = ["ABC"; "BCD"; "BA"];
>> str = strip(replace(str,'','>'),'>')

str =

  3×1 string array

    "A>B>C"
    "B>C>D"
    "B>A"
</code>```

Regexprep will work for older versions of MATLAB too

```<code>>> str = {'ABC';'BCD';'BA'};
>> str = regexprep(str,'(.)(?=.)','$1>')

str =

  3×1 cell array

    {'A>B>C'}
    {'B>C>D'}
    {'B>A'  }
</code>```

Body:
I have a column in Excel like this:

ABC
BCD
BA

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

A>B>C
B>C>D
B>A

Or could we do this in Matlab ?

Body:
In MATLAB (requires 17a for double quotes and 16b for strip/replace)

>> str = ["ABC"; "BCD"; "BA"];
>> str = strip(replace(str,'','>'),'>')

str =

  3×1 string array

    "A>B>C"
    "B>C>D"
    "B>A"

Regexprep will work for older versions of MATLAB too

>> str = {'ABC';'BCD';'BA'};
>> str = regexprep(str,'(.)(?=.)','$1>')

str =

  3×1 cell array

    {'A>B>C'}
    {'B>C>D'}
    {'B>A'  }


问:
Cannot push_back() a struct into an std::vector<std::shared_ptr<theStruct>> theVector
Hopefully my title isn't too confusing. I'm trying to write a sound manager for my game using SFML. I'm trying to replace my new/delete with the "smart pointer" std::shared_ptr. This is what I have so far.

```<code>/* SoundManager.h */
#ifndef SOUNDMANAGER_H
#define SOUNDMANAGER_H

#include <SFML/Audio.hpp>
#include <string>
#include <memory>

class SoundManager
{
    public:
        ~SoundManager();

        struct jteSound
        {
            sf::Sound snd;
            sf::SoundBuffer sndBuffer;
            std::string name;
        };

        //Load a new sound from path and store it in audio bank bnk.
        //Banks are simply std::vectors of type jteSound.
        void registerNewSound(std::vector<std::shared_ptr<jteSound>> &bnk, std::string path, std::string sndName);

        //Footsteps bank
        std::vector<std::shared_ptr<jteSound>> bnkFootsteps;
};

#endif // SOUNDMANAGER_H

/* SoundManager.cpp */
#include "SoundManager.h"
#include <stdlib.h>

SoundManager::~SoundManager()
{
    /*
    //Cleanup each sound bank that we use.
    for (std::vector<jteSound*>::iterator it = bnkFootsteps.begin(); it != bnkFootsteps.end(); ++it) {
        delete *it;
    }
    */
}

void SoundManager::registerNewSound(std::vector<std::shared_ptr<jteSound>> &bnk, std::string path, std::string sndName)
{
    static int counter = 0;
    for (int i = counter; counter <i+1; counter++) {
        bnk.push_back(jteSound);
        bnk[i]->name = sndName;
        bnk[i]->sndBuffer.loadFromFile(path);
        bnk[i]->snd.setBuffer(bnk[i]->sndBuffer);
    }
}
</code>```

bnk.push_back(jteSound); gives me a compiler error. If I remove the line, the program compiles, but crashes. I have tried things like emplace_back() or jteSound* or new jteSound, but nothing works. I always get a lengthy compiler error or immediate runtime crash. When I use regular pointers and new/delete, see https://bpaste.net/show/fa684f2f2d5e and https://bpaste.net/show/c74ac701ce7a, the code works as expected. Any thoughts appreciated!

答:
The type of the elements inside your std::vector is std::shared_ptr<jteSound> which means that std::vector::push_back will accept only instances of that type.

To make your code work you have two options. The first is using std::make_shared helper function as follows:

```<code>bnk.push_back(std::make_shared<jteSound>());

// the equivalent counterpart is:
bnk.push_back(std::shared_ptr<jteSound>(new jteSound));
</code>```

The second is using std::vector::emplace as follows:

```<code>bnk.emplace(bnk.end(), new jteSound);
</code>```

As the comments below warn, using the second option is risky because it can cause memory leak when the new jteSound succeeds but the std::vector::emplace has to reallocate memory and fails.

Body:
Hopefully my title isn't too confusing. I'm trying to write a sound manager for my game using SFML. I'm trying to replace my new/delete with the "smart pointer" std::shared_ptr. This is what I have so far.

/* SoundManager.h */
#ifndef SOUNDMANAGER_H
#define SOUNDMANAGER_H

#include <SFML/Audio.hpp>
#include <string>
#include <memory>

class SoundManager
{
    public:
        ~SoundManager();

        struct jteSound
        {
            sf::Sound snd;
            sf::SoundBuffer sndBuffer;
            std::string name;
        };

        //Load a new sound from path and store it in audio bank bnk.
        //Banks are simply std::vectors of type jteSound.
        void registerNewSound(std::vector<std::shared_ptr<jteSound>> &bnk, std::string path, std::string sndName);

        //Footsteps bank
        std::vector<std::shared_ptr<jteSound>> bnkFootsteps;
};

#endif // SOUNDMANAGER_H

/* SoundManager.cpp */
#include "SoundManager.h"
#include <stdlib.h>

SoundManager::~SoundManager()
{
    /*
    //Cleanup each sound bank that we use.
    for (std::vector<jteSound*>::iterator it = bnkFootsteps.begin(); it != bnkFootsteps.end(); ++it) {
        delete *it;
    }
    */
}

void SoundManager::registerNewSound(std::vector<std::shared_ptr<jteSound>> &bnk, std::string path, std::string sndName)
{
    static int counter = 0;
    for (int i = counter; counter name = sndName;
        bnk[i]->sndBuffer.loadFromFile(path);
        bnk[i]->snd.setBuffer(bnk[i]->sndBuffer);
    }
}

bnk.push_back(jteSound); gives me a compiler error. If I remove the line, the program compiles, but crashes. I have tried things like emplace_back() or jteSound* or new jteSound, but nothing works. I always get a lengthy compiler error or immediate runtime crash. When I use regular pointers and new/delete, see https://bpaste.net/show/fa684f2f2d5e and https://bpaste.net/show/c74ac701ce7a, the code works as expected. Any thoughts appreciated!

Body:
The type of the elements inside your std::vector is std::shared_ptr<jteSound> which means that std::vector::push_back will accept only instances of that type.

To make your code work you have two options. The first is using std::make_shared helper function as follows:

bnk.push_back(std::make_shared<jteSound>());

// the equivalent counterpart is:
bnk.push_back(std::shared_ptr<jteSound>(new jteSound));

The second is using std::vector::emplace as follows:

bnk.emplace(bnk.end(), new jteSound);

As the comments below warn, using the second option is risky because it can cause memory leak when the new jteSound succeeds but the std::vector::emplace has to reallocate memory and fails.


问:
make carousel centered in page?
```<code><div id="imageCarousel" class="carousel slide" data-interval="3000" data-ride="carousel">

                <ol class="carousel-indicators">
                  <li data-target="#imageCarousel" data-slide-to="0" class="active"></li>
                  <li data-target="#imageCarousel" data-slide-to="1"></li>
                  <li data-target="#imageCarousel" data-slide-to="2"></li>
                </ol>

                <div class="carousel-inner">

                  <div class="item active">
                    <img src="pics/space_1.jpg" alt="Space 1">
                    <div class="carousel-caption">
                      <h3>Space 1</h3>
                      <p>Infinite Boredom</p>
                    </div>
                  </div>

                  <div class="item">
                    <img src="pics/space_2.jpg" alt="Space 2">
                    <div class="carousel-caption">
                      <h3>Space 2</h3>
                      <p>Infinite Boredom</p>
                    </div>
                  </div>

                  <div class="item">
                    <img src="pics/space_3.jpg" alt="Space 3">
                    <div class="carousel-caption">
                      <h3>Space 3</h3>
                      <p>Infinite Boredom</p>
                    </div>
                  </div>

                </div>

                <a href="#imageCarousel" class="carousel-control left" data-slide="prev">
                  <span class="glyphicon glyphicon-chevron-left"></span>
                </a>

                <a href="#imageCarousel" class="carousel-control right" data-slide="next">
                  <span class="glyphicon glyphicon-chevron-right"></span>
                </a>

              </div>

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

I have a bootstrap carousel that is working fine. However, when I make my window fullscreen, it does not span the entire width of the page. What styling would I use in order to do this?

答:
Make sure you are following the correct nesting conventions. There may be an issue with your ".container" or ".container-fluid".

For more, reference: http://getbootstrap.com/css/#grid

Title: make carousel centered in page?

Body:
Space 1

Infinite Boredom

Space 2

Infinite Boredom

Space 3

Infinite Boredom

I have a bootstrap carousel that is working fine. However, when I make my window fullscreen, it does not span the entire width of the page. What styling would I use in order to do this?


问:
How to convert DateTime to Date
How can I convert Date to DateTime and vice versa?

E.g.

```<code>Date dt = new Date();
</code>```

Now I want to covert this to DateTime.

Also

```<code>DateTime dtim = new DateTime();
</code>```

Now I want to convert it to Date.

答:
As skaffman said above

```<code>dateTime.toDate()
</code>```

should do the trick. But keep in mind that if the dateTime object had a different timezone than the user's current timezone, dateTime.toDate() will return the date object in user's timezone.
ie

```<code>DateTime newDate = new DateTime().toDateTime(DateTimeZone.forID("America/Los_Angeles"));
System.out.println(newDate);
System.out.println(newDate.toDate());
</code>```

This will print

2017-07-05T14:19:23.294-07:00

Wed Jul 05 15:19:23 MDT 2017

as my system time is in MDT

ContentLicense: CC BY-SA 2.5

Title: How to convert DateTime to Date

Body:
How can I convert Date to DateTime and vice versa?

E.g.

Date dt = new Date();

Now I want to covert this to DateTime.

Also

DateTime dtim = new DateTime();

Now I want to convert it to Date.

Body:
As skaffman said above

dateTime.toDate()

should do the trick. But keep in mind that if the dateTime object had a different timezone than the user's current timezone, dateTime.toDate() will return the date object in user's timezone.
ie

DateTime newDate = new DateTime().toDateTime(DateTimeZone.forID("America/Los_Angeles"));
System.out.println(newDate);
System.out.println(newDate.toDate());

This will print

2017-07-05T14:19:23.294-07:00

Wed Jul 05 15:19:23 MDT 2017

as my system time is in MDT


问:
Removing/disabling backticks on variable in Active Record query in CodeIgniter
I'm trying to make a "between" query on my database using the Query Class of CodeIgniter, however, when adding a variable to the where clause, it adds backticks to the variable.

```<code>$this->db->select(TABLE_DISCOUNTSCARRIER.'.discount')->select(TABLE_DISCOUNTSCARRIER.'.idCarrier')
$this->db->from(TABLE_DISCOUNTSCARRIER);
$this->db->join(TABLE_DISCOUNTS, TABLE_DISCOUNTSCARRIER.'.idDiscount='.TABLE_DISCOUNTS.'.idDiscount');
$this->db->where(TABLE_DISCOUNTSCARRIER.'.idCarrier', $carrier);
$this->db->where($data['from'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');
$this->db->or_where($data['to'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');
</code>```

Which is being parsed into this (the last two lines)

```<code>SELECT
    discountbycarrier.discount,
    discountbycarrier.idCarrier
FROM (discountbycarrier)
JOIN discounts
ON discountbycarrier.idDiscount=discounts.idDiscount
WHERE `discountbycarrier`.`idCarrier` = '6'
AND `5` BETWEEN discounts.from AND discounts.to
OR `10` BETWEEN discounts.from AND discounts.to
</code>```

Already tried setting the $this->db->_protect_identifiers=false; but it removes the backticks on the rest of the statements but not the variables. Already tried using the intval() of the variable but neither this works.
As you can see the variable $carrier is correctly being parsed as integer.
Any ideas? Thanks in advance.

答:
Change this

```<code>   discounts.from
</code>```

to

```<code>  discounts.`from`
</code>```

Or better (best practice) don't use reserved keywords for table columns, the word FROM is part of the query language, in other words.

Backticks are used to escape reserved keywords and spaces.

UPDATE

Something like this ( although I didn't look the documentation )

```<code>  $this->db->where('? BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to', $data['from']);
</code>```

Body:
I'm trying to make a "between" query on my database using the Query Class of CodeIgniter, however, when adding a variable to the where clause, it adds backticks to the variable.

$this->db->select(TABLE_DISCOUNTSCARRIER.'.discount')->select(TABLE_DISCOUNTSCARRIER.'.idCarrier')
$this->db->from(TABLE_DISCOUNTSCARRIER);
$this->db->join(TABLE_DISCOUNTS, TABLE_DISCOUNTSCARRIER.'.idDiscount='.TABLE_DISCOUNTS.'.idDiscount');
$this->db->where(TABLE_DISCOUNTSCARRIER.'.idCarrier', $carrier);
$this->db->where($data['from'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');
$this->db->or_where($data['to'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');

Which is being parsed into this (the last two lines)

SELECT
    discountbycarrier.discount,
    discountbycarrier.idCarrier
FROM (discountbycarrier)
JOIN discounts
ON discountbycarrier.idDiscount=discounts.idDiscount
WHERE `discountbycarrier`.`idCarrier` = '6'
AND `5` BETWEEN discounts.from AND discounts.to
OR `10` BETWEEN discounts.from AND discounts.to

Already tried setting the $this->db->_protect_identifiers=false; but it removes the backticks on the rest of the statements but not the variables. Already tried using the intval() of the variable but neither this works.
As you can see the variable $carrier is correctly being parsed as integer.
Any ideas? Thanks in advance.

Body:
Change this

   discounts.from

to

  discounts.`from`

Or better (best practice) don't use reserved keywords for table columns, the word FROM is part of the query language, in other words.

Backticks are used to escape reserved keywords and spaces.

UPDATE

Something like this ( although I didn't look the documentation )

  $this->db->where('? BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to', $data['from']);


问:
request.getHeader("Referer") is not working
I was using the following code to get the previous url in my jsp.

```<code> String Str = new String(request.getHeader("Referer"));
 out.println("Str:"+Str);
</code>```

Str returns the correct url every time except while clicking on browser back button. Why is this happening? Or how can I get the previous url this time?

答:
Based on Encoding Sensitive Information in URI's

Clients SHOULD NOT include a Referer header field in a (non-secure)
  HTTP request if the referring page was transferred with a secure
  protocol.

Authors of services which use the HTTP protocol SHOULD NOT use GET
  based forms for the submission of sensitive data, because this will
  cause this data to be encoded in the Request-URI.

Probably in POST redirected requests you may get it.

Body:
I was using the following code to get the previous url in my jsp.

 String Str = new String(request.getHeader("Referer"));
 out.println("Str:"+Str);

Str returns the correct url every time except while clicking on browser back button. Why is this happening? Or how can I get the previous url this time?


问:
How do I implement Windows style for a dialog box in C++?
I have searched for an answer on the Internet, but with exceptions of the difference between modal and modaless dialog boxes, I couldn't find anything useful for my question.

As written in the title, my question is - how can I implement/use a Windows version specific design for my dialog box?  IOW, use the Windows 10 button style on a Windows 10 system.

I am using Visual Studio, and I have created a simple resource for my dialog using the integrated resource editor.

Here is my programm:

```<code>int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL);
    system("pause");
    return 0;
}
</code>```

Right now, when I compile this code, the console and the dialog box appear on the screen, but the dialog box controls (buttons) seem to be shown in the Windows 2000 style. I'm using Windows 10.

I have this style:

I want this style:

答:
You need to opt in to comctl32 v6 in your manifest: Enabling Visual Styles.

To enable your application to use visual styles, you must use
  ComCtl32.dll version 6 or later. Because version 6 is not
  redistributable, it is available only when your application is running
  on a version of Windows that contains it. Windows ships with both
  version 5 and version 6. ComCtl32.dll version 6 contains both the user
  controls and the common controls. By default, applications use the
  user controls defined in User32.dll and the common controls defined in
  ComCtl32.dll version 5. For a list of DLL versions and their
  distribution platforms, see Common Control Versions.

If you want your application to use visual styles, you must add an
  application manifest or compiler directive that indicates that
  ComCtl32.dll version 6 should be used if it is available.

An application manifest enables an application to specify which
  versions of an assembly it requires. In Microsoft Win32, an assembly
  is a set of DLLs and a list of versionable objects that are contained
  within those DLLs.

Body:
I have searched for an answer on the Internet, but with exceptions of the difference between modal and modaless dialog boxes, I couldn't find anything useful for my question.

As written in the title, my question is - how can I implement/use a Windows version specific design for my dialog box?  IOW, use the Windows 10 button style on a Windows 10 system.

I am using Visual Studio, and I have created a simple resource for my dialog using the integrated resource editor.

Here is my programm:

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL);
    system("pause");
    return 0;
}

Right now, when I compile this code, the console and the dialog box appear on the screen, but the dialog box controls (buttons) seem to be shown in the Windows 2000 style. I'm using Windows 10.

I have this style:

I want this style:


问:
Can't get jquery $ajax to call .NET MVC 2 controller method
I'm new to jquery and ajax - just can't seem to get this to work!  See my related question: Use Json and AjaxLink to Toggle Link Values in ASP.NET MVC 2

Here's my jquery:

```<code>$(function () {
    $("div[id^=add]").click(function (ev) {
        ev.preventDefault();
        updateMe(this.id.split('_')[1], "AddRequirement");
    });

    $("div[id^=remove]").click(function (ev) {
        ev.preventDefault();
        updateMe(this.id.split('_')[1], "RemoveRequirement");
    });
});

function updateMe(myId, myAction) {
    $.ajax({
        type: "POST",
        url: "AgreementType.aspx/" + myAction,
        data: 'aId=' + <%:Model.AgreementType.Id%> + '&rId=' + myId,
        dataType: "text",
        error: function(request, msg){
            alert( "Error upon saving request: " + msg );
        },
        success: function (data) {
            alert(data);
        }
    });
}
</code>```

Currently I have a two different divs.  A foreach loop determines which one to display:

```<code><%if(req.Agreements.Any(r => r.AgreementTypeId == Model.AgreementType.AgreementTypeId))
    {%>
        <div id="<%:string.Format("remove_{0}", req.Id)%>" class="divLink">Remove</div>
    <% }
    else
    { %>
        <div id="<%:string.Format("add_{0}", req.Id)%>" class="divLink">Add</div>
    <%{%>
</code>```

Here's my controller action.  Pretty simple:

```<code>    public JsonResult AddRequirement(string aId, string rId)
    {
        string result = "Remove";
        //Code to add requirement

        return this.Json(result);
    }

    public JsonResult RemoveRequirement(string aID, string rID)
    {
        string result = "Add";
        //Code to remove requirement

        return this.Json(result);
    }
}
</code>```

All the success function needs to do it update the innerHtml of the target with the contents, and change the id to match.  Seems so easy!  And yet I can't seem to figure it out.  TIA

答:
Finally - the code that works.  This will allow the user to click on a div which will call a different controller method based on the contents of that div, in effect allowing you to toggle toggle elements of the object in a foreach loop.  I'm sure it could be improved upon; for instance, I probably don't need to get the value of the div from the controller method, but at least it works.

Javascript

```<code><script type="text/javascript">
    $(function () {
        $("div[class^=toggleLink]").click(function (ev) {
            ev.preventDefault();

            var divText = $('#' + this.id).text();

            if (divText == "Remove") {
                updateMe(this.id, "Remove");
            }
            else if (divText == "Add") {
                updateMe(this.id, "Add");
            }
        });
    });

function updateMe(myId, myAction) {
    $.ajax(
    {
        type: "POST",
        url: "/AgreementType/" + myAction,
        data: "aId=<%:Model.AgreementType.Id%>&rId=" + myId,
        success: function (result) {
            if (result.success) {
                $('div#' + myId).text(result.value);
            }
        },
        error: function (req, status, error) {
            alert(req + " " + status + " " + error);
        }
    });
}

</script>
</code>```

Controller

```<code>    public ActionResult Add(string aId, string rId)
    {
        //Add to the template

        string result = "Remove";
        string nClass = "remLink";

        return Json(new { success = true, value = result, newClass = nClass });
    }

    public ActionResult Remove(string aID, string rId)
    {
        //Remove from the template

        string result = "Add";
        string nClass = "addLink";

        return Json(new { success = true, value = result, newClass = nClass });
    }
</code>```

Markup

```<code><% foreach(var req in std.Requirements)%>
   <% { %>
   <tr>
       <td>
       <%if(req.Agreements.Any(r => r.AgreementTypeId == Model.AgreementType.Id))
       {%>
           <div id="<%:req.Id%>" class="toggleLink">Remove</div>
       <% }
       else { %>
           <div id="<%:req.Id%>" class="toggleLink">Add</div>
       <%} %>
</code>```

Body:
I'm new to jquery and ajax - just can't seem to get this to work!  See my related question: Use Json and AjaxLink to Toggle Link Values in ASP.NET MVC 2

Here's my jquery:

$(function () {
    $("div[id^=add]").click(function (ev) {
        ev.preventDefault();
        updateMe(this.id.split('_')[1], "AddRequirement");
    });

    $("div[id^=remove]").click(function (ev) {
        ev.preventDefault();
        updateMe(this.id.split('_')[1], "RemoveRequirement");
    });
});

function updateMe(myId, myAction) {
    $.ajax({
        type: "POST",
        url: "AgreementType.aspx/" + myAction,
        data: 'aId=' + <%:Model.AgreementType.Id%> + '&rId=' + myId,
        dataType: "text",
        error: function(request, msg){
            alert( "Error upon saving request: " + msg );
        },
        success: function (data) {
            alert(data);
        }
    });
}

Currently I have a two different divs.  A foreach loop determines which one to display:

<%if(req.Agreements.Any(r => r.AgreementTypeId == Model.AgreementType.AgreementTypeId))
    {%>
        <div id="<%:string.Format("remove_{0}", req.Id)%>" class="divLink">Remove

    <% }
    else
    { %>
        <div id="<%:string.Format("add_{0}", req.Id)%>" class="divLink">Add

    <%{%>

Here's my controller action.  Pretty simple:

    public JsonResult AddRequirement(string aId, string rId)
    {
        string result = "Remove";
        //Code to add requirement

        return this.Json(result);
    }

    public JsonResult RemoveRequirement(string aID, string rID)
    {
        string result = "Add";
        //Code to remove requirement

        return this.Json(result);
    }
}

All the success function needs to do it update the innerHtml of the target with the contents, and change the id to match.  Seems so easy!  And yet I can't seem to figure it out.  TIA

Body:
Finally - the code that works.  This will allow the user to click on a div which will call a different controller method based on the contents of that div, in effect allowing you to toggle toggle elements of the object in a foreach loop.  I'm sure it could be improved upon; for instance, I probably don't need to get the value of the div from the controller method, but at least it works.

Javascript

<script type="text/javascript">
    $(function () {
        $("div[class^=toggleLink]").click(function (ev) {
            ev.preventDefault();

            var divText = $('#' + this.id).text();

            if (divText == "Remove") {
                updateMe(this.id, "Remove");
            }
            else if (divText == "Add") {
                updateMe(this.id, "Add");
            }
        });
    });

function updateMe(myId, myAction) {
    $.ajax(
    {
        type: "POST",
        url: "/AgreementType/" + myAction,
        data: "aId=<%:Model.AgreementType.Id%>&rId=" + myId,
        success: function (result) {
            if (result.success) {
                $('div#' + myId).text(result.value);
            }
        },
        error: function (req, status, error) {
            alert(req + " " + status + " " + error);
        }
    });
}

</script>

Controller

    public ActionResult Add(string aId, string rId)
    {
        //Add to the template

        string result = "Remove";
        string nClass = "remLink";

        return Json(new { success = true, value = result, newClass = nClass });
    }

    public ActionResult Remove(string aID, string rId)
    {
        //Remove from the template

        string result = "Add";
        string nClass = "addLink";

        return Json(new { success = true, value = result, newClass = nClass });
    }

Markup

<% foreach(var req in std.Requirements)%>
   <% { %>
   <tr>
       <td>
       <%if(req.Agreements.Any(r => r.AgreementTypeId == Model.AgreementType.Id))
       {%>
           <div id="<%:req.Id%>" class="toggleLink">Remove</div>
       <% }
       else { %>
           <div id="<%:req.Id%>" class="toggleLink">Add</div>
       <%} %>


问:
Spring Boot (2.0.0.BUILD-SNAPSHOT) application can't start with Jetty
I want to start a Spring Boot application but it is not possible due to:

```<code>Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-07-05 15:51:19.216 ERROR 10080 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:137) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1233) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at io.sc.pps.Application.main(Application.java:42) [main/:na]
Caused by: java.lang.ExceptionInInitializerError: null
    at org.eclipse.jetty.servlet.ServletContextHandler.newSessionHandler(ServletContextHandler.java:296) ~[jetty-servlet-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.servlet.ServletContextHandler.getSessionHandler(ServletContextHandler.java:391) ~[jetty-servlet-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.servlet.ServletContextHandler.relinkHandlers(ServletContextHandler.java:199) ~[jetty-servlet-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.servlet.ServletContextHandler.<init>(ServletContextHandler.java:171) ~[jetty-servlet-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.webapp.WebAppContext.<init>(WebAppContext.java:289) ~[jetty-webapp-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.webapp.WebAppContext.<init>(WebAppContext.java:211) ~[jetty-webapp-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.springframework.boot.web.embedded.jetty.JettyEmbeddedWebAppContext.<init>(JettyEmbeddedWebAppContext.java:28) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory.getWebServer(JettyServletWebServerFactory.java:155) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:161) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:134) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    ... 8 common frames omitted
Caused by: java.lang.SecurityException: class "javax.servlet.http.HttpSessionIdListener"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:898) ~[na:1.8.0_131]
    at java.lang.ClassLoader.preDefineClass(ClassLoader.java:668) ~[na:1.8.0_131]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:761) ~[na:1.8.0_131]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_131]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_131]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_131]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_131]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_131]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_131]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_131]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_131]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_131]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_131]
    at org.eclipse.jetty.server.session.SessionHandler.<clinit>(SessionHandler.java:140) ~[jetty-server-9.4.6.v20170531.jar:9.4.6.v20170531]
    ... 18 common frames omitted

Disconnected from the target VM, address: '127.0.0.1:52640', transport: 'socket'

Process finished with exit code 1
</code>```

I have never seen such error before and researching it does not lead to any working solution(s).

Do somebody know what's going on here?

Update

My Gradle Dependencies:

```<code>repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
    maven { url "http://download.osgeo.org/webdav/geotool" }
    maven { url "http://www.hibernatespatial.org/repository" }
    maven { url "http://repo.boundlessgeo.com/main/" }
    maven { url "http://www.datanucleus.org/downloads/maven2/" }
    maven { url "http://oss.jfrog.org/artifactory/oss-snapshot-local/" }
}

dependencyManagement {
    dependencies {
        dependencySet (group: 'org.hibernate', version: '5.2.8.Final') {
            entry 'hibernate-core'
            entry 'hibernate-entitymanager'
            entry 'hibernate-spatial'
        }

        dependency (group: 'io.prometheus', name: 'simpleclient_spring_boot', version: '0.0.21')

        dependencySet (group: 'io.github.resilience4j', version: '0.9.0-SNAPSHOT') {
            entry 'resilience4j-spring-boot'
            entry 'resilience4j-metrics'
            entry 'resilience4j-prometheus'
        }

        dependencySet (group: 'org.apache.ignite', version: '1.9.0') {
            entry 'ignite-core'
            entry 'ignite-spring'
            entry 'ignite-rest-http'
        }
    }
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-hateoas')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-jetty')
    compile('org.springframework.boot:spring-boot-starter-webflux')
    compile('org.springframework.boot:spring-boot-starter-actuator')

    compile('io.prometheus:simpleclient_spring_boot')

    compile('io.github.resilience4j:resilience4j-spring-boot') {
        exclude group: 'org.slf4j'
    }

    compile('io.github.resilience4j:resilience4j-metrics') {
        exclude group: 'org.slf4j'
    }

    compile('io.github.resilience4j:resilience4j-prometheus') {
        exclude group: 'org.slf4j'
    }

    compile('org.apache.ignite:ignite-core')
    compile('org.apache.ignite:ignite-spring')
//    compile('org.apache.ignite:ignite-rest-http')

    compile('com.h2database:h2')

    compile(group: 'org.apache.hive', name: 'hive-jdbc', version: '2.1.1') {
        exclude group: 'org.slf4j'
    }

    compile(group: 'org.springframework.data', name: 'spring-data-hadoop', version: '2.4.0.RELEASE')
    compile(group: 'org.springframework.data', name: 'spring-data-hadoop-config', version: '2.4.0.RELEASE')

    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('junit:junit')
}
</code>```

答:
Caused by: java.lang.SecurityException: class "javax.servlet.http.HttpSessionIdListener"'s signer information does not match signer information of other classes in the same package

That means you have the javax.servlet.http.HttpSessionIdListener in your classpath more then once (and one or more of them are in a signed jar file).

Cleanup your dependencies, ensure you only have a single servlet-api jar.

Since you are using Jetty 9.4.6, the servlet-api 3.1 jar coordinates on central.maven.org are ...

```<code>compile 'javax.servlet:javax.servlet-api:3.1.0'
</code>```

How to list all jars with class

Create a class to dump the locations of the class you are interested in.  This is created as a junit testcase so it can be run within the same gradle dependencies as your project.

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

import javax.servlet.http.HttpSessionIdListener;

import org.junit.Test;

public class ClasspathTest
{
    @Test
    public void testJavaServlet() throws IOException
    {
        ClassLoader cl = this.getClass().getClassLoader();
        String classAsResource = HttpSessionIdListener.class.getName().replace('.','/') + ".class";
        Enumeration<URL> urls = cl.getResources(classAsResource);
        System.out.printf("Looking for: %s%n",classAsResource);
        while (urls.hasMoreElements())
        {
            URL url = urls.nextElement();
            System.out.printf("Found: %s%n",url.toExternalForm());
        }
    }
}
```

Body:
I want to start a Spring Boot application but it is not possible due to:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-07-05 15:51:19.216 ERROR 10080 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:137) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1233) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at io.sc.pps.Application.main(Application.java:42) [main/:na]
Caused by: java.lang.ExceptionInInitializerError: null
    at org.eclipse.jetty.servlet.ServletContextHandler.newSessionHandler(ServletContextHandler.java:296) ~[jetty-servlet-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.servlet.ServletContextHandler.getSessionHandler(ServletContextHandler.java:391) ~[jetty-servlet-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.servlet.ServletContextHandler.relinkHandlers(ServletContextHandler.java:199) ~[jetty-servlet-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.servlet.ServletContextHandler.<init>(ServletContextHandler.java:171) ~[jetty-servlet-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.webapp.WebAppContext.<init>(WebAppContext.java:289) ~[jetty-webapp-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.eclipse.jetty.webapp.WebAppContext.<init>(WebAppContext.java:211) ~[jetty-webapp-9.4.6.v20170531.jar:9.4.6.v20170531]
    at org.springframework.boot.web.embedded.jetty.JettyEmbeddedWebAppContext.<init>(JettyEmbeddedWebAppContext.java:28) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory.getWebServer(JettyServletWebServerFactory.java:155) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:161) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:134) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    ... 8 common frames omitted
Caused by: java.lang.SecurityException: class "javax.servlet.http.HttpSessionIdListener"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:898) ~[na:1.8.0_131]
    at java.lang.ClassLoader.preDefineClass(ClassLoader.java:668) ~[na:1.8.0_131]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:761) ~[na:1.8.0_131]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_131]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_131]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_131]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_131]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_131]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_131]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_131]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_131]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_131]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_131]
    at org.eclipse.jetty.server.session.SessionHandler.<clinit>(SessionHandler.java:140) ~[jetty-server-9.4.6.v20170531.jar:9.4.6.v20170531]
    ... 18 common frames omitted

Disconnected from the target VM, address: '127.0.0.1:52640', transport: 'socket'

Process finished with exit code 1

I have never seen such error before and researching it does not lead to any working solution(s).

Do somebody know what's going on here?

Update

My Gradle Dependencies:

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
    maven { url "http://download.osgeo.org/webdav/geotool" }
    maven { url "http://www.hibernatespatial.org/repository" }
    maven { url "http://repo.boundlessgeo.com/main/" }
    maven { url "http://www.datanucleus.org/downloads/maven2/" }
    maven { url "http://oss.jfrog.org/artifactory/oss-snapshot-local/" }
}

dependencyManagement {
    dependencies {
        dependencySet (group: 'org.hibernate', version: '5.2.8.Final') {
            entry 'hibernate-core'
            entry 'hibernate-entitymanager'
            entry 'hibernate-spatial'
        }

        dependency (group: 'io.prometheus', name: 'simpleclient_spring_boot', version: '0.0.21')

        dependencySet (group: 'io.github.resilience4j', version: '0.9.0-SNAPSHOT') {
            entry 'resilience4j-spring-boot'
            entry 'resilience4j-metrics'
            entry 'resilience4j-prometheus'
        }

        dependencySet (group: 'org.apache.ignite', version: '1.9.0') {
            entry 'ignite-core'
            entry 'ignite-spring'
            entry 'ignite-rest-http'
        }
    }
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-hateoas')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-jetty')
    compile('org.springframework.boot:spring-boot-starter-webflux')
    compile('org.springframework.boot:spring-boot-starter-actuator')

    compile('io.prometheus:simpleclient_spring_boot')

    compile('io.github.resilience4j:resilience4j-spring-boot') {
        exclude group: 'org.slf4j'
    }

    compile('io.github.resilience4j:resilience4j-metrics') {
        exclude group: 'org.slf4j'
    }

    compile('io.github.resilience4j:resilience4j-prometheus') {
        exclude group: 'org.slf4j'
    }

    compile('org.apache.ignite:ignite-core')
    compile('org.apache.ignite:ignite-spring')
//    compile('org.apache.ignite:ignite-rest-http')

    compile('com.h2database:h2')

    compile(group: 'org.apache.hive', name: 'hive-jdbc', version: '2.1.1') {
        exclude group: 'org.slf4j'
    }

    compile(group: 'org.springframework.data', name: 'spring-data-hadoop', version: '2.4.0.RELEASE')
    compile(group: 'org.springframework.data', name: 'spring-data-hadoop-config', version: '2.4.0.RELEASE')

    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('junit:junit')
}

Body:
Caused by: java.lang.SecurityException: class "javax.servlet.http.HttpSessionIdListener"'s signer information does not match signer information of other classes in the same package

That means you have the javax.servlet.http.HttpSessionIdListener in your classpath more then once (and one or more of them are in a signed jar file).

Cleanup your dependencies, ensure you only have a single servlet-api jar.

Since you are using Jetty 9.4.6, the servlet-api 3.1 jar coordinates on central.maven.org are ...

compile 'javax.servlet:javax.servlet-api:3.1.0'

How to list all jars with class

Create a class to dump the locations of the class you are interested in.  This is created as a junit testcase so it can be run within the same gradle dependencies as your project.

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

import javax.servlet.http.HttpSessionIdListener;

import org.junit.Test;

public class ClasspathTest
{
    @Test
    public void testJavaServlet() throws IOException
    {
        ClassLoader cl = this.getClass().getClassLoader();
        String classAsResource = HttpSessionIdListener.class.getName().replace('.','/') + ".class";
        Enumeration<URL> urls = cl.getResources(classAsResource);
        System.out.printf("Looking for: %s%n",classAsResource);
        while (urls.hasMoreElements())
        {
            URL url = urls.nextElement();
            System.out.printf("Found: %s%n",url.toExternalForm());
        }
    }
}


问:
How to temporarily open a Word document and use it to copy-paste a range?
I have formatted cells that I wish to copy and paste into an html form.

If I copy the contents to a Word document and paste them from there to an html form, it works.

If I copy the contents directly from the spreadsheet into the html form, the formatting is lost.

If the range is in the clipboard after copying from a Word document, I can paste it to the html form.

I need a way to copy the range to clipboard and retain the formatting. Since from Word it works, that's where I'm starting... but if there is another way...

I'm thinking of either an embed word file, or a hidden one.

Copy cell, paste there, select all and copy from there. Afterwards, close/discard it.

EDIT: Managed to get some code... but it worked, then stopped, then worked again... no idea why...

```<code>Sub TempDoc()

Dim WDApp As Word.Application
Dim WDDoc As Word.Document

    Application.ScreenUpdating = False

Set WDObj = Sheets("Text2Form").OLEObjects("WDOC")

WDObj.Activate
WDObj.Object.Application.Visible = False

Set WDApp = GetObject(, "Word.Application")
Set WDDoc = WDApp.ActiveDocument

    WDApp.Visible = False

Worksheets("Text2Form").Cells(12, 4).Copy
    WDApp.Selection.Goto What:=wdGoToLine, Which:=wdGoToLast
    WDApp.Selection.PasteSpecial xlPasteValues

WDApp.ActiveDocument.Content.InsertAfter vbNewLine

Worksheets("Text2Form").Cells(14, 4).Copy
    WDApp.Selection.Goto What:=wdGoToLine, Which:=wdGoToLast
    WDApp.Selection.PasteSpecial xlPasteValues

WDDoc.Content.Copy
WDDoc.Content.Delete

WDApp.Quit
Application.ScreenUpdating = True

End Sub
</code>```

答: Have you tried right-clicking on the cell you wish to paste into, and clicking "Paste Special"?</p>

Body:
I have formatted cells that I wish to copy and paste into an html form.

If I copy the contents to a Word document and paste them from there to an html form, it works.

If I copy the contents directly from the spreadsheet into the html form, the formatting is lost.

If the range is in the clipboard after copying from a Word document, I can paste it to the html form.

I need a way to copy the range to clipboard and retain the formatting. Since from Word it works, that's where I'm starting... but if there is another way...

I'm thinking of either an embed word file, or a hidden one.

Copy cell, paste there, select all and copy from there. Afterwards, close/discard it.

EDIT: Managed to get some code... but it worked, then stopped, then worked again... no idea why...

Sub TempDoc()

Dim WDApp As Word.Application
Dim WDDoc As Word.Document

    Application.ScreenUpdating = False

Set WDObj = Sheets("Text2Form").OLEObjects("WDOC")

WDObj.Activate
WDObj.Object.Application.Visible = False

Set WDApp = GetObject(, "Word.Application")
Set WDDoc = WDApp.ActiveDocument

    WDApp.Visible = False

Worksheets("Text2Form").Cells(12, 4).Copy
    WDApp.Selection.Goto What:=wdGoToLine, Which:=wdGoToLast
    WDApp.Selection.PasteSpecial xlPasteValues

WDApp.ActiveDocument.Content.InsertAfter vbNewLine

Worksheets("Text2Form").Cells(14, 4).Copy
    WDApp.Selection.Goto What:=wdGoToLine, Which:=wdGoToLast
    WDApp.Selection.PasteSpecial xlPasteValues

WDDoc.Content.Copy
WDDoc.Content.Delete

WDApp.Quit
Application.ScreenUpdating = True

End Sub


问:
Azure Load Balancer keeps socket on server side open after timeout
The timeout documentation says that the client receives an error when the clients sends data to the load balancer.

When the connection is closed, your client application may receive the following error message: "The underlying connection was closed: A connection that was expected to be kept alive was closed by the server."

But our service-fabric endpoint still has that tcp socket open that already timed-out, even for days now.

The client just sent a TCP CLOSE after the timeout was already applied.

Why does the load balancer not inform the service fabric node that tcp connection was closed because of timeout?

Can the windows OS on the service fabric node close the socket after a timeout of no activity? Found a TCP Keep-alive documentation, be tcp-keepalive feature is currently not usable by our application.

答: Load Balancer does not send TCP RST when sessions are idle timed out.  Please investigate with Service Fabric how to manage this scenario and enable sending of TCP keep-alives.</p>