问:
How to get the video id from a YouTube URL with regex in Java
Porting from javascript answer to Java version
JavaScript REGEX: How do I get the YouTube video id from a URL?</p>

答:
Update 26 Mar 2023

Support live & shorts video

Regex

```<code>https://youtube.com/live/eLlxrBmD3H4
https://www.youtube.com/live/eLlxrBmD3H4
https://youtu.be/live/eLlxrBmD3H4

https://youtube.com/shorts/FnURdCtTvTU?feature=share

</code>```
```<code>http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|(?:be-nocookie|be)\.com\/(?:watch|[\w]+\?(?:feature=[\w]+.[\w]+\&)?v=|v\/|e\/|embed\/|live\/|shorts\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)

</code>```

Update 21 Oct 2022

As this post getting attention from people, I am going to update to serve more cases, thanks to @Nikhil Seban for your new links, the Java code is remained thanks to guys provide code @Leap Bun  @Pankaj

This regex also use match group(1), please take a look on the bottom

Regex Online Here

```<code>http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|(?:be-nocookie|be)\.com\/(?:watch|[\w]+\?(?:feature=[\w]+.[\w]+\&)?v=|v\/|e\/|embed\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)
</code>```
```<code>http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=pJegNopBLL8
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
https://www.youtube.com/watch?v=0zM4nApSvMg&feature=youtu.be
https://www.youtube.com/watch?v=_5BTo2oZ0SE
https://m.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE
https://m.youtube.com/watch?v=_5BTo2oZ0SE
https://www.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE&app=desktop
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=eLlxrBmD3H4

https://www.youtube.com/watch?v=DFYRQ_zQ-gk&feature=featured
https://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
https://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
https://www.youtube.com/embed/DFYRQ_zQ-gk?autoplay=1
https://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
https://youtu.be/DFYRQ_zQ-gk?t=120
https://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
https://www.youtube.com/HamdiKickProduction?v=DFYRQ_zQ-gk
https://www.youtube.com/watch?v=wz4MLJBdSpw&t=67s
http://www.youtube.com/watch?v=dQw4w9WgXcQ&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
https://www.youtube.com/watch?v=EL-UCUAt8DQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://youtu.be/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ

https://www.youtube-nocookie.com/embed/xHkq1edcbk4?rel=0

http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
</code>```

Old post

This below code you can also use either review what I have updated or to develop new pattern.

```<code>http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|be\.com\/(?:watch\?(?:feature=youtu.be\&)?v=|v\/|embed\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)
</code>```

This will work for

```<code>http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=pJegNopBLL8
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
https://www.youtube.com/watch?v=0zM4nApSvMg&feature=youtu.be
https://www.youtube.com/watch?v=_5BTo2oZ0SE
https://m.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE
https://m.youtube.com/watch?v=_5BTo2oZ0SE
https://www.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE&app=desktop
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=eLlxrBmD3H4
</code>```

Note: Using regex match group(1) to get ID

```<code>public static String getVideoId(@NonNull String videoUrl) {
    String videoId = "";
    String regex = PLEASE_COPY_ABOVE_REGEX_PATTERN
    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(url);
    if(matcher.find()){
        videoId = matcher.group(1);
    }
    return videoId;
}
</code>```

Body:
Update 26 Mar 2023

Support live & shorts video

Regex

https://youtube.com/live/eLlxrBmD3H4
https://www.youtube.com/live/eLlxrBmD3H4
https://youtu.be/live/eLlxrBmD3H4

https://youtube.com/shorts/FnURdCtTvTU?feature=share

http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|(?:be-nocookie|be)\.com\/(?:watch|[\w]+\?(?:feature=[\w]+.[\w]+\&)?v=|v\/|e\/|embed\/|live\/|shorts\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)

Update 21 Oct 2022

As this post getting attention from people, I am going to update to serve more cases, thanks to @Nikhil Seban for your new links, the Java code is remained thanks to guys provide code @Leap Bun  @Pankaj

This regex also use match group(1), please take a look on the bottom

Regex Online Here

http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|(?:be-nocookie|be)\.com\/(?:watch|[\w]+\?(?:feature=[\w]+.[\w]+\&)?v=|v\/|e\/|embed\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)

http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=pJegNopBLL8
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
https://www.youtube.com/watch?v=0zM4nApSvMg&feature=youtu.be
https://www.youtube.com/watch?v=_5BTo2oZ0SE
https://m.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE
https://m.youtube.com/watch?v=_5BTo2oZ0SE
https://www.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE&app=desktop
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=eLlxrBmD3H4

https://www.youtube.com/watch?v=DFYRQ_zQ-gk&feature=featured
https://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
https://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
https://www.youtube.com/embed/DFYRQ_zQ-gk?autoplay=1
https://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
https://youtu.be/DFYRQ_zQ-gk?t=120
https://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
https://www.youtube.com/HamdiKickProduction?v=DFYRQ_zQ-gk
https://www.youtube.com/watch?v=wz4MLJBdSpw&t=67s
http://www.youtube.com/watch?v=dQw4w9WgXcQ&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
https://www.youtube.com/watch?v=EL-UCUAt8DQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://youtu.be/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ

https://www.youtube-nocookie.com/embed/xHkq1edcbk4?rel=0

http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg

Old post

This below code you can also use either review what I have updated or to develop new pattern.

http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|be\.com\/(?:watch\?(?:feature=youtu.be\&)?v=|v\/|embed\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)

This will work for

http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=pJegNopBLL8
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
https://www.youtube.com/watch?v=0zM4nApSvMg&feature=youtu.be
https://www.youtube.com/watch?v=_5BTo2oZ0SE
https://m.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE
https://m.youtube.com/watch?v=_5BTo2oZ0SE
https://www.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE&app=desktop
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=eLlxrBmD3H4

Note: Using regex match group(1) to get ID

public static String getVideoId(@NonNull String videoUrl) {
    String videoId = "";
    String regex = PLEASE_COPY_ABOVE_REGEX_PATTERN
    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(url);
    if(matcher.find()){
        videoId = matcher.group(1);
    }
    return videoId;
}


来源: stackexchange

问:
DSA verification calculation
Am I missing something? from FIPS180-2, on page 25, it gives the values of u1, u2, g^u1 mod p, y^u2 mod p and v. i have calculated all the values except v. yet, when i do the math, my calculations refuse to be v = 0x8bac1ab66410435cb7181f95b16ab97c92b341c0. instead, i get v = 0xc5a54698ae8e5b94661134260594ff4e3f488e26, which is not equal to r, from before. im doing (pow(g, u1, p) * pow(y, u2, p)) % q to do the calculation, where pow is the builtin function, not the math module function

答:
You're skipping one mod p calculation. You should compute:

(((pow(g, u1, p) * pow(y, u2, p))) % p ) % q

ContentLicense: CC BY-SA 2.5

Title: DSA verification calculation


问:
Change
 height using CSS
I have seen a question here about the same, but I can't get any of the answers to work (at least on Chrome).

This question is only for
, I know plenty of other techniques to change the height but in this case I can't change the HTML.

```<code>bla<BR><BR>bla<BR>bla<BR><BR>bla
</code>```

CSS:

br {
  display: block;
  margin-bottom: 2px;
  font-size:2px;
  line-height: 2px;
}
```

Desired effect: smaller inter-line height.

The only thing I can get to work is display:none, but then all line break are removed.

Here's a fiddle for it using some of the techniques, but see that it renders the exact same as without any CSS.

答:
The BR is anything but 'extra-special': it is still a valid XML tag that you can give attributes to. For example, you don't have to encase it with a span to change the line-height, rather you can apply the line height directly to the element.

You could do it with inline CSS:

This is a small line

break. Whereas, this is a BIG line

break!```
</div>
</div>
</p>

<p>Notice how two line breaks were used instead of one. This is because of how CSS inline elements work. Unfourtunately, the most awesome css feature possible (the <code>lh</code> unit) is still not there yet with any browser compatibility as of 2019. Thus, I have to use JavaScript for the demo below.</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-js lang-js prettyprint-override"><code>addEventListener("load", function(document, getComputedStyle){"use strict";
  var allShowLineHeights = document.getElementsByClassName("show-lh");
  for (var i=0; i < allShowLineHeights.length; i=i+1|0) {
    allShowLineHeights[i].textContent = getComputedStyle(
      allShowLineHeights[i]
    ).lineHeight;
  }
}.bind(null, document, getComputedStyle), {once: 1, passive: 1});</code>```

.show-lh {padding: 0 .25em}
.r {background: #f77}
.g {background: #7f5}
.b {background: #7cf}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>This is a small line
<span class="show-lh r"></span><br /><span class="show-lh r"></span>
break. Whereas, this is a BIG line
<span class="show-lh g"></span><br /><span class="show-lh g"></span>
<span class="show-lh b"></span><br style="line-height:40vh"/><span class="show-lh b"></span>
break!</code>```

You can even use any CSS selectors you want like ID's and classes.

#biglinebreakid {
  line-height: 450%;
  // 9x the normal height of a line break!
}
.biglinebreakclass {
  line-height: 1em;
  // you could even use calc!
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>This is a small line
<br />
break. Whereas, this is a BIG line
<br />
<br id="biglinebreakid" />
break! You can use any CSS selectors you want for things like this line
<br />
<br class="biglinebreakclass" />
break!</code>```

You can find our more about line-height at the W3C docs.

Basically, BR tags are not some void in world of CSS styling: they still can be styled. However, I would recommend only using line-height to style BR tags. They were never intended to be anything more than a line-break, and as such they might not always work as expected when using them as something else. Observe how even after applying tons of visual effects, the line break is still invisible:

#paddedlinebreak {
  display: block;
  width: 6em;
  height: 6em;
  background: orange;
  line-height: calc(6em + 100%);
  outline: 1px solid red;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="outline: 1px solid yellow;margin:1em;display:inline-block;overflow:visible">
This is a padded line
<br id="paddedlinebreak" />
break.
</div></code>```

A work-around for things such as margins and paddings is to instead style a span with a br in it like so.

#paddedlinebreak {
  background: orange;
  line-height: calc(6em + 100%);
  padding: 3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="outline: 1px solid yellow;margin:1em;display:inline-block;overflow:visible">
This is a padded line
<span id="paddedlinebreak"><br /></span>
break.
</div></code>```

Notice how the orange blob above is the span that contains the br.

ContentLicense: CC BY-SA 4.0

Title: Change <br> height using CSS

Body:
I have seen a question here about the same, but I can't get any of the answers to work (at least on Chrome).

This question is only for
, I know plenty of other techniques to change the height but in this case I can't change the HTML.

bla

bla
bla

bla

CSS:

br {
  display: block;
  margin-bottom: 2px;
  font-size:2px;
  line-height: 2px;
}

Desired effect: smaller inter-line height.

The only thing I can get to work is display:none, but then all line break are removed.

Here's a fiddle for it using some of the techniques, but see that it renders the exact same as without any CSS.

Body:
The BR is anything but 'extra-special': it is still a valid XML tag that you can give attributes to. For example, you don't have to encase it with a span to change the line-height, rather you can apply the line height directly to the element.

You could do it with inline CSS:

This is a small line
<br />
break. Whereas, this is a BIG line
<br />
<br style="line-height:40vh"/>
break!

Notice how two line breaks were used instead of one. This is because of how CSS inline elements work. Unfourtunately, the most awesome css feature possible (the lh unit) is still not there yet with any browser compatibility as of 2019. Thus, I have to use JavaScript for the demo below.

addEventListener("load", function(document, getComputedStyle){"use strict";
  var allShowLineHeights = document.getElementsByClassName("show-lh");
  for (var i=0; i < allShowLineHeights.length; i=i+1|0) {
    allShowLineHeights[i].textContent = getComputedStyle(
      allShowLineHeights[i]
    ).lineHeight;
  }
}.bind(null, document, getComputedStyle), {once: 1, passive: 1});

.show-lh {padding: 0 .25em}
.r {background: #f77}
.g {background: #7f5}
.b {background: #7cf}

This is a small line
<span class="show-lh r"></span><br /><span class="show-lh r"></span>
break. Whereas, this is a BIG line
<span class="show-lh g"></span><br /><span class="show-lh g"></span>
<span class="show-lh b"></span><br style="line-height:40vh"/><span class="show-lh b"></span>
break!

You can even use any CSS selectors you want like ID's and classes.

#biglinebreakid {
  line-height: 450%;
  // 9x the normal height of a line break!
}
.biglinebreakclass {
  line-height: 1em;
  // you could even use calc!
}

This is a small line
<br />
break. Whereas, this is a BIG line
<br />
<br id="biglinebreakid" />
break! You can use any CSS selectors you want for things like this line
<br />
<br class="biglinebreakclass" />
break!

You can find our more about line-height at the W3C docs.

Basically, BR tags are not some void in world of CSS styling: they still can be styled. However, I would recommend only using line-height to style BR tags. They were never intended to be anything more than a line-break, and as such they might not always work as expected when using them as something else. Observe how even after applying tons of visual effects, the line break is still invisible:

#paddedlinebreak {
  display: block;
  width: 6em;
  height: 6em;
  background: orange;
  line-height: calc(6em + 100%);
  outline: 1px solid red;
  border: 1px solid green;
}

<div style="outline: 1px solid yellow;margin:1em;display:inline-block;overflow:visible">
This is a padded line
<br id="paddedlinebreak" />
break.
</div>

A work-around for things such as margins and paddings is to instead style a span with a br in it like so.

#paddedlinebreak {
  background: orange;
  line-height: calc(6em + 100%);
  padding: 3em;
}

<div style="outline: 1px solid yellow;margin:1em;display:inline-block;overflow:visible">
This is a padded line
<span id="paddedlinebreak"><br /></span>
break.
</div>

Notice how the orange blob above is the span that contains the br.


问:
Void function is throwing a "no return statement" warning
So I have the following function, evidently a void:

```<code>static void *CpuStatsTestLoop (void *arg){
    UNUSED (arg);

    rtems_object_set_name(rtems_task_self(), "CPU Usage Thread");

    while (1)
    {
        sleep (CPU_USAGE_REPORT_INTERVAL_SECS);
        rtems_cpu_usage_report();
        rtems_cpu_usage_reset();
    }
}
</code>```

and it throws

"cpu_stats.c:98:1: warning: no return statement in function returning non-void [-Wreturn-type]".

I've tried adding a blank return and return 0 with no luck.

Any idea about why it's throwing this error, and how to fix?

答:
This function has a return type of void *, i.e. a pointer of any type, not void, so it must return a value.

You could fix this by changing the return type to void.  However, it looks like this function is meant to be invoked as a thread, in which case it has to have a signature of void *(*)(void *), so if that's the case changing the return type is not an option.

Given that this function has a while (1) loop it should never return.  Still, the function needs to return something, so put return NULL; at the bottom.  That will satisfy the compiler, and it will act as a safety catch in case you later introduce a bug that causes you to break out of the loop.

ContentLicense: CC BY-SA 3.0

Body:
So I have the following function, evidently a void:

static void *CpuStatsTestLoop (void *arg){
    UNUSED (arg);

    rtems_object_set_name(rtems_task_self(), "CPU Usage Thread");

    while (1)
    {
        sleep (CPU_USAGE_REPORT_INTERVAL_SECS);
        rtems_cpu_usage_report();
        rtems_cpu_usage_reset();
    }
}

and it throws

"cpu_stats.c:98:1: warning: no return statement in function returning non-void [-Wreturn-type]".

I've tried adding a blank return and return 0 with no luck.

Any idea about why it's throwing this error, and how to fix?


问:
Read/Write XLSM using POI
I'm using POI in my c# code for few weeks, and i've found and issue i don't manage to solve: Xlsm.

I've to open an xlsm template, edit it and save it. The template contains Macro, but i just add data into the xlsm file.
Actually, I think that Read and Edit are working find (thanks to debugging in vs), the issue is when I try to write...
The code is working, there is no error, but when I Try to open it with Excel, it crashes..

```<code>FileStream temp = new FileStream(xlsm_file, FileMode.Open, FileAccess.ReadWrite);
XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.Create(temp);
XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
workbook.SetSheetName(0, sheetname.Substring(0, Math.Min(sheetname.Length, 30)));
temp.Close();
FileStream toWrite = new FileStream(xlsm_file, FileMode.Open, FileAccess.ReadWrite);
workbook.Write(toWrite);
toWrite.Close();
</code>```

for example, even this crashes..

Is anyone having an Idea?
Thanks !

答:
you need to write your macro embedded file in appropriate format for example I read .xltm file and write with its MIME type of .xltm . see the below function

```<code>     public ActionResult DownloadXLTMFile()
            {
                try
                {
                  //Get your macro enabled file after manipulation
                   MemoryStream excelMS =  .....
                   //Using Resposne Stream to Make File Available for User to Download;
                    Response.Clear();

                    Response.ContentType = "application/vnd.ms-excel.template.macroEnabled.12";
                    Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",  "YourFileName.xltm"));

                    Response.BinaryWrite(excelMS.ToArray());
                    Response.End();
                }
                catch (Exception Ex)
                {  }
                finally
                {}
                return View();
            }
</code>```

you can find your appropriate MIME type here

Title: Read/Write XLSM using POI

Body:
I'm using POI in my c# code for few weeks, and i've found and issue i don't manage to solve: Xlsm.

I've to open an xlsm template, edit it and save it. The template contains Macro, but i just add data into the xlsm file.
Actually, I think that Read and Edit are working find (thanks to debugging in vs), the issue is when I try to write...
The code is working, there is no error, but when I Try to open it with Excel, it crashes..

FileStream temp = new FileStream(xlsm_file, FileMode.Open, FileAccess.ReadWrite);
XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.Create(temp);
XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
workbook.SetSheetName(0, sheetname.Substring(0, Math.Min(sheetname.Length, 30)));
temp.Close();
FileStream toWrite = new FileStream(xlsm_file, FileMode.Open, FileAccess.ReadWrite);
workbook.Write(toWrite);
toWrite.Close();

for example, even this crashes..

Is anyone having an Idea?
Thanks !

Body:
you need to write your macro embedded file in appropriate format for example I read .xltm file and write with its MIME type of .xltm . see the below function

     public ActionResult DownloadXLTMFile()
            {
                try
                {
                  //Get your macro enabled file after manipulation
                   MemoryStream excelMS =  .....
                   //Using Resposne Stream to Make File Available for User to Download;
                    Response.Clear();

                    Response.ContentType = "application/vnd.ms-excel.template.macroEnabled.12";
                    Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",  "YourFileName.xltm"));

                    Response.BinaryWrite(excelMS.ToArray());
                    Response.End();
                }
                catch (Exception Ex)
                {  }
                finally
                {}
                return View();
            }

you can find your appropriate MIME type here


问:
sum by group including intermediate groups
I have:

```<code>df <- data.frame(group=c(1,1,2,4,4,5), value=c(3,1,5,2,3,6))
aggregate(value ~ group, data = df, FUN = 'sum')

  group value
1  1     4
2  2     5
3  4     5
4  5     6
</code>```

is there a way to include intermediate groups to return the below? I realise this could be done by creating a dataframe with all the desired groups and matching in the results from aggregate() but I am hoping there is a cleaner way to do this. it would need to be as fast as using aggregate and only use base r packages - this is due to restrictions in my workplace.

```<code>  group value
1  1     4
2  2     5
3  3     0
4  4     5
5  5     6
</code>```

答:
You can use mergefrom base R. I've changed the name of your data.frame to dat, since df is the name of an R function.

```<code>dat <- read.table(text = "
group value
  1     4
  2     5
  4     5
  5     6
", header = TRUE)
str(dat)

res <- aggregate(value ~ group, data = dat, FUN = 'sum')
merge(res, data.frame(group = seq(from = min(res$group), to = max(res$group))), all = TRUE)
</code>```

Note that there will be a NA, not a zero. I believe that you should solve that by leaving it as a missing value.

Body:
I have:

df <- data.frame(group=c(1,1,2,4,4,5), value=c(3,1,5,2,3,6))
aggregate(value ~ group, data = df, FUN = 'sum')

  group value
1  1     4
2  2     5
3  4     5
4  5     6

is there a way to include intermediate groups to return the below? I realise this could be done by creating a dataframe with all the desired groups and matching in the results from aggregate() but I am hoping there is a cleaner way to do this. it would need to be as fast as using aggregate and only use base r packages - this is due to restrictions in my workplace.

  group value
1  1     4
2  2     5
3  3     0
4  4     5
5  5     6

Body:
You can use mergefrom base R. I've changed the name of your data.frame to dat, since df is the name of an R function.

dat <- read.table(text = "
group value
  1     4
  2     5
  4     5
  5     6
", header = TRUE)
str(dat)

res <- aggregate(value ~ group, data = dat, FUN = 'sum')
merge(res, data.frame(group = seq(from = min(res$group), to = max(res$group))), all = TRUE)

Note that there will be a NA, not a zero. I believe that you should solve that by leaving it as a missing value.


问:
Api Management sets forward-request for a one way request
I want to log to log the request and the response so I place a one-way-request in the inbound and the outbound section:

```<code><policies>
    <inbound>
        <send-one-way-request mode="new">
            <set-url>@("example.com")</set-url>
            <set-method>POST</set-method>
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>@(context.Request.Body.As<string>(preserveContent: true))</set-body>
        </send-one-way-request>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <send-one-way-request mode="new">
            <set-url>@("example.com")</set-url>
            <set-method>POST</set-method>
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>@(context.Response.Body.As<string>(preserveContent: true))</set-body>
        </send-one-way-request>
    </outbound>
</policies>
</code>```

identical call, except the body.

When I check the trace I see this in the inbound section:

send-one-way-request (0 ms)

```<code>"One way request was successfully send to https://...."
</code>```

forward-request (9690 ms)

```<code>{
    "response": {
        "status": {
            "code": 200,
            "reason": "OK"
        },
        "headers": [
            {
                "name": "Pragma",
                "value": "no-cache"
            },
            {
                "name": "Content-Length",
                "value": "2"
            },
            {
                "name": "Cache-Control",
                "value": "no-cache"
            },
            {
                "name": "Content-Type",
                "value": "application/json; charset=utf-8"
            },
            {
                "name": "Date",
                "value": "Wed, 05 Jul 2017 07:56:14 GMT"
            },
            {
                "name": "Expires",
                "value": "-1"
            },
            {
                "name": "Server",
                "value": "Microsoft-IIS/8.0"
            },
            {
                "name": "X-AspNet-Version",
                "value": "4.0.30319"
            },
            {
                "name": "X-Powered-By",
                "value": "ASP.NET"
            }
        ]
    }
}
</code>```

but in the outbound I only get:

send-one-way-request (0 ms)

```<code>"One way request was successfully send to https://...."
</code>```

and no forward request. Because I use a one way request I don't expect a response from the calls and I can't remember to have the forward-request in the inbound part (didn't found them in a saved traced call with a one way request in the inbound).

Is there maybe a configuration anything else that triggers a forward-request?

Edit:

I use the azure function to handle this. When I make a typo in the subdomain the forward-request disappears, but when I make a typo in the function name it is still there... Both requests are directed to the same azure function.

Edit2:

This is getting more confuse: when I send the default body from the swagger file the request-forward is not there. If I repeat the request or if i modify the default body it appears...

答:
Since send-one-way request policy is completely asynchronous in regards to request processing itself, there is no guarantee that reply from such request will be logged, because by the time it is received the request itself may be long processed, response returned to client along with tracing information. So it works as a best effort, if by the time when response to send-one-way-request is received the main request is still being processed response will be logged, otherwise not.

In the first example reply to one-way request in inbound is logged because there is still a lot processing to be done on the main request - send request to backend, process outbound section. But when one-way request is placed as the last statement in outbound, right before response to the client is sent - response to one-way request will come too late to be placed into trace.

Typo in subdomain may trigger longer connection time, if such domain not actively refuses connections, thus will stall response, thus it will disappear from trace.

It's all a question of timing. If you want to make sure that main request processing is stalled until you get response from these side requests use send-request policy instead.

Body:
I want to log to log the request and the response so I place a one-way-request in the inbound and the outbound section:

<policies>
    <inbound>
        <send-one-way-request mode="new">
            <set-url>@("example.com")</set-url>
            <set-method>POST</set-method>
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>@(context.Request.Body.As<string>(preserveContent: true))</set-body>
        </send-one-way-request>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <send-one-way-request mode="new">
            <set-url>@("example.com")</set-url>
            <set-method>POST</set-method>
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>@(context.Response.Body.As<string>(preserveContent: true))</set-body>
        </send-one-way-request>
    </outbound>
</policies>

identical call, except the body.

When I check the trace I see this in the inbound section:

send-one-way-request (0 ms)

"One way request was successfully send to https://...."

forward-request (9690 ms)

{
    "response": {
        "status": {
            "code": 200,
            "reason": "OK"
        },
        "headers": [
            {
                "name": "Pragma",
                "value": "no-cache"
            },
            {
                "name": "Content-Length",
                "value": "2"
            },
            {
                "name": "Cache-Control",
                "value": "no-cache"
            },
            {
                "name": "Content-Type",
                "value": "application/json; charset=utf-8"
            },
            {
                "name": "Date",
                "value": "Wed, 05 Jul 2017 07:56:14 GMT"
            },
            {
                "name": "Expires",
                "value": "-1"
            },
            {
                "name": "Server",
                "value": "Microsoft-IIS/8.0"
            },
            {
                "name": "X-AspNet-Version",
                "value": "4.0.30319"
            },
            {
                "name": "X-Powered-By",
                "value": "ASP.NET"
            }
        ]
    }
}

but in the outbound I only get:

send-one-way-request (0 ms)

"One way request was successfully send to https://...."

and no forward request. Because I use a one way request I don't expect a response from the calls and I can't remember to have the forward-request in the inbound part (didn't found them in a saved traced call with a one way request in the inbound).

Is there maybe a configuration anything else that triggers a forward-request?

Edit:

I use the azure function to handle this. When I make a typo in the subdomain the forward-request disappears, but when I make a typo in the function name it is still there... Both requests are directed to the same azure function.

Edit2:

This is getting more confuse: when I send the default body from the swagger file the request-forward is not there. If I repeat the request or if i modify the default body it appears...


问:
Can I detect XHTML parsing errors using Javascript?
When I have a markup error in my XHTML page, Mozilla Firefox displays the "Yellow Screen of Death", showing only a large red error message on a yellow background.

While these errors are rare, they are extremely user-unfriendly.

Is there a way I can detect these using Javascript, and thereby send a message back to the server?

What I've discovered so far:
 - Scripts placed before the parsing error still run. (Of course.)
 - Timeouts and intervals that were set in these scripts will still execute after the parsing error.
 - In Firefox, the DOM is a <parsererror> with a <sourcetext> inside it. I can detect this if I query document.firstChild.tagName.

Remaining questions:
 - What events are available that I could listen for to detect this happening? (Polling sucks.)
 - How can I detect this in other browsers?

答:
I know it's probably not the most helpful answer, but have you considered switching to a transitional doctype?

By all means, put your files through a parser to detect errors, but do it offline - the risk of showing users the YSOD is not worth it!

OwnerDisplayName: phyzome

OwnerDisplayName: nickf


问:
How to make your c# app work as windows service?
How to make your c# app work as windows service? (matereals, todos wanted)</p>

答: There is lots of info about that on MSDN: Windows Service Applications</p>


问:
Count participants of tournament
i have schema like this http://sqlfiddle.com/#!17/30859/1, as you can see in that SQL fiddle i have query that i need to improve, actually i need to add new column that will give me total number of participants in each tournament, i'm not sure how i can do that, i tried sub select but without any success. Thanks in advance for help</p>

答:
```<code>SELECT t.id, t.name as tournamentName, m.name as creator, s.name as
sponsorName,
(count * from member_tournament mt where mt.tournament_id=t.id) members
FROM tournament t
LEFT JOIN member m ON m.id = t.member_id
LEFT JOIN sponsor s ON s.id = t.sponsor_id
</code>```

Title: Count participants of tournament


问:
How to remove dupes from blocks of text
What's a smart and easy way to remove dupes within blocks within a file of text. Each block is separated by two newlines.

BEFORE:

```<code>apple
banana
apple
cherry
cherry

delta
epsilon
delta
epsilon

apple pie
delta
delta
</code>```

AFTER:

```<code>apple
banana
cherry

delta
epsilon

apple pie
delta
</code>```

Thanks. Should work on a Mac. Allow unicode. Any shell method/language/command. Dupes are not necessarily consecutive. Bonus if you ignore leading/trailing whitespace, or can use a comma as the delimiter within a record.

答:
Given:

```<code>$ cat file
apple
banana
apple
cherry
cherry

delta
epsilon
delta
epsilon

apple pie
delta
delta
</code>```

You can use Ruby's paragraph mode command line switch to have the blank line be a delimiter for each record and set the field separator to be \n for each field. Then uniquify each block:

```<code>$ ruby -00 -F'\n' -lane '$><<$F.uniq.join("\n")<<"\n\n"' file
apple
banana
cherry

delta
epsilon

apple pie
delta
</code>```

Explained:

```<code>$ ruby -00 -F'\n' -lane '$><<$F.uniq.join("\n")<<"\n\n"'
   ^                                                      # ruby 1.9+ only I think
        ^                                                 # split records by \n\n
            ^                                             # split fields by \n
                   ^                                      # options to:
                                                            -l loop over input
                                                             a auto split
                                                             n don't auto print
                                                             e compile command line
                         ^                                # to STDOUT
                           ^                              # append
                             ^                            # the split fields
                                 ^                        # made uniq
                                     ^                    # join back to a string
                                          ^               # add back the record separator
</code>```

Alternatively, you can use a Ruby hash to count the fields and then just print the keys of the hash:

```<code>$ ruby -00 -F'\n' -lane 'h=Hash.new(0)
                         $F.each {|f| h[f]+=1 }
                         p h
                         puts h.keys.join("\n")<<"\n\n"
                         ' file
{"apple"=>2, "banana"=>1, "cherry"=>2}
apple
banana
cherry

{"delta"=>2, "epsilon"=>2}
delta
epsilon

{"apple pie"=>1, "delta"=>2}
apple pie
delta
</code>```

(In ruby 1.9+, hashes maintain insertion order -- this will print the words in file order.)

Then if you want to add a , to the potential field separators, you can do:

```<code>$ ruby -00 -F'\n|,' -lane '$><<$F.uniq.join("\n")<<"\n\n"' file
</code>```

Title: How to remove dupes from blocks of text

Body:
What's a smart and easy way to remove dupes within blocks within a file of text. Each block is separated by two newlines.

BEFORE:

apple
banana
apple
cherry
cherry

delta
epsilon
delta
epsilon

apple pie
delta
delta

AFTER:

apple
banana
cherry

delta
epsilon

apple pie
delta

Thanks. Should work on a Mac. Allow unicode. Any shell method/language/command. Dupes are not necessarily consecutive. Bonus if you ignore leading/trailing whitespace, or can use a comma as the delimiter within a record.

Body:
Given:

$ cat file
apple
banana
apple
cherry
cherry

delta
epsilon
delta
epsilon

apple pie
delta
delta

You can use Ruby's paragraph mode command line switch to have the blank line be a delimiter for each record and set the field separator to be \n for each field. Then uniquify each block:

$ ruby -00 -F'\n' -lane '$><<$F.uniq.join("\n")<<"\n\n"' file
apple
banana
cherry

delta
epsilon

apple pie
delta

Explained:

$ ruby -00 -F'\n' -lane '$><<$F.uniq.join("\n")<<"\n\n"'
   ^                                                      # ruby 1.9+ only I think
        ^                                                 # split records by \n\n
            ^                                             # split fields by \n
                   ^                                      # options to:
                                                            -l loop over input
                                                             a auto split
                                                             n don't auto print
                                                             e compile command line
                         ^                                # to STDOUT
                           ^                              # append
                             ^                            # the split fields
                                 ^                        # made uniq
                                     ^                    # join back to a string
                                          ^               # add back the record separator

Alternatively, you can use a Ruby hash to count the fields and then just print the keys of the hash:

$ ruby -00 -F'\n' -lane 'h=Hash.new(0)
                         $F.each {|f| h[f]+=1 }
                         p h
                         puts h.keys.join("\n")<<"\n\n"
                         ' file
{"apple"=>2, "banana"=>1, "cherry"=>2}
apple
banana
cherry

{"delta"=>2, "epsilon"=>2}
delta
epsilon

{"apple pie"=>1, "delta"=>2}
apple pie
delta

(In ruby 1.9+, hashes maintain insertion order -- this will print the words in file order.)

Then if you want to add a , to the potential field separators, you can do:

$ ruby -00 -F'\n|,' -lane '$><<$F.uniq.join("\n")<<"\n\n"' file


问:
Different and wrong size of a WinForms form on high-resolution screen in VS IDE and exe
I am developing a C# WinForms app for .NET 4.0 in VS 2017 on my ASUS NV552 laptop with UltraHD monitor with 282ppi. To work comfortably, I set the system scale factor to 300% in my Windows 10 Pro Creators Update. When I compile and launch the project, the size of the form differs from what I see in the VS Designer and it seems, .NET stops recalculating the form size at all for big form sizes.

For instance, when the form's Size property is set to 1606; 1284 in the VS property browser, the result size of the form on the screen displayed from the exe is 421x285. However, when I resize the form in the Designer say to 1943x1284, I see the same form of 421x285 in the exe!

Moreover, it seems, for smaller sizes I even see the result form with improper proportions of width and height.

If it helps somehow, below are the corresponding auto-scale settings for this form in the .designer.cs file when Size equals 1606; 1284:

this.AutoScaleDimensions = new System.Drawing.SizeF(19F, 37F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1570, 1181);
```
<p>I do understand that by default VS 2017 produces DPI-unaware exe applications, and that's OK if the form size is reduced in pixels when it is displayed from the exe (as if it were developed for 96ppi). Microsoft solved this problem with the release of .NET Framework 4.7 - now we can make our WinForms forms DPI-aware using the following setting in app.config (according to High DPI support in Windows Forms):</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <System.Windows.Forms.ApplicationConfigurationSection>
        <add key="DpiAwareness" value="PerMonitorV2" />
    </System.Windows.Forms.ApplicationConfigurationSection>
</configuration>
</code>```

But I need to solve the problem for old legacy DPI-unaware WinForms apps. Is there a solution?

Please, don't write useless comments containing phrases like "WinForms is dead" and "switch to WPF". Write only if you have ideas how to improve the described behavior in WinForms projects.

答:
WinForms Designer does not work well when HDPI scaling is enabled. You can somewhat improve your experience is you declare VisualStudio process as DPI-unaware, as described in this blog post:
https://code4ward.net/2016/11/29/visual-studio-winforms-designer-on-highdpi/

Unfortunately there is no easy way to convert an existing application to support DPI awareness, each form has to be worked on individually.

Thank you, Tanya

Body:
I am developing a C# WinForms app for .NET 4.0 in VS 2017 on my ASUS NV552 laptop with UltraHD monitor with 282ppi. To work comfortably, I set the system scale factor to 300% in my Windows 10 Pro Creators Update. When I compile and launch the project, the size of the form differs from what I see in the VS Designer and it seems, .NET stops recalculating the form size at all for big form sizes.

For instance, when the form's Size property is set to 1606; 1284 in the VS property browser, the result size of the form on the screen displayed from the exe is 421x285. However, when I resize the form in the Designer say to 1943x1284, I see the same form of 421x285 in the exe!

Moreover, it seems, for smaller sizes I even see the result form with improper proportions of width and height.

If it helps somehow, below are the corresponding auto-scale settings for this form in the .designer.cs file when Size equals 1606; 1284:

this.AutoScaleDimensions = new System.Drawing.SizeF(19F, 37F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1570, 1181);

I do understand that by default VS 2017 produces DPI-unaware exe applications, and that's OK if the form size is reduced in pixels when it is displayed from the exe (as if it were developed for 96ppi). Microsoft solved this problem with the release of .NET Framework 4.7 - now we can make our WinForms forms DPI-aware using the following setting in app.config (according to High DPI support in Windows Forms):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <System.Windows.Forms.ApplicationConfigurationSection>
        <add key="DpiAwareness" value="PerMonitorV2" />
    </System.Windows.Forms.ApplicationConfigurationSection>
</configuration>

But I need to solve the problem for old legacy DPI-unaware WinForms apps. Is there a solution?

Please, don't write useless comments containing phrases like "WinForms is dead" and "switch to WPF". Write only if you have ideas how to improve the described behavior in WinForms projects.


问:
HTML table background not working
Hello I currently am helping out an organization that uses a very basic website. They lack any CSS capabilities and I have had to code purely in html (which is far from fun). However I seem to be running into a issue. Whenever I run the code on the website a table's background fails to show up.

```<code>table style = "background: url(image.png)"
</code>```

This is how I coded the table, and I don't believe I made a mistake there because when I plug it into an html editor it works perfectly fine. Am I simply working with an outdated version of html? Or is what I'm asking for impossible with this website? Any help would be greatly appreciated.

Here is my code if it could clear up any confusion

```<code><table style="height: 10px; border-color: #000000; background:
url('http://i.imgur.com/2JxgSxt.jpg'), center, no-repeat; background-size:
100%;" width="100%">
<tbody>
<tr>
<td style="text-align: center; width: 15%;" bgcolor=""><span style="color:
#ffffff;"><strong>Feb.</strong></span><br />
<p><span style="color: #ffffff;"><strong>23rd-25th</strong></span></p>
</td>
<td style="width: 5%;" bgcolor=""><span style="color: #ffffff;">
</span></td>
<td bgcolor="">
<h2><span style="color: #ffffff;">Two-Umpire Mechanics Clinic </span>
</h2>
<h4><span style="color: #ffffff;">Friday-Sunday - </span></h4>
</td>
<td style="text-align: center;" bgcolor="" width="10%"><span style="color:
#ffffff;"> <img style="-moz-transform: scaleX(-1); -o-transform:
scaleX(-1); -webkit-transform: scaleX(-1); transform: scaleX(-1); filter:
FlipH;" src="http://www.clker.com/cliparts/6/k/K/P/5/Z/plain-left-white-
arrow-md.png" alt="" width="17" height="32" /></span></td>
</tr>
</tbody>
</table>
</code>```

答:
Try following code:

    First column
    Second column
    Third column

    First column
    Second column
    Third column

    First column
    Second column
    Third column

```

Title: HTML table background not working

Body:
Hello I currently am helping out an organization that uses a very basic website. They lack any CSS capabilities and I have had to code purely in html (which is far from fun). However I seem to be running into a issue. Whenever I run the code on the website a table's background fails to show up.

table style = "background: url(image.png)"

This is how I coded the table, and I don't believe I made a mistake there because when I plug it into an html editor it works perfectly fine. Am I simply working with an outdated version of html? Or is what I'm asking for impossible with this website? Any help would be greatly appreciated.

Here is my code if it could clear up any confusion

Feb.

23rd-25th

Two-Umpire Mechanics Clinic

Friday-Sunday -

Body:
Try following code:

<table background="http://lorempixel.com/400/200">
  <tr>
    <td>First column</td>
    <td>Second column</td>
    <td>Third column</td>
  </tr>

  <tr>
    <td>First column</td>
    <td>Second column</td>
    <td>Third column</td>
  </tr>

  <tr>
    <td>First column</td>
    <td>Second column</td>
    <td>Third column</td>
  </tr>
</table>


答:
Since you have only written psuedo code it is difficult to validate, but at the moment you are lacking quotes for the image url it should look like this

```<code><table style="width: 350px; height: 350px; background: url('https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded')">
<tr>
    <td>My awesome content</td>
</tr>
</table>
</code>```

Note I added some static width and height just so the example is visible. You probably should not use that in production.

Title: HTML table background not working

Body:
Since you have only written psuedo code it is difficult to validate, but at the moment you are lacking quotes for the image url it should look like this

<table style="width: 350px; height: 350px; background: url('https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded')">
<tr>
    <td>My awesome content</td>
</tr>
</table>

Note I added some static width and height just so the example is visible. You probably should not use that in production.


问:
Buffer is used, but may not have been initialized (in visual studio)
This is a snippet of my c++ code:

```<code>char buff[512];
memset(buff, ' ', sizeof(buff));
GetModuleFileName(NULL, buff, _MAX_PATH);
char *file = strrchr(buff, '.');
</code>```

It seems buff is initialized in the first line. But I get this from visual studio(This is a warning, not an error, I want to remove this warning):

```<code>'buff' is not initialized
'buff' is used, but may not have been initialized
</code>```

What's the problem?

答:
It looks like you are using a plain char* pointer for buff like this:

```<code>char* buff;
</code>```

instead of

```<code>char buff[_MAX_PATH];
</code>```

memset() won't allocate any memory for the buffer pointer.

Alternatively you could also use an initialized pointer:

```<code>char* buff = new[_MAX_PATH];
</code>```

But don't forget to call

```<code>delete [] buff;
</code>```

then, and that sizeof() won't give you the size of the allocated array but only the size of the pointer variable itself.

The even better alternative would be to use a std::vector<char> instead:

```<code>std::vector<char> buff(_MAX_PATH,'\0');
</code>```

You need to change some more code to use that correctly though:

```<code>GetModuleFileName(NULL, buff.data(), _MAX_PATH);
char *file = strrchr(buff.data(), '.');
</code>```

Also you should initialize your buffer with NUL chars rather than blanks (' '):

```<code>memset(buff, '\0', sizeof(buff));
           // ^^
</code>```

Body:
This is a snippet of my c++ code:

char buff[512];
memset(buff, ' ', sizeof(buff));
GetModuleFileName(NULL, buff, _MAX_PATH);
char *file = strrchr(buff, '.');

It seems buff is initialized in the first line. But I get this from visual studio(This is a warning, not an error, I want to remove this warning):

'buff' is not initialized
'buff' is used, but may not have been initialized

What's the problem?

Body:
It looks like you are using a plain char* pointer for buff like this:

char* buff;

instead of

char buff[_MAX_PATH];

memset() won't allocate any memory for the buffer pointer.

Alternatively you could also use an initialized pointer:

char* buff = new[_MAX_PATH];

But don't forget to call

delete [] buff;

then, and that sizeof() won't give you the size of the allocated array but only the size of the pointer variable itself.

The even better alternative would be to use a std::vector<char> instead:

std::vector<char> buff(_MAX_PATH,'\0');

You need to change some more code to use that correctly though:

GetModuleFileName(NULL, buff.data(), _MAX_PATH);
char *file = strrchr(buff.data(), '.');

Also you should initialize your buffer with NUL chars rather than blanks (' '):

memset(buff, '\0', sizeof(buff));
           // ^^


问:
Adding Items to DataGridView from a ListBox to a Single Column
I need to populate a DataGridView with items from a List.

I need the first row of the GridView populated with the items from the String List and i need to do some processing on the items in the GridView one by one and add the result to the second row(String).

Currently im Binding the DataGridView like this

```<code> dataGridView1.DataSource = mylist.ConvertAll(x => new { Value = x });
 dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
</code>```

I need to predefine the column name add strings in the first row,process these strings one by one and update the second column..what is the best way to do this?

答:
First you need to build your columns either programmatically or you can use the designer - that is up to you.  I will code all of it for the sake of showing the entire example:</p>

```<code>private DataGridView dgNew;

public MyForm()
{
    InitializeComponent();
    MyInitializeComponent();
}

private void MyInitializeComponent()
{
    dgNew = new DataGridView();

    var txtCol = new DataGridViewTextBoxColumn
    {
        HeaderText = "Column1",
        Name = "Column1",
        DataPropertyName = "Value"
    };
    dgNew.Columns.Add(txtCol);

    txtCol = new DataGridViewTextBoxColumn
    {
        HeaderText = "Column2",
        Name = "Column2",
    };
    dgNew.Columns.Add(txtCol);

    var listOfStrings = new List<string> {"one", "two", "three"};
    dgNew.DataSource = listOfStrings.ConvertAll(x => new { Value = x }); ;
    dgNew.Location = dg.Location;
    dgNew.Parent = this;

    this.Load += Form_Load;
}

private void Form_Load(object sender, EventArgs e)
{
    // Iterate over the rows, ignoring the header row
    foreach (var row in dgNew.Rows.OfType<DataGridViewRow>().Where(a => a.Index != -1))
    {
        var col1Value = row.Cells["Column1"].Value?.ToString();
        var col2Cell = row.Cells["Column2"];

        if (col1Value == null) continue;

        switch (col1Value)
        {
            case ("one"):
                col2Cell.Value = "row1, col2 val";
                break;
            case ("two"):
                col2Cell.Value = "row2, col2 val";
                break;
            case ("three"):
                col2Cell.Value = "row1, col3 val";
                break;
        }
    }
}
</code>```

Body:
I need to populate a DataGridView with items from a List.

I need the first row of the GridView populated with the items from the String List and i need to do some processing on the items in the GridView one by one and add the result to the second row(String).

Currently im Binding the DataGridView like this

 dataGridView1.DataSource = mylist.ConvertAll(x => new { Value = x });
 dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

I need to predefine the column name add strings in the first row,process these strings one by one and update the second column..what is the best way to do this?

Body:
First you need to build your columns either programmatically or you can use the designer - that is up to you.  I will code all of it for the sake of showing the entire example:

private DataGridView dgNew;

public MyForm()
{
    InitializeComponent();
    MyInitializeComponent();
}

private void MyInitializeComponent()
{
    dgNew = new DataGridView();

    var txtCol = new DataGridViewTextBoxColumn
    {
        HeaderText = "Column1",
        Name = "Column1",
        DataPropertyName = "Value"
    };
    dgNew.Columns.Add(txtCol);

    txtCol = new DataGridViewTextBoxColumn
    {
        HeaderText = "Column2",
        Name = "Column2",
    };
    dgNew.Columns.Add(txtCol);

    var listOfStrings = new List<string> {"one", "two", "three"};
    dgNew.DataSource = listOfStrings.ConvertAll(x => new { Value = x }); ;
    dgNew.Location = dg.Location;
    dgNew.Parent = this;

    this.Load += Form_Load;
}

private void Form_Load(object sender, EventArgs e)
{
    // Iterate over the rows, ignoring the header row
    foreach (var row in dgNew.Rows.OfType<DataGridViewRow>().Where(a => a.Index != -1))
    {
        var col1Value = row.Cells["Column1"].Value?.ToString();
        var col2Cell = row.Cells["Column2"];

        if (col1Value == null) continue;

        switch (col1Value)
        {
            case ("one"):
                col2Cell.Value = "row1, col2 val";
                break;
            case ("two"):
                col2Cell.Value = "row2, col2 val";
                break;
            case ("three"):
                col2Cell.Value = "row1, col3 val";
                break;
        }
    }
}


问:
Pseudo Element ::before Hiding Sibling Element's Content
I want to create a transition effect when hovering over my list element (or alternatively my anchor tags within these list elements).

Unfortunately, when I use my created transition the ::before pseudo-element (or the ::after, I'm not sure) are hiding what is technically its sibling content, that being the text within the anchor tags.

I've tried manipulating the z-index on the ul, li and a tags to no avail. The problem likely lies within my use of position: absolute in my transitions but I can't tell what I'm doing wrong.

Here's the HTML and CSS and a JSFiddle link

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    font-family: 'Open Sans', sans-serif;
}

#headercontainer {
    background-color: #4f2f65;
    height: 125px;
    position: relative;
}

#headercontainer ul {
    height: 100%;
    display: table;
    text-align: center;
    list-style: none;
    margin: 0;
    padding: 0;
}

#sitelogo {
    padding-top: 0px;
}

#headercontainer ul li {
    display: table-cell;
    vertical-align: middle;
    position: relative;
}

#headercontainer ul li a {
    color: #fff;
    font-size: 20px;
    text-decoration: none;
}

a::before {
    content: '';
    display: block;
    height: 0px;
    background-color: #fff;
    position: absolute;
    bottom: 0;
    width: 100%;
    transition: all ease-in-out 200ms;
}

a:hover::before {
    height: 125px;
}

header::after {
    content: '';
    display: table;
    clear: both;
}

#headerlinkslist a:hover {
    color: red;
}

.headerlinks {
    padding-left: 80px;
    padding-right: 80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <header>
        <div id="headercontainer">
            <ul id="headerlinkslist">
                <li id="sitelogo"></li>
                <li>RULES</li>
                <li>NEWS</li>
                <li>STATS</li>
                <li>SUBMIT</li>
                <li>LOGIN / REGISTER</li>
        </div>
    </header>
</body></code>```

答:
give the parent li a z-index, then use z-index: -1 on the pseudo element to push it behind the a but on top of the li.

You also need to close your ul

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Open Sans', sans-serif;
}

#headercontainer {
  background-color: #4f2f65;
  height: 125px;
  position: relative;
}

#headercontainer ul {
  height: 100%;
  display: table;
  text-align: center;
  list-style: none;
  margin: 0;
  padding: 0;
}

#sitelogo {
  padding-top: 0px;
}

#headercontainer ul li {
  display: table-cell;
  vertical-align: middle;
  position: relative;
  z-index: 1;
}

#headercontainer ul li a {
  color: #fff;
  font-size: 20px;
  text-decoration: none;
  transition: color .25s;
}

a::before {
  content: '';
  display: block;
  height: 0px;
  background-color: #fff;
  position: absolute;
  bottom: 0;
  width: 100%;
  transition: all ease-in-out 200ms;
  z-index: -1;
}

a:hover::before {
  height: 125px;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

#headerlinkslist a:hover {
  color: red;
}

.headerlinks {
  padding-left: 80px;
  padding-right: 80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <header>
    <div id="headercontainer">

      <ul id="headerlinkslist">
        <li id="sitelogo"></li>
        <li>RULES</li>
        <li>NEWS</li>
        <li>STATS</li>
        <li>SUBMIT</li>
        <li>LOGIN / REGISTER</li>

       </ul>
    </div>

  </header>
</body></code>```

Body:
I want to create a transition effect when hovering over my list element (or alternatively my anchor tags within these list elements).

Unfortunately, when I use my created transition the ::before pseudo-element (or the ::after, I'm not sure) are hiding what is technically its sibling content, that being the text within the anchor tags.

I've tried manipulating the z-index on the ul, li and a tags to no avail. The problem likely lies within my use of position: absolute in my transitions but I can't tell what I'm doing wrong.

Here's the HTML and CSS and a JSFiddle link

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    font-family: 'Open Sans', sans-serif;
}

#headercontainer {
    background-color: #4f2f65;
    height: 125px;
    position: relative;
}

#headercontainer ul {
    height: 100%;
    display: table;
    text-align: center;
    list-style: none;
    margin: 0;
    padding: 0;
}

#sitelogo {
    padding-top: 0px;
}

#headercontainer ul li {
    display: table-cell;
    vertical-align: middle;
    position: relative;
}

#headercontainer ul li a {
    color: #fff;
    font-size: 20px;
    text-decoration: none;
}

a::before {
    content: '';
    display: block;
    height: 0px;
    background-color: #fff;
    position: absolute;
    bottom: 0;
    width: 100%;
    transition: all ease-in-out 200ms;
}

a:hover::before {
    height: 125px;
}

header::after {
    content: '';
    display: table;
    clear: both;
}

#headerlinkslist a:hover {
    color: red;
}

.headerlinks {
    padding-left: 80px;
    padding-right: 80px;
}

RULES

NEWS

STATS

SUBMIT

LOGIN / REGISTER

Body:
give the parent li a z-index, then use z-index: -1 on the pseudo element to push it behind the a but on top of the li.

You also need to close your ul

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Open Sans', sans-serif;
}

#headercontainer {
  background-color: #4f2f65;
  height: 125px;
  position: relative;
}

#headercontainer ul {
  height: 100%;
  display: table;
  text-align: center;
  list-style: none;
  margin: 0;
  padding: 0;
}

#sitelogo {
  padding-top: 0px;
}

#headercontainer ul li {
  display: table-cell;
  vertical-align: middle;
  position: relative;
  z-index: 1;
}

#headercontainer ul li a {
  color: #fff;
  font-size: 20px;
  text-decoration: none;
  transition: color .25s;
}

a::before {
  content: '';
  display: block;
  height: 0px;
  background-color: #fff;
  position: absolute;
  bottom: 0;
  width: 100%;
  transition: all ease-in-out 200ms;
  z-index: -1;
}

a:hover::before {
  height: 125px;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

#headerlinkslist a:hover {
  color: red;
}

.headerlinks {
  padding-left: 80px;
  padding-right: 80px;
}

<body>
  <header>
    <div id="headercontainer">

      <ul id="headerlinkslist">
        <li id="sitelogo"></li>
        <li><a href="" class="headerlinks">RULES</a></li>
        <li><a href="" class="headerlinks">NEWS</a></li>
        <li><a href="" class="headerlinks">STATS</a></li>
        <li><a href="" class="headerlinks">SUBMIT</a></li>
        <li><a href="" class="headerlinks">LOGIN / REGISTER</a></li>

       </ul>
    </div>

  </header>
</body>


问:
Reference an attribute/parameter in a regex expression
I have two types of xml file (pom.xml and descriptors) that I want to join into a single dataset. There is no common key, so I'm taking the two directories and using the project name fragment before the underscore.

I have two variables to work with:

```<code>repository="/home/qeebrato/Git/ddt"
uri="file:/home/qeebrato/Git/ddt/eventhandlers_repeatlookup/src/main/resources/descriptors/eventhandlers_repeatlookup.descriptor"
</code>```

I want "eventhandlers".

To get this project fragment I have

```<code><xsl:attribute name="project"><xsl:value-of select='replace(@uri,"(.*)@repository(^_).*_(^$)","$2")'/></xsl:attribute>
</code>```

The webpages on XSLT string processing I've seen make no mention of using identifiers inside the regex.

答:
Building a string to use in a replace() regex

The replace() function takes at least three arguments: the input string, the regex pattern to match, and the replacement.

In your sample:
* The input string is the uri attribute on some element.
* The pattern seems to include the value of the repository attribute on this same element.
* The replacement is just the second match in the pattern.

The main problem you mention in your post is in the pattern -- you want to include the value of the repository attribute.  To do so, we can follow Martin Honnen's advice from his comment, and use concat() to construct the string:

```<code>concat("(.*)", @repository, "(^_).*_(^$)")
</code>```

Troubleshooting problems with a regex

I created a simple test XML document:

```<code><?xml version="1.0" encoding="UTF-8"?>
<test repository="/home/qeebrato/Git/ddt" uri="file:/home/qeebrato/Git/ddt/eventhandlers_repeatlookup/src/main/resources/descriptors/eventhandlers_repeatlookup.descriptor"/>
</code>```

And a simple XSL file to apply to this test, using the fixed replace() call above:

```<code><xsl:template match="test">
    <xsl:value-of select='replace(@uri,concat("(.*)", @repository, "(^_).*_(^$)"),"$2")'/>
</xsl:template>
</code>```

Running this XSL against this XML gives me:

```<code>file:/home/qeebrato/Git/ddt/eventhandlers_repeatlookup/src/main/resources/descriptors/eventhandlers_repeatlookup.descriptor
</code>```

... which is identical to the original value of the uri attribute.  Ultimately, your replace() doesn't do anything.

From the W3C specification:

Summary: The function returns the xs:string that is obtained by replacing each non-overlapping substring of $input that matches the given $pattern with an occurrence of the $replacement string.

A careful reading of this, and testing, clarifies that the function returns $input if $pattern is valid, but doesn't match anything.

Let's deconstruct your $pattern regex.

(.*) -- zero or more characters:

This alone could match the whole string.

@repository -- the value of the repository attribute: /home/qeebrato/Git/ddt

This matches the first part of the actual path in your $input string.

(^_) -- this is where things go funny.

I think you meant to use [^_] instead, with square brackets, which indicates a character that is not an underscore.

However, (^_) with round parentheses translates to a capturing match of an underscore at the start of $input, or at the start of a line, depending on your mode.  The replace() function defaults to ^ matching the start of the whole string.  Since there is no underscore at the start of your $input string, this $pattern fails to match -- so the function just returns $input as-is.

Getting what you need

You say, I want "eventhandlers".  If you mean, I want to extract this portion of the string, here's the replace statement you'd need to get that as output:

```<code>replace(@uri, concat(".*", @repository, "/([^_]+)_.*$"), "$1")
</code>```

Breaking this down:

.* matches zero or more characters.

@repository plugs in the string value of that attribute: /home/qeebrato/Git/ddt

/ since we need another path separator.

([^_]+) in round parens to capture, and what we capture is + one or more characters that [^_] are not an underscore.

_.*$ matches the following underscore, and then anything else until the end of the string.

We replace all that with $1, our first (and only) captured match, producing eventhandlers.

Notes

You mention in your post that you have two variables.  However, you use the @ symbol in your replace() call, which specifies an attribute value.

If repository and uri are actually variables (defined in your XSL using <xsl:variable> elements) or parameters (defined using <xsl:param>), then you need to use $ instead of @.

If you're working with regular expressions a lot, it will likely prove very worthwhile to use a regular expression tool, such as Regex Tester (online), RegExr (online), or RegexBuddy (for pay application; apparently made by the same guy that maintains http://www.regular-expressions.info/).

(Full disclosure: I have used RegexBuddy for years, but otherwise have no relationship with any of these regex websites or tool developers).

Body:
I have two types of xml file (pom.xml and descriptors) that I want to join into a single dataset. There is no common key, so I'm taking the two directories and using the project name fragment before the underscore.

I have two variables to work with:

repository="/home/qeebrato/Git/ddt"
uri="file:/home/qeebrato/Git/ddt/eventhandlers_repeatlookup/src/main/resources/descriptors/eventhandlers_repeatlookup.descriptor"

I want "eventhandlers".

To get this project fragment I have

<xsl:attribute name="project"><xsl:value-of select='replace(@uri,"(.*)@repository(^_).*_(^$)","$2")'/></xsl:attribute>

The webpages on XSLT string processing I've seen make no mention of using identifiers inside the regex.

Body:
Building a string to use in a replace() regex

The replace() function takes at least three arguments: the input string, the regex pattern to match, and the replacement.

In your sample:
* The input string is the uri attribute on some element.
* The pattern seems to include the value of the repository attribute on this same element.
* The replacement is just the second match in the pattern.

The main problem you mention in your post is in the pattern -- you want to include the value of the repository attribute.  To do so, we can follow Martin Honnen's advice from his comment, and use concat() to construct the string:

concat("(.*)", @repository, "(^_).*_(^$)")

Troubleshooting problems with a regex

I created a simple test XML document:

<?xml version="1.0" encoding="UTF-8"?>
<test repository="/home/qeebrato/Git/ddt" uri="file:/home/qeebrato/Git/ddt/eventhandlers_repeatlookup/src/main/resources/descriptors/eventhandlers_repeatlookup.descriptor"/>

And a simple XSL file to apply to this test, using the fixed replace() call above:

<xsl:template match="test">
    <xsl:value-of select='replace(@uri,concat("(.*)", @repository, "(^_).*_(^$)"),"$2")'/>
</xsl:template>

Running this XSL against this XML gives me:

file:/home/qeebrato/Git/ddt/eventhandlers_repeatlookup/src/main/resources/descriptors/eventhandlers_repeatlookup.descriptor

... which is identical to the original value of the uri attribute.  Ultimately, your replace() doesn't do anything.

From the W3C specification:

Summary: The function returns the xs:string that is obtained by replacing each non-overlapping substring of $input that matches the given $pattern with an occurrence of the $replacement string.

A careful reading of this, and testing, clarifies that the function returns $input if $pattern is valid, but doesn't match anything.

Let's deconstruct your $pattern regex.

(.*) -- zero or more characters:

This alone could match the whole string.

@repository -- the value of the repository attribute: /home/qeebrato/Git/ddt

This matches the first part of the actual path in your $input string.

(^_) -- this is where things go funny.

I think you meant to use [^_] instead, with square brackets, which indicates a character that is not an underscore.

However, (^_) with round parentheses translates to a capturing match of an underscore at the start of $input, or at the start of a line, depending on your mode.  The replace() function defaults to ^ matching the start of the whole string.  Since there is no underscore at the start of your $input string, this $pattern fails to match -- so the function just returns $input as-is.

Getting what you need

You say, I want "eventhandlers".  If you mean, I want to extract this portion of the string, here's the replace statement you'd need to get that as output:

replace(@uri, concat(".*", @repository, "/([^_]+)_.*$"), "$1")

Breaking this down:

.* matches zero or more characters.

@repository plugs in the string value of that attribute: /home/qeebrato/Git/ddt

/ since we need another path separator.

([^_]+) in round parens to capture, and what we capture is + one or more characters that [^_] are not an underscore.

_.*$ matches the following underscore, and then anything else until the end of the string.

We replace all that with $1, our first (and only) captured match, producing eventhandlers.

Notes

You mention in your post that you have two variables.  However, you use the @ symbol in your replace() call, which specifies an attribute value.

If repository and uri are actually variables (defined in your XSL using <xsl:variable> elements) or parameters (defined using <xsl:param>), then you need to use $ instead of @.

If you're working with regular expressions a lot, it will likely prove very worthwhile to use a regular expression tool, such as Regex Tester (online), RegExr (online), or RegexBuddy (for pay application; apparently made by the same guy that maintains http://www.regular-expressions.info/).

(Full disclosure: I have used RegexBuddy for years, but otherwise have no relationship with any of these regex websites or tool developers).


问:
How to have default forgot password but custom login and registration in Laravel
I want to use the default forgot password but want to have custom login and registration

I have used generator make:auth and the scaffolding is generated

but the problem is:

//file web.php

```<code>Auth::routes();

Route::get('login',function(){
    return view('login');
});

Route::post('login','RegistrationController@login');

Route::get('register','RegistrationController@getRegister');
Route::post('register','RegistrationController@postRegister');
</code>```

But All above routes takes me to default login and register page

but when I remove  Auth::routes(); it takes me to all custom routes

but I want login, registration as custom routes and forgot password as a default of Laravel

my question: I want a login and registration custom routes to be applied but for forgot password default routes of Laravel to be applied.

how can I achieve this? Please help me thanks in advance!!!!

答:
You can replace the default routes created by Auth::routes(). By default that function creates the following routes:

```<code>Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
</code>```

You can replace Auth::routes() with the above and modify to your needs. Be aware that the controllers for these may need to be adjusted to cooperate with your customizations depending on what you are trying to achieve

Body:
I want to use the default forgot password but want to have custom login and registration

I have used generator make:auth and the scaffolding is generated

but the problem is:

//file web.php

Auth::routes();

Route::get('login',function(){
    return view('login');
});

Route::post('login','RegistrationController@login');

Route::get('register','RegistrationController@getRegister');
Route::post('register','RegistrationController@postRegister');

But All above routes takes me to default login and register page

but when I remove  Auth::routes(); it takes me to all custom routes

but I want login, registration as custom routes and forgot password as a default of Laravel

my question: I want a login and registration custom routes to be applied but for forgot password default routes of Laravel to be applied.

how can I achieve this? Please help me thanks in advance!!!!

Body:
You can replace the default routes created by Auth::routes(). By default that function creates the following routes:

Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');

You can replace Auth::routes() with the above and modify to your needs. Be aware that the controllers for these may need to be adjusted to cooperate with your customizations depending on what you are trying to achieve


问:
PCA: Get Top 20 Most Important Dimensions
I'm doing a bit of machine learning and trying to find important dimensions using PCA.  Here's what I've done so far:

```<code>from sklearn.decomposition import PCA
pca = PCA(n_components=0.98)
X_reduced = pca.fit_transform(df_normalized)
X_reduced.shape
(2208, 1961)
</code>```

So I have 2,208 rows consisting of 1,961 columns after running PCA that explains 98% of the variance in my dataset.  However, I'm worried that the dimensions with the least explanatory power may actually be hurting my attempt at prediction (my model may just find spurious correlations in the data).

Does SciKit-Learn order the columns by importance?  If so, I could just do:

X_final = X_reduced[:, :20], correct?

Thanks for the help!

答:
From the documentation it says the output is sorted by explained variance. So yes, you should be able to do what you suggest and just take the first N dimensions the output. You could also print the output variable explained_variance_ (or even explained_variance_ratio_) along with the components_ output to double check the order.

Example from the documentation shows how to access the explained variance amounts:

```<code>import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=2)
pca.fit(X)

print(pca.explained_variance_ratio_)
</code>```

so in  your case you could do print(X_reduced.components_) and print(X_reduced.explained_variance_ratio_) to get both. Then simply take the first N that you want from X_reduced.components_ after finding what N explains y% of your variance.

Be aware! In your suggested solution you mix up the dimensions. X_reduced.components_ is of the shape [n_components, n_features] so for instance if you want the first 20 components you should use X_reduced.components[:20, :] I believe.

Body:
I'm doing a bit of machine learning and trying to find important dimensions using PCA.  Here's what I've done so far:

from sklearn.decomposition import PCA
pca = PCA(n_components=0.98)
X_reduced = pca.fit_transform(df_normalized)
X_reduced.shape
(2208, 1961)

So I have 2,208 rows consisting of 1,961 columns after running PCA that explains 98% of the variance in my dataset.  However, I'm worried that the dimensions with the least explanatory power may actually be hurting my attempt at prediction (my model may just find spurious correlations in the data).

Does SciKit-Learn order the columns by importance?  If so, I could just do:

X_final = X_reduced[:, :20], correct?

Thanks for the help!

Body:
From the documentation it says the output is sorted by explained variance. So yes, you should be able to do what you suggest and just take the first N dimensions the output. You could also print the output variable explained_variance_ (or even explained_variance_ratio_) along with the components_ output to double check the order.

Example from the documentation shows how to access the explained variance amounts:

import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=2)
pca.fit(X)

print(pca.explained_variance_ratio_)

so in  your case you could do print(X_reduced.components_) and print(X_reduced.explained_variance_ratio_) to get both. Then simply take the first N that you want from X_reduced.components_ after finding what N explains y% of your variance.

Be aware! In your suggested solution you mix up the dimensions. X_reduced.components_ is of the shape [n_components, n_features] so for instance if you want the first 20 components you should use X_reduced.components[:20, :] I believe.


问:
Badge - data structure / models?
I'm trying to figure out how one would set up a database and/or model in order to handle various badges. Lets take the Stack Overflow badges as an example. There are different rules for each and some might be just a variable different (like 10 comments vs 100 comments).

My question is how do you set up this type validation/check within an application? Should each badge have its own method?

答:
I would imagine some are calculated realtime, while others are calculated in processes that run intermittently.

For example, for the badge that appears when your answer gets 10 upvotes, that could be calculated realtime with little performance hit.

On the other hand, for the badge that checks if you hit the daily reputation cap x number of times, you would probably want to do that as some sort of batch job, since you only check at the end of each day.

The key concern is to keep things running fast.  Stack overflow gets thousands (maybe tens of thousands) of questions a day, with probably hundreds of thousands of comments.  Anything that is not trivial to calculate should be run in a separate process.  It keeps the core functionality tight, limited, and clean, allowing high performance.  Running complex calculations in processes outside the core posting system allows you to do so without affecting users' ability to use the site.  If a task is sufficiently complex, you can scale horizontally by just running the same process across multiple machines.

Title: Badge - data structure / models?


问:
Parsing a Log File to Display Data from Multiple Lines Using Regular Expressions
So I'm trying to parse a bit of code here to get message text from a log file. I'll explain as I go. Here's the code:

```<code>// Print to interactions
  try
  {
  // assigns the input file to a filereader object
     BufferedReader infile = new BufferedReader(new FileReader(log));

      sc = new Scanner(log);
            while(sc.hasNext())
              {
                 String line=sc.nextLine();
                   if(line.contains("LANTALK")){
                    Document doc = Jsoup.parse(line);
                    Element idto = doc.select("MBXTO").first();
                    Element  msg = doc.select("MSGTEXT").first();
                    System.out.println(" to " + idto.text() + " " +
                        msg.text());
                    System.out.println();

                   } // End of if

               } // End of while

  try
  {
   // Print to output file
      sc = new Scanner (log);
            while(sc.hasNext())
              {
                 String line=sc.nextLine();
                   if(line.contains("LANTALK")){
                    Document doc = Jsoup.parse(line);
                    Element idto = doc.select("MBXTO").first();
                    Element  msg = doc.select("MSGTEXT").first();
                    outFile.println(" to " + idto.text() + " " +
                        msg.text());
                    outFile.println();
                    outFile.println();
               } // End of if

               } // End of while
    } // end of try
</code>```

I'm getting input from a log file, here's a sample of what it looks like and the lines that I'm filtering out:

```<code>08:25:20.740 [D] [T:000FF0] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>1124</MBXID><MBXTO>5760</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>and I talked to him and he
gave me a credit card number</MSGTEXT>
08:25:20.751 [+] [T:000FF0] [S:1:1:1124:5607:5] LANMSG [15/2 | 0]
08:25:20.945 [+] [T:000FF4] [S:1:1:1124:5607:5] LANMSGTYPESTOPPED [0/2 | 0]
08:25:21.327 [+] [T:000FE8] [S:1:1:1124:5607:5] LANMSGTYPESTARTED [0/2 | 0]
</code>```

So far, I've been able to filter the line that contains the message (LANMSG). And from that, I've been able to get the id number of the recipient (MBXTO). But the next line contains the sender's id, which I need to pull out and display. ([S:1:1:1124:SENDERID:5]). How should I do this? Below is a copy of the output I'm getting:

```<code>to 5760 and I talked to him and he gave me a credit card number
</code>```

And here's what I need to get:

```<code>SENDERID to 5760 and I talked to him and he gave me a credit card number
</code>```

Any help you guys could give me on this would be great. I'm just not sure how to go about getting the information I need.

答:
Your answer isn't clear enough, but as it seems like you have not used regex in this code... remember to specify what have you tried before asking.
Anyways the regex you're searching for is:

```<code>(\d{2}:\d{2}:\d{2}\.\d{3})\s\[D\].+<MBXID>(\d+)<\/MBXID><MBXTO>(\d+)<\/MBXTO>.+<MSGTEXT>(.+)<\/MSGTEXT>
</code>```

Working example in Regex101

It should capture:

$1: 08:25:20.740

$2: 1124

$3: 5760

$4: and I talked to him and he
gave me a credit card number (Note that it also capture \n, or newline, characters).

(Also, you'll use matcher.group(number) instead of $number in Java).

And then you can use these substitution (group reference) terms to get your formatted output.

E.g.:  $1 [$2] to [$3] $4

Should return:

```<code>08:25:20.740 [1124] to [5760] and I talked to him and he
gave me a credit card number
</code>```

Remember, when you're going to implement regex in your Java code, you must escape all the backslashes (\), for this reason, this regex looks bigger:

```<code>Pattern pattern = Pattern.compile("(\\d{2}:\\d{2}:\\d{2}\\.\\d{3})\\s\\[D\\].+<MBXID>(\\d+)<\\/MBXID><MBXTO>(\\d+)<\\/MBXTO>.+<MSGTEXT>(.+)<\\/MSGTEXT>", Pattern.MULTILINE + Pattern.DOTALL);
// Multiline is used to capture the LANMSG more than once, and Dotall is used to make the '.' term in regex also match the newline in the input
Matcher matcher = pattern.matcher(input);
while (matcher.find()){
    String output = matcher.group(1) + " [" + matcher.group(2) + "] to [" + matcher.group(3) + "] " + matcher.group(4);
    System.out.println(output);
}
</code>```

And for your second problem Oh, you have edited and erased it already. . . But I'll still answer:
You can parse the $2 and $3 and make them return an integer:

```<code>int id1 = Integer.parseInt(matcher.group(2));
int id2 = Integer.parseInt(matcher.group(3));
</code>```

This way you can create a method to return a name for these IDs. e.g.:
 UserUtil.getName(int id)

Body:
So I'm trying to parse a bit of code here to get message text from a log file. I'll explain as I go. Here's the code:

// Print to interactions
  try
  {
  // assigns the input file to a filereader object
     BufferedReader infile = new BufferedReader(new FileReader(log));

      sc = new Scanner(log);
            while(sc.hasNext())
              {
                 String line=sc.nextLine();
                   if(line.contains("LANTALK")){
                    Document doc = Jsoup.parse(line);
                    Element idto = doc.select("MBXTO").first();
                    Element  msg = doc.select("MSGTEXT").first();
                    System.out.println(" to " + idto.text() + " " +
                        msg.text());
                    System.out.println();

                   } // End of if

               } // End of while

  try
  {
   // Print to output file
      sc = new Scanner (log);
            while(sc.hasNext())
              {
                 String line=sc.nextLine();
                   if(line.contains("LANTALK")){
                    Document doc = Jsoup.parse(line);
                    Element idto = doc.select("MBXTO").first();
                    Element  msg = doc.select("MSGTEXT").first();
                    outFile.println(" to " + idto.text() + " " +
                        msg.text());
                    outFile.println();
                    outFile.println();
               } // End of if

               } // End of while
    } // end of try

I'm getting input from a log file, here's a sample of what it looks like and the lines that I'm filtering out:

08:25:20.740 [D] [T:000FF0] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>1124</MBXID><MBXTO>5760</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>and I talked to him and he
gave me a credit card number</MSGTEXT>
08:25:20.751 [+] [T:000FF0] [S:1:1:1124:5607:5] LANMSG [15/2 | 0]
08:25:20.945 [+] [T:000FF4] [S:1:1:1124:5607:5] LANMSGTYPESTOPPED [0/2 | 0]
08:25:21.327 [+] [T:000FE8] [S:1:1:1124:5607:5] LANMSGTYPESTARTED [0/2 | 0]

So far, I've been able to filter the line that contains the message (LANMSG). And from that, I've been able to get the id number of the recipient (MBXTO). But the next line contains the sender's id, which I need to pull out and display. ([S:1:1:1124:SENDERID:5]). How should I do this? Below is a copy of the output I'm getting:

to 5760 and I talked to him and he gave me a credit card number

And here's what I need to get:

SENDERID to 5760 and I talked to him and he gave me a credit card number

Any help you guys could give me on this would be great. I'm just not sure how to go about getting the information I need.

Body:
Your answer isn't clear enough, but as it seems like you have not used regex in this code... remember to specify what have you tried before asking.
Anyways the regex you're searching for is:

(\d{2}:\d{2}:\d{2}\.\d{3})\s\[D\].+<MBXID>(\d+)<\/MBXID><MBXTO>(\d+)<\/MBXTO>.+<MSGTEXT>(.+)<\/MSGTEXT>

Working example in Regex101

It should capture:

$1: 08:25:20.740

$2: 1124

$3: 5760

$4: and I talked to him and he
gave me a credit card number (Note that it also capture \n, or newline, characters).

(Also, you'll use matcher.group(number) instead of $number in Java).

And then you can use these substitution (group reference) terms to get your formatted output.

E.g.:  $1 [$2] to [$3] $4

Should return:

08:25:20.740 [1124] to [5760] and I talked to him and he
gave me a credit card number

Remember, when you're going to implement regex in your Java code, you must escape all the backslashes (\), for this reason, this regex looks bigger:

Pattern pattern = Pattern.compile("(\\d{2}:\\d{2}:\\d{2}\\.\\d{3})\\s\\[D\\].+<MBXID>(\\d+)<\\/MBXID><MBXTO>(\\d+)<\\/MBXTO>.+<MSGTEXT>(.+)<\\/MSGTEXT>", Pattern.MULTILINE + Pattern.DOTALL);
// Multiline is used to capture the LANMSG more than once, and Dotall is used to make the '.' term in regex also match the newline in the input
Matcher matcher = pattern.matcher(input);
while (matcher.find()){
    String output = matcher.group(1) + " [" + matcher.group(2) + "] to [" + matcher.group(3) + "] " + matcher.group(4);
    System.out.println(output);
}

And for your second problem Oh, you have edited and erased it already. . . But I'll still answer:
You can parse the $2 and $3 and make them return an integer:

int id1 = Integer.parseInt(matcher.group(2));
int id2 = Integer.parseInt(matcher.group(3));

This way you can create a method to return a name for these IDs. e.g.:
 UserUtil.getName(int id)


问:
string1 OR string2 in regex?
In the below example I have tried to force the match to end with ".flv" or ".mp4". That is why \b is there.

However, the order for some reason matters. Right now it outputs flv links correctly, but any link with "mp4" at the end is printed as mp4.

```<code>perl -ne 'print "$1\n" if /(http[^\s]*\.\bflv\b|\bmp4\b)/' test.html
</code>```

How can I get a real .flv or .mp4?

答:
With correct grouping, Regex should be:

```<code>/\b(http\S+\.(?:flv|mp4))\b/
</code>```

In your regex http and dot is matched before flv but not before mp4. Your regex is executed as http[^\s]*\.\bflv\b OR \bmp4\b

Moreover there is no need to match for \b after a dot since dot is considered a non-word character. You only need to match \b after .flv and .mp4. Also it is better to match \b before http also.

Also note use of \S instead of [^\s]

Title: string1 OR string2 in regex?

Body:
In the below example I have tried to force the match to end with ".flv" or ".mp4". That is why \b is there.

However, the order for some reason matters. Right now it outputs flv links correctly, but any link with "mp4" at the end is printed as mp4.

perl -ne 'print "$1\n" if /(http[^\s]*\.\bflv\b|\bmp4\b)/' test.html

How can I get a real .flv or .mp4?

Body:
With correct grouping, Regex should be:

/\b(http\S+\.(?:flv|mp4))\b/

In your regex http and dot is matched before flv but not before mp4. Your regex is executed as http[^\s]*\.\bflv\b OR \bmp4\b

Moreover there is no need to match for \b after a dot since dot is considered a non-word character. You only need to match \b after .flv and .mp4. Also it is better to match \b before http also.

Also note use of \S instead of [^\s]


问:
Can a NATS publisher send a single message into multiple queues?
I'm building a system where two different entities need to process messages from the same source (in different ways - for example one will log all messages while another entity might want to aggregate data).

Ideally each entity is fully scalable for performance and resiliency, so we have multiple publishers, multiple log subscribers and multiple aggregation subscribers, but still each messages generated by each published is processed by exactly one log subscriber and one aggregation subscribers.

With AMQP we can achieve this by publishing to a fan-out exchange that distributes messages to two queues where each queue has many subscribers. I understand that the same behavior can be achieved in NATS by simply having all the subscribers listen on the same "subject" by use two distinct "queue group names" base on their roles.

In such an instance messages to the subject will be delivered to one subscriber from each queue group, i.e. each message will be delivered exactly n-times, n being the number of distinct queue groups and not the number of subscribers. Is this correct?

答:
Indeed, you can use queue subscribers (for instance in Go, it would be such API: func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error).

The queue is the group name. For instance, it could be in your example log and aggregation. You can create as many queue subscribers on each of these groups and only 1 member in each group will receive a given message.

For instance, suppose that you publish a message on subject foo and you have 10 queue subscribers on foo with queue name log and 10 queue subscribers on foo with queue name aggregation. The message will be delivered to 2 subscribers, 1 for group log and 1 for group aggregation.

Hope this helps.