问:
Why can't I use a key function that returns a reference when sorting a vector with sort_by_key?
I'm trying to sort a Vec<String> using a key function that returns references to the strings in the vector.  A contrived example is to use the identity function as key function (which of course is useless, but it's the minimal example to reproduce my problem):

fn key(x: &String) -> &String {
    x
}

fn example(items: Vec<String>) {
    items.sort_by_key(key);
}
```
<p>This gives the following error:</p>
<pre class="lang-none prettyprint-override"><code>error[E0308]: mismatched types
   --> src/lib.rs:6:11
    |
6   |     items.sort_by_key(key);
    |           ^^^^^^^^^^^ lifetime mismatch
    |
    = note: expected associated type `<for<'r> fn(&'r String) -> &'r String {key} as FnOnce<(&String,)>>::Output`
               found associated type `<for<'r> fn(&'r String) -> &'r String {key} as FnOnce<(&String,)>>::Output`
    = note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
</code>```

I don't understand why I get this error, so I tried to track this down.  I first implemented my own version of sort_by_key():

```<code>fn sort_by_key<T, K: Ord>(a: &mut [T], key: fn(&T) -> K) {
    a.sort_by(|x, y| key(x).cmp(&key(y)));
}
</code>```

When trying to call this function, I get what looks like the "opposite" error:

error[E0308]: mismatched types
 --> src/lib.rs:6:29
  |
6 |     sort_by_key(&mut items, key);
  |                             ^^^ one type is more general than the other
  |
  = note: expected fn pointer `for<'r> fn(&'r String) -> &String`
             found fn pointer `for<'r> fn(&'r String) -> &'r String`
```
<p>I can make this code compile by fixing the key type to <code>&T</code> instead of using the generic parameter <code>K</code>, or by using <code>&K</code> instead of <code>K</code> as return type for the key function:</p>
<pre class="lang-rust prettyprint-override"><code>fn sort_by_key_v2<T: Ord>(a: &mut [T], key: fn(&T) -> &T) {
    a.sort_by(|x, y| key(x).cmp(&key(y)));
}

fn sort_by_key_v3<T, K: Ord>(a: &mut [T], key: fn(&T) -> &K) {
    a.sort_by(|x, y| key(x).cmp(&key(y)));
}
</code>```

I also tried adding lifetime annotations, but that only shifted the error around without resolving it.

Here's the three versions of the sort_by_key() function on the Playground.

Why am I getting these errors?  Is there any way to fix them while keeping the key type K completely generic?

答:
The cleanest workaround (IMO) for this that builds on Shepmaster's answer is:

```<code>fn ref_key<T, K: Ord + ?Sized>(mut f: impl FnMut(&T) -> &K) -> impl FnMut(&T, &T) -> Ordering {
    move |a, b| f(a).cmp(f(b))
}
</code>```

It can be used simply by converting slice.sort_by_key(key) to slice.sort_by(ref_key(key)).

Body:
I'm trying to sort a Vec<String> using a key function that returns references to the strings in the vector.  A contrived example is to use the identity function as key function (which of course is useless, but it's the minimal example to reproduce my problem):

fn key(x: &String) -> &String {
    x
}

fn example(items: Vec<String>) {
    items.sort_by_key(key);
}

This gives the following error:

error[E0308]: mismatched types
   --> src/lib.rs:6:11
    |
6   |     items.sort_by_key(key);
    |           ^^^^^^^^^^^ lifetime mismatch
    |
    = note: expected associated type `<for<'r> fn(&'r String) -> &'r String {key} as FnOnce<(&String,)>>::Output`
               found associated type `<for<'r> fn(&'r String) -> &'r String {key} as FnOnce<(&String,)>>::Output`
    = note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here

I don't understand why I get this error, so I tried to track this down.  I first implemented my own version of sort_by_key():

fn sort_by_key<T, K: Ord>(a: &mut [T], key: fn(&T) -> K) {
    a.sort_by(|x, y| key(x).cmp(&key(y)));
}

When trying to call this function, I get what looks like the "opposite" error:

error[E0308]: mismatched types
 --> src/lib.rs:6:29
  |
6 |     sort_by_key(&mut items, key);
  |                             ^^^ one type is more general than the other
  |
  = note: expected fn pointer `for<'r> fn(&'r String) -> &String`
             found fn pointer `for<'r> fn(&'r String) -> &'r String`

I can make this code compile by fixing the key type to &T instead of using the generic parameter K, or by using &K instead of K as return type for the key function:

fn sort_by_key_v2<T: Ord>(a: &mut [T], key: fn(&T) -> &T) {
    a.sort_by(|x, y| key(x).cmp(&key(y)));
}

fn sort_by_key_v3<T, K: Ord>(a: &mut [T], key: fn(&T) -> &K) {
    a.sort_by(|x, y| key(x).cmp(&key(y)));
}

I also tried adding lifetime annotations, but that only shifted the error around without resolving it.

Here's the three versions of the sort_by_key() function on the Playground.

Why am I getting these errors?  Is there any way to fix them while keeping the key type K completely generic?

Body:
The cleanest workaround (IMO) for this that builds on Shepmaster's answer is:

fn ref_key<T, K: Ord + ?Sized>(mut f: impl FnMut(&T) -> &K) -> impl FnMut(&T, &T) -> Ordering {
    move |a, b| f(a).cmp(f(b))
}

It can be used simply by converting slice.sort_by_key(key) to slice.sort_by(ref_key(key)).


来源: stackexchange

问:
How to make my image span multiple columns?
I have a simple piece of code at the moment and I've recently attempted to move away from floats to CSS grids and I'm having an issue, getting my images to span my entire width of columns.

Would someone please be able to have a look at my HTML and CSS and advise me how I would best go around fixing my issue?

/*  *//* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}
body {
  line-height: 1;
}
ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}

/*reset*/

    body {
  margin: 40px;
}

.sidebar {
        grid-area: sidebar;
    }

    .sidebar2 {
        grid-area: sidebar2;
    }

    .content {
        grid-area: content;
    }

    .hero_image {
        grid-area: hero_image
    }

    .header {
        grid-area: header;
    }

    .footer {
        grid-area: footer;
    }

    .wrapper {
        background-color: #fff;
        color: #444;
    }

  .wrapper {
    display: grid;
    grid-gap: 1em;
    grid-template-areas:
     "header"
     "sidebar"
     "content"
     "sidebar2"
     "hero_image"
     "footer"
  }

    @media only screen and (min-width: 1101px)   {
        .wrapper {
      grid-gap: 20px;
            grid-template-columns: 15% auto 15%;
            grid-template-areas:
            "header  header  header"
            "sidebar content sidebar2"
            "hero_image hero_image hero_image"
            "footer  footer  footer";
            max-width: 100%;
        }
    }

    @media only screen and (max-width: 1100px)   {
        .wrapper {
      grid-gap: 20px;
            grid-template-columns: 20% auto ;
            grid-template-areas:
            "header  header"
            "sidebar content"
            "sidebar2 sidebar2"
            "hero_image hero_image"
            "footer  footer";
            max-width: 100%;
        }
    }

    @media only screen and (max-width: 650px)  {
    .wrapper {

        grid-template-columns: 100%;
        grid-template-areas:
        "header"
        "sidebar"
        "content"
        "sidebar2"
        "hero_image"
        "footer";
      }
    }

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 10px;
  font-size: 150%;
}

.header, .footer {
  background-color: #999;
}

.sidebar2 {
  background-color: #ccc;
  color: #444;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<!--==========================================================================================================
                                                  CHARACTER SET
  ========================================================================================================== -->
  <meta charset="utf-8">
  <!--==========================================================================================================
                                                  HTML WEB PAGE TITLE - IN TAB BAR
  ========================================================================================================== -->

  <title>Swift Tools</title>
<!--==========================================================================================================
                                                  FORCE METADATE/MICRODATA OF WHATS ON THE SITE
  ========================================================================================================== -->

  <meta name="description" content="The HTML5 Herald">
  <meta name="author" content="SitePoint">
  <!--==========================================================================================================
                                                  CSS LINK
  ========================================================================================================== -->

  <link rel="stylesheet" href="style.css">
   <!--==========================================================================================================
                                                  RESPONSIVE DESIGN SETTING
  ========================================================================================================== -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<div class="wrapper">
  <div class="box header">
    <header>
        <div id="header_h1">
          <h1>Swift Tools</h1>
        </div>
      </header>
    </div>

  <div class="box sidebar">
            Home
            Photoshop
            Illustrator
            About
    </div>

  <div class="box sidebar2">
    <div class="right">
            <h2 class="righth2">About</h2>
            <p class="rightp">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
        </div>
  </div>
  <div class="box content">
    <div class="main">
            <h2>Lorum Ipsum</h2>
            <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
        </div>
  </div>

<div class="box hero_img">
  <div class="hero_image">
            <img src="images/new-york-4854718_1920.jpg" alt="A photo of downtown newyork in the summer sun" style="max-width:100%;height:auto;" >
          </div>

          <picture class="main_page_responsive_img">
            <source srcset="images/taxi-cab-381233_1920.jpg" media="(max-width: 620px)">
            <source srcset="images/statue-of-liberty-267948_1920.jpg" media="(max-width: 1000px)">
            <source srcset="images/new-york-city-801867_1920.jpg" media="(min-width: 1001px)">
            <source srcset="images/statue-of-liberty-267948_1920.jpg">
              <img class="hero_image" src="images/statue-of-liberty-267948_1920.jpg" alt="Statue of Liberty on a sunnyday" style="max-width:100%;height:auto;">
          </picture>
        </div>

  <div class="box footer">
    <div class="footer_p">
              <p class="right">test test test test</p>
            </div>
  </div>
</div>

</html></code>```

答: If you want to span images to entire width of its parent, you can try providing width 100% to images</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a simple piece of code at the moment and I've recently attempted to move away from floats to CSS grids and I'm having an issue, getting my images to span my entire width of columns.

Would someone please be able to have a look at my HTML and CSS and advise me how I would best go around fixing my issue?

/*  *//* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}
body {
  line-height: 1;
}
ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}

/*reset*/

    body {
  margin: 40px;
}

.sidebar {
        grid-area: sidebar;
    }

    .sidebar2 {
        grid-area: sidebar2;
    }

    .content {
        grid-area: content;
    }

    .hero_image {
        grid-area: hero_image
    }

    .header {
        grid-area: header;
    }

    .footer {
        grid-area: footer;
    }

    .wrapper {
        background-color: #fff;
        color: #444;
    }

  .wrapper {
    display: grid;
    grid-gap: 1em;
    grid-template-areas:
     "header"
     "sidebar"
     "content"
     "sidebar2"
     "hero_image"
     "footer"
  }

    @media only screen and (min-width: 1101px)   {
        .wrapper {
      grid-gap: 20px;
            grid-template-columns: 15% auto 15%;
            grid-template-areas:
            "header  header  header"
            "sidebar content sidebar2"
            "hero_image hero_image hero_image"
            "footer  footer  footer";
            max-width: 100%;
        }
    }

    @media only screen and (max-width: 1100px)   {
        .wrapper {
      grid-gap: 20px;
            grid-template-columns: 20% auto ;
            grid-template-areas:
            "header  header"
            "sidebar content"
            "sidebar2 sidebar2"
            "hero_image hero_image"
            "footer  footer";
            max-width: 100%;
        }
    }

    @media only screen and (max-width: 650px)  {
    .wrapper {

        grid-template-columns: 100%;
        grid-template-areas:
        "header"
        "sidebar"
        "content"
        "sidebar2"
        "hero_image"
        "footer";
      }
    }

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 10px;
  font-size: 150%;
}

.header, .footer {
  background-color: #999;
}

.sidebar2 {
  background-color: #ccc;
  color: #444;
}

<!DOCTYPE html>

  <meta charset="utf-8">

  <title>Swift Tools</title>

  <meta name="description" content="The HTML5 Herald">
  <meta name="author" content="SitePoint">

  <link rel="stylesheet" href="style.css">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

Swift Tools

            Home
            Photoshop
            Illustrator
            About

About

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

Lorum Ipsum

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

          <picture class="main_page_responsive_img">
            <source srcset="images/taxi-cab-381233_1920.jpg" media="(max-width: 620px)">
            <source srcset="images/statue-of-liberty-267948_1920.jpg" media="(max-width: 1000px)">
            <source srcset="images/new-york-city-801867_1920.jpg" media="(min-width: 1001px)">
            <source srcset="images/statue-of-liberty-267948_1920.jpg">

          </picture>

test test test test


问:
How do you stop a thead background color from leaking when there are rounded corners?
I have a table with rounded corners. I've specified a different background colour only for the thead.

On all browsers other than Firefox, the background colour leaks through the rounded corner. I've set overflow to hidden but that doesn't seem to help.

How can I stop the background colour from leaking through the rounded corner of the table?

Here's the code:
https://codepen.io/ayushn21/pen/OJVRMgG

Thanks!

答:
You have to set the border-radius (top-left and top-right) for the appropriate th cells (first and last child accordingly). So simply add the following to the CSS of your Codepen Example.

```<code>  th:first-child {
    border-top-left-radius: 10px;
  }
  th:last-child {
    border-top-right-radius: 10px;
  }
</code>```

Try it out in the snippet below.

table {
  border: 1px solid #bcccdc;
  border-collapse: separate;
  border-radius: 10px;
  overflow: hidden;
}
 table td, table th {
  padding: 10px;
  vertical-align: middle;
  border-left: 1px solid #bcccdc;
  border-top: 1px solid #bcccdc;
}
 table th:first-child {
  border-top-left-radius: 10px;
}
 table th:last-child {
  border-top-right-radius: 10px;
}
 table th {
  font-family: sans-serif;
  background-color: #f1f5f8;
  border-top: none;
}
 table td:first-child, table th:first-child {
  border-left: none;
}
 table tr.section-header {
  background-color: #eefcf5;
  font-size: 80%;
  font-weight: 500;
}
 table caption {
  font-family: sans-serif;
  font-style: italic;
  margin-bottom: 5px;
  font-weight: 500;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <caption>A caption</caption>
  <thead>
  <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 3</th>
    <th>Col 4</th>
  </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
  </tbody>
</table></code>```

Body:
You have to set the border-radius (top-left and top-right) for the appropriate th cells (first and last child accordingly). So simply add the following to the CSS of your Codepen Example.

  th:first-child {
    border-top-left-radius: 10px;
  }
  th:last-child {
    border-top-right-radius: 10px;
  }

Try it out in the snippet below.

table {
  border: 1px solid #bcccdc;
  border-collapse: separate;
  border-radius: 10px;
  overflow: hidden;
}
 table td, table th {
  padding: 10px;
  vertical-align: middle;
  border-left: 1px solid #bcccdc;
  border-top: 1px solid #bcccdc;
}
 table th:first-child {
  border-top-left-radius: 10px;
}
 table th:last-child {
  border-top-right-radius: 10px;
}
 table th {
  font-family: sans-serif;
  background-color: #f1f5f8;
  border-top: none;
}
 table td:first-child, table th:first-child {
  border-left: none;
}
 table tr.section-header {
  background-color: #eefcf5;
  font-size: 80%;
  font-weight: 500;
}
 table caption {
  font-family: sans-serif;
  font-style: italic;
  margin-bottom: 5px;
  font-weight: 500;
  text-align: center;
}

<table>
  <caption>A caption</caption>
  <thead>
  <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 3</th>
    <th>Col 4</th>
  </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
  </tbody>
</table>


问:
get previous row id using stored procedure
My requirement like this:

I have to fetch a row from table "A". Now I have to loop through all the rows and get the values from the ID column. If I get ID = 5 then I want to execute some stored procedure through which I get the previous id row from some table "B". Like

```<code>select * from table b where ID = 4
</code>```

Buy my question is: if someone deleted that row from the database (e.g. some user deleted the rows with id 3 and 4) - then how can I get the row with id = 2 from the database?

Please give me some sql stored procedure to get previous id record from table.

答:
Hard to understand exactly what it is your looking for - something like this maybe??

```<code>CREATE PROCEDURE dbo.FetchPreviousRow @ID INT
AS BEGIN

   SELECT TOP 1 ID, (other columns.....)
   FROM dbo.TableB
   WHERE ID < @ID
   ORDER BY ID DESC

END
</code>```

This will select the row with the biggest ID less than the @ID you pass in, so:

```<code>EXEC dbo.FetchPreviousRow @ID = 5
</code>```

will return the row with ID = 4 - if it exists. Otherwise, it will return the row with ID = 3 - if it exists. Otherwise the row with ID = 2 - and so on....

ContentLicense: CC BY-SA 3.0

Body:
My requirement like this:

I have to fetch a row from table "A". Now I have to loop through all the rows and get the values from the ID column. If I get ID = 5 then I want to execute some stored procedure through which I get the previous id row from some table "B". Like

select * from table b where ID = 4

Buy my question is: if someone deleted that row from the database (e.g. some user deleted the rows with id 3 and 4) - then how can I get the row with id = 2 from the database?

Please give me some sql stored procedure to get previous id record from table.

Body:
Hard to understand exactly what it is your looking for - something like this maybe??

CREATE PROCEDURE dbo.FetchPreviousRow @ID INT
AS BEGIN

   SELECT TOP 1 ID, (other columns.....)
   FROM dbo.TableB
   WHERE ID < @ID
   ORDER BY ID DESC

END

This will select the row with the biggest ID less than the @ID you pass in, so:

EXEC dbo.FetchPreviousRow @ID = 5

will return the row with ID = 4 - if it exists. Otherwise, it will return the row with ID = 3 - if it exists. Otherwise the row with ID = 2 - and so on....


问:
Why does javac allow "new CLS().new InnerCLS()" compile?
Consider the following snippet:

(I came across this syntax when inspecting some decompiled class files and this is a minimal representation)

```<code>public class Main {
    public static void main(String[] args) {
        Main.Inner o = new Main().new Inner() {};

        System.out.println("Bye from " + o.getClass());
    }

    class Inner {}
}
</code>```

This compiles and runs fine (I tested a bunch of JDKs).

Can someone please explain how come this compiles and what does this code represent?

This code creates 3 classes:

```<code>1. Main - This creates the following code (I removed the irrelevant parts):
    new Main$1
    dup
    new Main
    dup
    invokespecial Method Main <init> ()V
    dup
    invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
    pop
    invokespecial Method Main$1 <init> (LMain;)V

Why is it calling getClass (the result is popped anyway)?

2. Main$Inner - This class looks like as would expect an inner class to look

3. Main$1 - This creates the following class (I removed the irrelevant parts):
    final class Main$1 extends Main$Inner
    method <init> : (LMain;)V
    aload_0
    aload_1
    dup
    invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
    pop
    invokespecial Method Main$Inner <init> (LMain;)V
    return

Again, why is it calling getClass (the result is popped anyway)?
</code>```

BTW, it can be nested even further like this:

```<code>public class Main {
    public static void main(String[] args) {
        Object o = new Main().new Inner1().new Inner2().new Inner3() {};

        System.out.println("Bye from " + o.getClass());
    }

    class Inner1 {
        class Inner2 {
            class Inner3 {
            }
        }
    }
}
</code>```

答:
Inner classes must be instantiated with a this pointer to the outer class.

The syntax outer.new Inner() is one way to achieve that (the new instance of Inner will have the value of outer as the outer.this reference.

This is equivalent to having a non-static method in the Main class:

```<code>class Main {

    Inner makeInner() {
        /// "this." is implied here, but it is there.
        return new Inner();
    }
    class Inner {
    }
}
</code>```

Body:
Consider the following snippet:

(I came across this syntax when inspecting some decompiled class files and this is a minimal representation)

public class Main {
    public static void main(String[] args) {
        Main.Inner o = new Main().new Inner() {};

        System.out.println("Bye from " + o.getClass());
    }

    class Inner {}
}

This compiles and runs fine (I tested a bunch of JDKs).

Can someone please explain how come this compiles and what does this code represent?

This code creates 3 classes:

1. Main - This creates the following code (I removed the irrelevant parts):
    new Main$1
    dup
    new Main
    dup
    invokespecial Method Main <init> ()V
    dup
    invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
    pop
    invokespecial Method Main$1 <init> (LMain;)V

Why is it calling getClass (the result is popped anyway)?

2. Main$Inner - This class looks like as would expect an inner class to look

3. Main$1 - This creates the following class (I removed the irrelevant parts):
    final class Main$1 extends Main$Inner
    method <init> : (LMain;)V
    aload_0
    aload_1
    dup
    invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
    pop
    invokespecial Method Main$Inner <init> (LMain;)V
    return

Again, why is it calling getClass (the result is popped anyway)?

BTW, it can be nested even further like this:

public class Main {
    public static void main(String[] args) {
        Object o = new Main().new Inner1().new Inner2().new Inner3() {};

        System.out.println("Bye from " + o.getClass());
    }

    class Inner1 {
        class Inner2 {
            class Inner3 {
            }
        }
    }
}

Body:
Inner classes must be instantiated with a this pointer to the outer class.

The syntax outer.new Inner() is one way to achieve that (the new instance of Inner will have the value of outer as the outer.this reference.

This is equivalent to having a non-static method in the Main class:

class Main {

    Inner makeInner() {
        /// "this." is implied here, but it is there.
        return new Inner();
    }
    class Inner {
    }
}


问:
Navigating to child route with route parameter in relation to current route - Angular 8
I want to achieve this:

```<code><button [routerLink]="['deepRoute', deepRouteId]">Deep Route</button>
</code>```

But though an Angular (click) event, from any route (including child routes), like this:

```<code><button (click)="navigateToDeepRoute(deepRouteId)">Deep Route</button>
</code>```

Relevant routing code in my app-routing.module.ts:

```<code>const routes: Routes = [
{
  path: 'mainRoute',
  component: MainRouteComponent,
  children: [
    {
      path: 'childRoute/:childRouteId',
      component: ChildRouteComponent,
      children: [
        {
          path: 'deepRoute/:deepRouteId'
          component: DeepRouteComponent
        }
      ]
    }
  ]
}
....
</code>```

Given my routing, I'm currently in the ChildRouteComponent:

example.com/mainRoute/childRoute/1

And would like to navigate to:

example.com/mainRoute/childRoute/1/deepRoute/2

Inside my ChildRouteComponent, I have my navigation method:

```<code>navigateToDeepRoute(deepRouteId) {
  this.router.navigate(['deeperPath', { deepRouteId: deepRouteId}, { relativeTo: this.route.parent } ]);
}
</code>```

But it's not working..

I've also tried:

```<code>this.router.navigate(['deeperPath', { deepRouteId: deepRouteId } ], { relativeTo: this.route } );
</code>```

And..

```<code>this.router.navigate(['../deeperPath', { deepRouteId: deepRouteId }, { relativeTo: this.route.parent } ]);
</code>```

But still, no cigar. Any advice?

答:
I figured it out, my issue had to do with a very minimal syntax error:</p>

```<code>navigateToDeepRoute(deepRouteId) {
  this.router.navigate(['deeperPath', deepRouteId], { relativeTo: this.route } );
}
</code>```

Body:
I want to achieve this:

<button [routerLink]="['deepRoute', deepRouteId]">Deep Route</button>

But though an Angular (click) event, from any route (including child routes), like this:

<button (click)="navigateToDeepRoute(deepRouteId)">Deep Route</button>

Relevant routing code in my app-routing.module.ts:

const routes: Routes = [
{
  path: 'mainRoute',
  component: MainRouteComponent,
  children: [
    {
      path: 'childRoute/:childRouteId',
      component: ChildRouteComponent,
      children: [
        {
          path: 'deepRoute/:deepRouteId'
          component: DeepRouteComponent
        }
      ]
    }
  ]
}
....

Given my routing, I'm currently in the ChildRouteComponent:

example.com/mainRoute/childRoute/1

And would like to navigate to:

example.com/mainRoute/childRoute/1/deepRoute/2

Inside my ChildRouteComponent, I have my navigation method:

navigateToDeepRoute(deepRouteId) {
  this.router.navigate(['deeperPath', { deepRouteId: deepRouteId}, { relativeTo: this.route.parent } ]);
}

But it's not working..

I've also tried:

this.router.navigate(['deeperPath', { deepRouteId: deepRouteId } ], { relativeTo: this.route } );

And..

this.router.navigate(['../deeperPath', { deepRouteId: deepRouteId }, { relativeTo: this.route.parent } ]);

But still, no cigar. Any advice?

Body:
I figured it out, my issue had to do with a very minimal syntax error:

navigateToDeepRoute(deepRouteId) {
  this.router.navigate(['deeperPath', deepRouteId], { relativeTo: this.route } );
}


问:
What does adding a second parameter in a for loop with nested enumerate() do?
I'm trying myself on Python again and I want to create a text-based Ticktacktoe.

Currently, I am working on the layout with 0 representing the empty spaces in the games and numbers up top and on the left for coordinates.This is what I have so far:

```<code>game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for row in enumerate(game):
    print(row)
</code>```

which outputs this :

```<code>     0  1  2
(0, [0, 0, 0])
(1, [0, 0, 0])
(2, [0, 0, 0])
</code>```

The problem is that I want it to look like this:

```<code>   0  1  2
0 [0, 0, 0]
1 [0, 0, 0]
2 [0, 0, 0]
</code>```

Now I found a way by adding 'count' into the for loop. But I don't understand why at all.
Looking up the Python documentation did not help.
Why is this happening? Why does that get rid of the brackets and commas?

```<code>game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for count, row in enumerate(game):
    print(count, row)
</code>```

Edit: I think I understand now.Since enumarate() returns the Index and the value all that's basically happening is that I assigned count to the Index and row to basically the value? And that is why there are now brackets since print prints more than 1 variable using a space? Could you confirm this?

答: In the first example a tuple will be passed to print(), which is printed enclosed in parenthesis. In the second answer the row count and the row itself are passed as separate arguments to print() - print() will then print the arguments space separated.

Body:
I'm trying myself on Python again and I want to create a text-based Ticktacktoe.

Currently, I am working on the layout with 0 representing the empty spaces in the games and numbers up top and on the left for coordinates.This is what I have so far:

game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for row in enumerate(game):
    print(row)

which outputs this :

     0  1  2
(0, [0, 0, 0])
(1, [0, 0, 0])
(2, [0, 0, 0])

The problem is that I want it to look like this:

   0  1  2
0 [0, 0, 0]
1 [0, 0, 0]
2 [0, 0, 0]

Now I found a way by adding 'count' into the for loop. But I don't understand why at all.
Looking up the Python documentation did not help.
Why is this happening? Why does that get rid of the brackets and commas?

game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for count, row in enumerate(game):
    print(count, row)

Edit: I think I understand now.Since enumarate() returns the Index and the value all that's basically happening is that I assigned count to the Index and row to basically the value? And that is why there are now brackets since print prints more than 1 variable using a space? Could you confirm this?


问:
Wordpress - Add comma to all but last item, remove underscore
I'm using the advanced custom field plugin for Wordpress to show the results of checkboxes. I have what I want working, I just want to tidy up the code and add the following:

Remove the underscore from the social media tag (some kind of stripping out???).

If possible I'd like to show a comma after each "tag" but not if it's the last one.

Here's my test page, they're the blue "tags" under the discipline section.

Here's my code:

```<code>    <?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

foreach($catNames as $name){
    if(in_array($name, get_field('categories') )){
echo '<a href="/tags/design/'.$name.'" title="'.$name.'">'.strtoupper($name).'</a>';
    }
}
?>
</code>```

答:
Ok this should be better</p>

```<code><?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');
    foreach($catNames as $name){
        $theID = get_cat_ID($name); // get the ID of each category
        echo '<a href="'.get_category_link($theID).'" title="'.$theID->name.'">'.$theID->name.'</a>';
    }
?>
</code>```

Body:
I'm using the advanced custom field plugin for Wordpress to show the results of checkboxes. I have what I want working, I just want to tidy up the code and add the following:

Remove the underscore from the social media tag (some kind of stripping out???).

If possible I'd like to show a comma after each "tag" but not if it's the last one.

Here's my test page, they're the blue "tags" under the discipline section.

Here's my code:

    <?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

foreach($catNames as $name){
    if(in_array($name, get_field('categories') )){
echo ''.strtoupper($name).'';
    }
}
?>

Body:
Ok this should be better

<?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');
    foreach($catNames as $name){
        $theID = get_cat_ID($name); // get the ID of each category
        echo '<a href="'.get_category_link($theID).'" title="'.$theID->name.'">'.$theID->name.'</a>';
    }
?>


问:
Do variable length arrays start with default 0 values in C?
I know I cannot initialize variable-length arrays in C with explicitly provided values. The following code is not supported:

```<code>void main() {
  int l = 2;
  float test[l] = {1.0, 2.0};  // my compiler says: "Variable-sized object may not be initialized"
}
</code>```

My question is: if I don't attempt to give any values:

```<code>void main() {
  int l = 2;
  float test[l];
}
</code>```

…will a C compiler make sure it starts initialized to zero by default?

答:
Variable length arrays are not initialized by default and cannot be initialized explicitly, except that memory allocation routines such as calloc may initialize the space.

C 2018 6.7.6.2 (“Array declarators”) 2 says:

… If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.

So the storage duration of a variable length array must be one of the other storage durations: automatic or allocated [6.2.4 1]. (There is a temporary storage duration, but only for structures or unions [6.2.4 7].)

6.7.9 10 says objects with automatic storage duration are not initialized by default:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate…

Additionally, 6.7.9 3 says you cannot initialize variable length arrays explicitly:

The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

Body:
I know I cannot initialize variable-length arrays in C with explicitly provided values. The following code is not supported:

void main() {
  int l = 2;
  float test[l] = {1.0, 2.0};  // my compiler says: "Variable-sized object may not be initialized"
}

My question is: if I don't attempt to give any values:

void main() {
  int l = 2;
  float test[l];
}

…will a C compiler make sure it starts initialized to zero by default?


问:
gRPC Distributed Servers - Keeping Packet Order
I'm trying out gRPC as a solution to a problem and im wondering if its possible to do that, i have not found anything regarding this.

Ill exemplify the problem

Let's say i have a distributed server A of 100 nodes.

Those servers are going to call another server B, which is a single node, using gRPC calls. Each node has a pool of connections open to server B.

The goal is to make sure server B receives all requests in order. Since latency can vary, if two nodes of server A sends requests almost at the same time, it would be possible to receive those requests in an incorrect order ?

Would apreciate any help. Thanks

答:
inter stream order is not guaranteed in http2 layer. your best bet is client generates a sequence number (this is yet another very hard problem), so you can handle it in order on the server side (B).
Note that telling order of request itself is very hard unless you have an atomic clock.

this problem usually means you are trying solve the actual problem in wrong way. with some legacy code this can be unavoidable, but better to fix underlying issue rather than fix it in hacky way or something impossible.


问:
percentile rank in pandas in groups
I can't quite figure out how to write function to accomplish a grouped percentile.  I have all teams from years 1985-2012 in a data frame; the first 10 are shown below: it's currently sorted by year.  I was looking to give a percentile for LgRnk grouped by Year.  So for instance, 23 LgRank (worst team) for 1985 would be a 100 percentile and a 1 LgRank (best team) for 1985 would be a 1 percentile. 30 LgRank (worst team) for 2010 would be 100 percentile, etc.   It needs to be grouped by year b/c of the differing number of LgRnks.

```<code>    Team                WLPer   Year LgRnk   W  L
19  Sacramento Kings    0.378   1985    18  31  51
0   Atlanta Hawks       0.415   1985    17  34  48
17  Phoenix Suns        0.439   1985    16  36  46
4   Cleveland Cavaliers 0.439   1985    15  36  46
13  Milwaukee Bucks     0.720   1985    3   59  23
3   Chicago Bulls       0.463   1985    14  38  44
16  Philadelphia 76ers  0.707   1985    4   58  24
22  Washington Wizards  0.488   1985    13  40  42
20  San Antonio Spurs   0.500   1985    12  41  41
21  Utah Jazz           0.500   1985    11  41  41
</code>```

I've tried creating a function using: scipy.stats.percentileofscore
and I can't quite get it.

答:
You need to calculate rank within the group before normalizing within the group. The other answers will result in percentiles over 100%. I suggest:</p>

```<code>df['percentile'] = df.groupby('year')['LgRnk'].rank(pct=True)
</code>```

Title: percentile rank in pandas in groups

Body:
I can't quite figure out how to write function to accomplish a grouped percentile.  I have all teams from years 1985-2012 in a data frame; the first 10 are shown below: it's currently sorted by year.  I was looking to give a percentile for LgRnk grouped by Year.  So for instance, 23 LgRank (worst team) for 1985 would be a 100 percentile and a 1 LgRank (best team) for 1985 would be a 1 percentile. 30 LgRank (worst team) for 2010 would be 100 percentile, etc.   It needs to be grouped by year b/c of the differing number of LgRnks.

    Team                WLPer   Year LgRnk   W  L
19  Sacramento Kings    0.378   1985    18  31  51
0   Atlanta Hawks       0.415   1985    17  34  48
17  Phoenix Suns        0.439   1985    16  36  46
4   Cleveland Cavaliers 0.439   1985    15  36  46
13  Milwaukee Bucks     0.720   1985    3   59  23
3   Chicago Bulls       0.463   1985    14  38  44
16  Philadelphia 76ers  0.707   1985    4   58  24
22  Washington Wizards  0.488   1985    13  40  42
20  San Antonio Spurs   0.500   1985    12  41  41
21  Utah Jazz           0.500   1985    11  41  41

I've tried creating a function using: scipy.stats.percentileofscore
and I can't quite get it.

Body:
You need to calculate rank within the group before normalizing within the group. The other answers will result in percentiles over 100%. I suggest:

df['percentile'] = df.groupby('year')['LgRnk'].rank(pct=True)


问:
AWS Amplify Auth with Cognito User Pool not returning nonce or at_hash claim in JWT id_token
I'm trying to use Amplify Auth to implement an OpenID Connect Implicit Flow to provide SSO to a number of React clients.

I've been able to get this working with Cognito Hosted UI, but that requires other apps users to click a button to confirm login in order to authenticate. I'd prefer for it to be seamless ie when a user is logged in on one site and navigate to another they are automatically authenticated if they have a session with the auth provider.

To try and achieve this I've set up a separate Amplify app that uses the React Authenticator Component.

I'm able to authenticate with this and redirect back to the client. However the id_token doesn't contain the at_hash or nonce claim. Presumably, the at_hash is missing because the authentication provider app is not sending the responseType of token id_token when it authenticates with Cognito. The nonce is missing because I haven't found a way to pass it in.

Is there a way to get Amplify Authenticator SignIn to request an id_token with the at_hash claim?

Is it possible to pass a nonce value through to the id_token claims?

Note
I'm trying to adhere to: https://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowSteps
Specifically for this part: 3.2.2.10.  ID Token

```<code>import React from 'react';
import { Authenticator, ConfirmSignIn, SignIn } from 'aws-amplify-react';
import Amplify, { Auth } from 'aws-amplify';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);

const getSearchParams = () =>
    window.location.search.substr(1);

const getValueFromSearchParam = (key) =>
    new URLSearchParams(getSearchParams()).get(key);

const getRedirectUri = () => {
    const redirect_uri = getValueFromSearchParam('redirect_uri');
    return redirect_uri ? decodeURI(redirect_uri) : null;
};

const Login = () => {
    const handleAuthStateChange = (state) => {
        if(state === 'signedIn') {
            const redirect_uri = getRedirectUri();
            const state = getValueFromSearchParam('state');
            if(redirect_uri === null) {
                throw new Error('No redirect_uri provided');
            }
            Auth.currentSession().then(currentSession => {
                const id_token = currentSession.idToken.jwtToken;
                const access_token = currentSession.accessToken.jwtToken;
                const redirect = `${redirect_uri}#access_token=${access_token}&id_token=${id_token}&state=${state}`;
                window.location.replace(redirect);
            }).catch(err => console.error(err));
        }
    };

    return (
        <Authenticator
            hideDefault={true}
            onStateChange={handleAuthStateChange}
        >
            <SignIn  />
            <ConfirmSignIn/>
        </Authenticator>
    );
};
</code>```

答:
A few issues here that may be of interest:

Cognito lacks some standards based support, as you are noticing

If you use response_type = token id_token you will be limited to fixed 60 minute user sessions

Amplify may not be the most standard based library in terms of nonce parameters etc

Authorization Code Flow (PKCE) is recommended these days for SPAs - you may find this an easier way to implement the post login checks you are looking for

Unfortunately you may need to make some trade offs when working with Cognito - and make the 'least bad choice'. If it helps, here is some stuff of mine to compare against:

Cognito integration using OIDC Client Library

Online Link to Code Sample

Cognito Write Up

SPA Token Renewal Notes

Body:
I'm trying to use Amplify Auth to implement an OpenID Connect Implicit Flow to provide SSO to a number of React clients.

I've been able to get this working with Cognito Hosted UI, but that requires other apps users to click a button to confirm login in order to authenticate. I'd prefer for it to be seamless ie when a user is logged in on one site and navigate to another they are automatically authenticated if they have a session with the auth provider.

To try and achieve this I've set up a separate Amplify app that uses the React Authenticator Component.

I'm able to authenticate with this and redirect back to the client. However the id_token doesn't contain the at_hash or nonce claim. Presumably, the at_hash is missing because the authentication provider app is not sending the responseType of token id_token when it authenticates with Cognito. The nonce is missing because I haven't found a way to pass it in.

Is there a way to get Amplify Authenticator SignIn to request an id_token with the at_hash claim?

Is it possible to pass a nonce value through to the id_token claims?

Note
I'm trying to adhere to: https://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowSteps
Specifically for this part: 3.2.2.10.  ID Token

import React from 'react';
import { Authenticator, ConfirmSignIn, SignIn } from 'aws-amplify-react';
import Amplify, { Auth } from 'aws-amplify';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);

const getSearchParams = () =>
    window.location.search.substr(1);

const getValueFromSearchParam = (key) =>
    new URLSearchParams(getSearchParams()).get(key);

const getRedirectUri = () => {
    const redirect_uri = getValueFromSearchParam('redirect_uri');
    return redirect_uri ? decodeURI(redirect_uri) : null;
};

const Login = () => {
    const handleAuthStateChange = (state) => {
        if(state === 'signedIn') {
            const redirect_uri = getRedirectUri();
            const state = getValueFromSearchParam('state');
            if(redirect_uri === null) {
                throw new Error('No redirect_uri provided');
            }
            Auth.currentSession().then(currentSession => {
                const id_token = currentSession.idToken.jwtToken;
                const access_token = currentSession.accessToken.jwtToken;
                const redirect = `${redirect_uri}#access_token=${access_token}&id_token=${id_token}&state=${state}`;
                window.location.replace(redirect);
            }).catch(err => console.error(err));
        }
    };

    return (
        <Authenticator
            hideDefault={true}
            onStateChange={handleAuthStateChange}
        >
            <SignIn  />
            <ConfirmSignIn/>
        </Authenticator>
    );
};


问:
Maven Dependencies? Doesn't access servlet - 404 Error
I have a program that I wrote a couple years ago for a class, and it worked fine. Recently I updated a lot of things - Java, Eclipse, Tomcat, etc. because I haven't been programming in a while. I messed with the dependencies and now I cannot get it to work. It correctly displays the opening jsp, but never makes it to the handling servlet, giving me a 404 error. I think that I must not have the correct dependency for the servlet anymore? I know the program works, so I have not included code for it. The program uses Eclipselink, mySQL, JSP, and Servlets. (Yes, kicking myself for messing with it). These are the dependencies I have. Am I missing one? Have the wrong one? I am not well versed in maven dependencies

```<code>    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>2.7.6</version>
</dependency>
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa</artifactId>
    <version>2.7.6</version>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>
</code>```

And my build has:
Apache Tomcat 9
Java jdk 13.1
Maven Dependencies

Thanks for any help you can give.

答: Well, dang it all. I have been trying to get this working for 2 days. Decided problem was with Tomcat. Downloaded and reinstalled it all. Port errors. Changed to every number in the world. Cleaned server, updated project, etc. Nothing worked. Kept getting port number error. Finally saw where someone said they fixed it by restarting computer. Last ditch effort and for some godforsaken reason, it worked. SOOOOOO frustrating. Thanks for your help anyway. I should know - when in doubt, reboot.  </p>

Body:
I have a program that I wrote a couple years ago for a class, and it worked fine. Recently I updated a lot of things - Java, Eclipse, Tomcat, etc. because I haven't been programming in a while. I messed with the dependencies and now I cannot get it to work. It correctly displays the opening jsp, but never makes it to the handling servlet, giving me a 404 error. I think that I must not have the correct dependency for the servlet anymore? I know the program works, so I have not included code for it. The program uses Eclipselink, mySQL, JSP, and Servlets. (Yes, kicking myself for messing with it). These are the dependencies I have. Am I missing one? Have the wrong one? I am not well versed in maven dependencies

    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>2.7.6</version>
</dependency>
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa</artifactId>
    <version>2.7.6</version>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

And my build has:
Apache Tomcat 9
Java jdk 13.1
Maven Dependencies

Thanks for any help you can give.


问:
How can i append a space in each side of a string?
i have a NSString object named as myString.i need to append a space in each side of my string.
can any one tell me the good way to do it?</p>

答:
```<code>NSString *myNewString = [NSString stringWithFormat: @" %@ ", myString];
</code>```


问:
Is there a way to initialize a vector by index in c++11?
It is easy to fill the elements of a vector by index after it has been initialized:

```<code>std::vector<int> myVector {0, 0, 0};
int indexOfInterest = 1;
myVector[indexOfInterest] = 999;
// myVector now contains {0, 999, 0}
</code>```

However, is there a way to initialize a vector directly with the index? indexOfInterest may change in my code in the future, and I would like to avoid hard-coding the vector with

```<code>std::vector<int> myVector {0, 999, 0};
</code>```

Is there some syntax like

```<code>int indexOfInterest = 1;
std::vector<int> myVector[3] {indexOfInterest : 999}; // this is made-up syntax!
// desired: myVector contains {0, 999, 0} and is 3 elements large
</code>```

that can be used in C++11 to achieve this effect?

答:
In the comments you mention, that you need this in order to initialize the vector in a member initializer list.

You can delegate the construction to a function or lambda in the member initializer list:

```<code>some_constructor(...) : myVector([]{
    std::vector<int> vec(3);
    myVector[indexOfInterest] = 999;
    return vec;
}()) {
}
</code>```

You can also write yourself a generic function for the task, e.g.:

```<code>template<typename T, std::size_t N>
std::vector<T> make_vector(typename std::vector<T>::size_type size, const T& value, std::pair<typename std::vector<T>::size_type, T>(&&entries)[N]) {
    std::vector<T> vec(size, value);
    for(auto& entry : entries)
        vec[entry.first] = std::move(entry.second);
    return vec;
}

template<typename T, std::size_t N>
std::vector<T> make_vector(typename std::vector<T>::size_type size, std::pair<typename std::vector<T>::size_type, T>(&&entries)[N]) {
    return make_vector<T>(size, {}, entries);
}
</code>```

This can be used in the member initializer for example like this:

```<code>some_constructor(...) : myVector(make_vector(3, 0, {{indexOfInterest, 999}})) {
}
</code>```

or

```<code>some_constructor(...) : myVector(make_vector<int>(3, {{indexOfInterest, 999}})) {
}
</code>```

with the second overload.

Instead of an array, you can also take the argument as a std::initializer_list<...> with the difference being that the array version instantiates new functions for each list size given to the call, while the initializer list will use the same function for different list sizes.

The function does in any case not copy the constructed vector. It may however move it once (C++17, due to mandatory copy elision except for vec into the return value) or multiple times (before C++17). All these may however be optimized away by the compiler due to (named) return value optimization.

Body:
It is easy to fill the elements of a vector by index after it has been initialized:

std::vector<int> myVector {0, 0, 0};
int indexOfInterest = 1;
myVector[indexOfInterest] = 999;
// myVector now contains {0, 999, 0}

However, is there a way to initialize a vector directly with the index? indexOfInterest may change in my code in the future, and I would like to avoid hard-coding the vector with

std::vector<int> myVector {0, 999, 0};

Is there some syntax like

int indexOfInterest = 1;
std::vector<int> myVector[3] {indexOfInterest : 999}; // this is made-up syntax!
// desired: myVector contains {0, 999, 0} and is 3 elements large

that can be used in C++11 to achieve this effect?

Body:
In the comments you mention, that you need this in order to initialize the vector in a member initializer list.

You can delegate the construction to a function or lambda in the member initializer list:

some_constructor(...) : myVector([]{
    std::vector<int> vec(3);
    myVector[indexOfInterest] = 999;
    return vec;
}()) {
}

You can also write yourself a generic function for the task, e.g.:

template<typename T, std::size_t N>
std::vector<T> make_vector(typename std::vector<T>::size_type size, const T& value, std::pair<typename std::vector<T>::size_type, T>(&&entries)[N]) {
    std::vector<T> vec(size, value);
    for(auto& entry : entries)
        vec[entry.first] = std::move(entry.second);
    return vec;
}

template<typename T, std::size_t N>
std::vector<T> make_vector(typename std::vector<T>::size_type size, std::pair<typename std::vector<T>::size_type, T>(&&entries)[N]) {
    return make_vector<T>(size, {}, entries);
}

This can be used in the member initializer for example like this:

some_constructor(...) : myVector(make_vector(3, 0, {{indexOfInterest, 999}})) {
}

or

some_constructor(...) : myVector(make_vector<int>(3, {{indexOfInterest, 999}})) {
}

with the second overload.

Instead of an array, you can also take the argument as a std::initializer_list<...> with the difference being that the array version instantiates new functions for each list size given to the call, while the initializer list will use the same function for different list sizes.

The function does in any case not copy the constructed vector. It may however move it once (C++17, due to mandatory copy elision except for vec into the return value) or multiple times (before C++17). All these may however be optimized away by the compiler due to (named) return value optimization.


答:
enumerate(items) returns a list of tuples of a number and your item, where the number increases by one for each new item in the list (counting).
In this case enumerate returns the following tuples:

```<code>{0, [0, 0, 0]}, {1, [0, 0, 0]}, {2, [0, 0, 0]}
</code>```

By using a second variable name in the for loop you are destructuring the tuple into count and row. Whereas before you were only giving 1 variable name, so the variable was assigned the entire tuple.

Title: What does adding a second parameter in a for loop with nested enumerate() do?

Body:
enumerate(items) returns a list of tuples of a number and your item, where the number increases by one for each new item in the list (counting).
In this case enumerate returns the following tuples:

{0, [0, 0, 0]}, {1, [0, 0, 0]}, {2, [0, 0, 0]}

By using a second variable name in the for loop you are destructuring the tuple into count and row. Whereas before you were only giving 1 variable name, so the variable was assigned the entire tuple.


问:
How to create OnPointerDownMixedRealityPointerEventData dynamycally in a cube?
I am working with MRTK 2.3.0 version, I have created a dragged cube when "event pointer down" creates a new gameobject cube, but the new cube has not event. I want to assign a event for move it. How could assign event by code?</p>

```<code>    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Microsoft.MixedReality.Toolkit.Input;

    public class TouchableCube : MonoBehaviour, IMixedRealityPointerHandler
    {
        Color colorBlue = Color.blue;
        Renderer rend;

        public void OnPointerClicked(MixedRealityPointerEventData eventData)
        {
            rend.material.color = colorBlue;
        }

        public void OnPointerDown(MixedRealityPointerEventData eventData)
        {
            rend.material.color = Color.red;
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.position = new Vector3(0,0,2);

            cube.SetActive(true);

        }

        public void OnPointerDragged(MixedRealityPointerEventData eventData)
        {
            rend.material.color = Color.yellow;
            Vector3 v = new Vector3(
                               eventData.Pointer.Position.x,
                               eventData.Pointer.Position.y,
                               eventData.Pointer.Position.z);
            rend.transform.position = v;
        }
</code>```

答:
You can add a PointerHandler to your to and add listeners it. Here is how you would add a listener that changes a color of the cube, from your sample code:

```<code>        public void OnPointerDown(MixedRealityPointerEventData eventData)
        {
            rend.material.color = Color.red;
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.position = new Vector3(0,0,2);
            var pointerHandler = target.AddComponent<PointerHandler>();
            pointerHandler.OnPointerDown.AddListener((e) => material.color = Color.green);
            pointerHandler.OnPointerUp.AddListener((e) => material.color = Color.magenta);
            cube.SetActive(true);

        }
</code>```

For more examples, see How to add near interactivity and Pointers.

Body:
I am working with MRTK 2.3.0 version, I have created a dragged cube when "event pointer down" creates a new gameobject cube, but the new cube has not event. I want to assign a event for move it. How could assign event by code?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Microsoft.MixedReality.Toolkit.Input;

    public class TouchableCube : MonoBehaviour, IMixedRealityPointerHandler
    {
        Color colorBlue = Color.blue;
        Renderer rend;

        public void OnPointerClicked(MixedRealityPointerEventData eventData)
        {
            rend.material.color = colorBlue;
        }

        public void OnPointerDown(MixedRealityPointerEventData eventData)
        {
            rend.material.color = Color.red;
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.position = new Vector3(0,0,2);

            cube.SetActive(true);

        }

        public void OnPointerDragged(MixedRealityPointerEventData eventData)
        {
            rend.material.color = Color.yellow;
            Vector3 v = new Vector3(
                               eventData.Pointer.Position.x,
                               eventData.Pointer.Position.y,
                               eventData.Pointer.Position.z);
            rend.transform.position = v;
        }

Body:
You can add a PointerHandler to your to and add listeners it. Here is how you would add a listener that changes a color of the cube, from your sample code:

        public void OnPointerDown(MixedRealityPointerEventData eventData)
        {
            rend.material.color = Color.red;
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.position = new Vector3(0,0,2);
            var pointerHandler = target.AddComponent<PointerHandler>();
            pointerHandler.OnPointerDown.AddListener((e) => material.color = Color.green);
            pointerHandler.OnPointerUp.AddListener((e) => material.color = Color.magenta);
            cube.SetActive(true);

        }

For more examples, see How to add near interactivity and Pointers.


问:
Vanilla JavaScript in Svelte
I've been following a guide to collapse a sidebar. I realised that I cannot use the $ because it's reserved in Svelte. Can someone guide me on how to make this work? Thanks :)

```<code>$(document).ready(function () {
    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });
});
</code>```

答:
The equivalent vanilla js code would be:</p>

```<code>const sidebarCollapse = document.getElementById('sidebarCollapse');
const sidebar = document.getElementById('sidebar');

sidebarCollapse.onclick = () => sidebar.classList.toggle('active');
</code>```

Title: Vanilla JavaScript in Svelte

Body:
I've been following a guide to collapse a sidebar. I realised that I cannot use the $ because it's reserved in Svelte. Can someone guide me on how to make this work? Thanks :)

$(document).ready(function () {
    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });
});

Body:
The equivalent vanilla js code would be:

const sidebarCollapse = document.getElementById('sidebarCollapse');
const sidebar = document.getElementById('sidebar');

sidebarCollapse.onclick = () => sidebar.classList.toggle('active');


问:
Kotlin multiplatform project is using old complied code
I am experimenting with kotlin multiplatform code I got some sample code running but have made changes to that code now. Every time i compile my project the old kotlin code is run instead of the new code with my changes. How do i make a clean build with the new kotlin code? i have tried invalidating the caches and restarting android, uninstalling the application, running gradle build androidJar, androidMainClasses,clean all haven't worked. Any ideas?  When i try to change the name of the method i get Caused by: java.lang.NoSuchMethodError: No static method aboutMe it can't find the new method

答: A new build should clear out old compiled code that has changed, but if it doesn't, run gradle clean (either from a command line with the gradlew wrapper or via the gradle tasks window in Android Studio). This will remove the build directory which will cause the next build to rebuild everything and should eliminate cached code issues.


问:
Convert word to pdf java
I'm trying convert word to pdf, my code is:

```<code>public static void main(String[] args) {
    try  {
        XWPFDocument document = new XWPFDocument();
        document.createStyles();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun title = paragraph.createRun();
        title.setText("gLETS GO");

        PdfOptions options = PdfOptions.create();
        OutputStream out = new FileOutputStream(new File("C:/Users/pepe/Desktop/DocxToPdf1.pdf"));
        PdfConverter.getInstance().convert(document, out, options);
        System.out.println("Done");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

I'm getting error:

```<code>fr.opensagres.poi.xwpf.converter.core.XWPFConverterException: org.apache.xmlbeans.XmlException: error: Unexpected end of file after null
at fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:71)
at fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:39)

Caused by: org.apache.xmlbeans.XmlException: error: Unexpected end of file
</code>```

I have tried other solutions but doesnt works. I create a java project, if someone can help me or other way to do

答:
This is probably a duplicate of Trying to make simple PDF document with Apache poi. But let's have a complete example again to show how to create a new XWPFDocument from scratch using the latest apache poi 4.1.2 which then can be converted to PDF using PdfConverter of fr.opensagres.poi.xwpf.converter version 2.0.2 and iText.

As told the default *.docx documents created by apache poi lacks some content which PdfConverter needs.

There must be a styles document, even if it is empty.

And there must be section properties for the page having at least the page size set. To fulfilling this we must add some code additionally in our program. Unfortunately this then needs the full jar of all of the schemas ooxml-schemas-1.4.jar as mentioned in Faq-N10025.

And because we need changing the underlying low level objects, the document must be written so underlying objects will be committed. Else the XWPFDocument which we hand over the PdfConverter will be incomplete.

Minimal complete working example:

```<code>import java.io.*;
import java.math.BigInteger;

//needed jars: fr.opensagres.poi.xwpf.converter.core-2.0.2.jar,
//             fr.opensagres.poi.xwpf.converter.pdf-2.0.2.jar,
//             fr.opensagres.xdocreport.itext.extension-2.0.2.jar,
//             itext-4.2.1.jar
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;

//needed jars: apache poi and it's dependencies
//             and additionally: ooxml-schemas-1.4.jar
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class XWPFToPDFConverterSampleMin {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  // there must be a styles document, even if it is empty
  XWPFStyles styles = document.createStyles();

  // there must be section properties for the page having at least the page size set
  CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
  CTPageSz pageSz = sectPr.addNewPgSz();
  pageSz.setW(BigInteger.valueOf(12240)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
  pageSz.setH(BigInteger.valueOf(15840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"

  // filling the body
  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun title = paragraph.createRun();
  title.setText("gLETS GO");

  //document must be written so underlaaying objects will be committed
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  document.write(out);
  document.close();

  document = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()));
  PdfOptions options = PdfOptions.create();
  PdfConverter converter = (PdfConverter)PdfConverter.getInstance();
  converter.convert(document, new FileOutputStream("XWPFToPDFConverterSampleMin.pdf"), options);

  document.close();

 }
}
</code>```

Title: Convert word to pdf java

Body:
I'm trying convert word to pdf, my code is:

public static void main(String[] args) {
    try  {
        XWPFDocument document = new XWPFDocument();
        document.createStyles();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun title = paragraph.createRun();
        title.setText("gLETS GO");

        PdfOptions options = PdfOptions.create();
        OutputStream out = new FileOutputStream(new File("C:/Users/pepe/Desktop/DocxToPdf1.pdf"));
        PdfConverter.getInstance().convert(document, out, options);
        System.out.println("Done");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I'm getting error:

fr.opensagres.poi.xwpf.converter.core.XWPFConverterException: org.apache.xmlbeans.XmlException: error: Unexpected end of file after null
at fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:71)
at fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.doConvert(PdfConverter.java:39)

Caused by: org.apache.xmlbeans.XmlException: error: Unexpected end of file

I have tried other solutions but doesnt works. I create a java project, if someone can help me or other way to do

Body:
This is probably a duplicate of Trying to make simple PDF document with Apache poi. But let's have a complete example again to show how to create a new XWPFDocument from scratch using the latest apache poi 4.1.2 which then can be converted to PDF using PdfConverter of fr.opensagres.poi.xwpf.converter version 2.0.2 and iText.

As told the default *.docx documents created by apache poi lacks some content which PdfConverter needs.

There must be a styles document, even if it is empty.

And there must be section properties for the page having at least the page size set. To fulfilling this we must add some code additionally in our program. Unfortunately this then needs the full jar of all of the schemas ooxml-schemas-1.4.jar as mentioned in Faq-N10025.

And because we need changing the underlying low level objects, the document must be written so underlying objects will be committed. Else the XWPFDocument which we hand over the PdfConverter will be incomplete.

Minimal complete working example:

import java.io.*;
import java.math.BigInteger;

//needed jars: fr.opensagres.poi.xwpf.converter.core-2.0.2.jar,
//             fr.opensagres.poi.xwpf.converter.pdf-2.0.2.jar,
//             fr.opensagres.xdocreport.itext.extension-2.0.2.jar,
//             itext-4.2.1.jar
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;

//needed jars: apache poi and it's dependencies
//             and additionally: ooxml-schemas-1.4.jar
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class XWPFToPDFConverterSampleMin {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  // there must be a styles document, even if it is empty
  XWPFStyles styles = document.createStyles();

  // there must be section properties for the page having at least the page size set
  CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
  CTPageSz pageSz = sectPr.addNewPgSz();
  pageSz.setW(BigInteger.valueOf(12240)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
  pageSz.setH(BigInteger.valueOf(15840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"

  // filling the body
  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun title = paragraph.createRun();
  title.setText("gLETS GO");

  //document must be written so underlaaying objects will be committed
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  document.write(out);
  document.close();

  document = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()));
  PdfOptions options = PdfOptions.create();
  PdfConverter converter = (PdfConverter)PdfConverter.getInstance();
  converter.convert(document, new FileOutputStream("XWPFToPDFConverterSampleMin.pdf"), options);

  document.close();

 }
}


问:
Spring MVC - Query param with hyphens in name in POJO
My Spring Boot Application has an API - GET : /employee

And request can have query params like (ALL with dash in the variable name) - first-name, last-name, phone-number, zip-code etc.

I also have to do sanity JAVAX validation( @Size, @Pattern etc. ) on these parameters, so I am consuming these params in a EmployeeRequest POJO ex. @Valid EmployeeRequest bean.

But in have variable names are not allowed with hyphens, so its not working.

I can do this by using -
   @RequestParam(value = "first-name,required = false) String firstName

But by doing so, my controller method will have tens of arguments and I have to Javax validation explicitly, so I am trying to do using Request POJO.

Please provide the advise how we handle it where we have multiple query param with hyphens in name and needs Javax validation in Spring Boot application.

答:
Soem code would make your question a bit easier to understand however is seems that you are looking for the following:

```<code>public class EmployeeRequest{

   @JsonProperty("first-name")
   private String firstName;

   @JsonProperty("last-name")
   private String lastName;

}
</code>```

https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonProperty.html

Defines name of the logical property, i.e. JSON object field name to
  use for the property.

Body:
Soem code would make your question a bit easier to understand however is seems that you are looking for the following:

public class EmployeeRequest{

   @JsonProperty("first-name")
   private String firstName;

   @JsonProperty("last-name")
   private String lastName;

}

https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonProperty.html

Defines name of the logical property, i.e. JSON object field name to
  use for the property.


问:
Changing an item in a list with a text document
I have a problem where i'm running a function that should check through the lines in the text document, find the username that matches, and chagne the 2nd sintem in the list with each line (its a password reset program). The text document normally looks like this:

```<code>test test
username password
hello hi
</code>```

This is the code i've tried. reset_username was taken when logging in.(I've also included the login function for example)

password change function:

```<code>def password_change():
    for _ in open('info.txt', 'r').readlines():
        login_info = _.split()
        if reset_username == login_info[0]:
            login_info[1] = [password_reenter_txt.get()]
            menu_window()
</code>```

Login function:

```<code>def txt_file_log_in():

    try:
        for _ in open('info.txt', 'r').readlines():
            login_info = _.split() #split on the space made and store result with 2 strings
            if username_enter_txt.get() == login_info[0] and password_enter_txt.get() == login_info[1]:
                password_fault_report.configure(text='User name and Password Correct')

                global reset_username
                reset_username = username_enter_txt.get()

                messagebox.showinfo('Success', 'You have successfully logged in!')#pop up window informing user for sign up.
                login_window.destroy()
                final_window()

        password_fault_report.configure(text='User name or password incorrect,')

    except:
        password_fault_report.configure(text='No accounts found, you need to sign in first...')
</code>```

The error i'm having is that it will run the function and run the menu window, however it doesn't change the document at all.

I am a beginner in tk, python so it could be a very stupid mistake so sorry. Also if iv'e made a mistake in the post, also let me know :)

答: You're reading your data from a file, then modifying the data in memory, but you never write it back to the file.

Body:
I have a problem where i'm running a function that should check through the lines in the text document, find the username that matches, and chagne the 2nd sintem in the list with each line (its a password reset program). The text document normally looks like this:

test test
username password
hello hi

This is the code i've tried. reset_username was taken when logging in.(I've also included the login function for example)

password change function:

def password_change():
    for _ in open('info.txt', 'r').readlines():
        login_info = _.split()
        if reset_username == login_info[0]:
            login_info[1] = [password_reenter_txt.get()]
            menu_window()

Login function:

def txt_file_log_in():

    try:
        for _ in open('info.txt', 'r').readlines():
            login_info = _.split() #split on the space made and store result with 2 strings
            if username_enter_txt.get() == login_info[0] and password_enter_txt.get() == login_info[1]:
                password_fault_report.configure(text='User name and Password Correct')

                global reset_username
                reset_username = username_enter_txt.get()

                messagebox.showinfo('Success', 'You have successfully logged in!')#pop up window informing user for sign up.
                login_window.destroy()
                final_window()

        password_fault_report.configure(text='User name or password incorrect,')

    except:
        password_fault_report.configure(text='No accounts found, you need to sign in first...')

The error i'm having is that it will run the function and run the menu window, however it doesn't change the document at all.

I am a beginner in tk, python so it could be a very stupid mistake so sorry. Also if iv'e made a mistake in the post, also let me know :)


问:
How can I change the size of drawer/back button icons of appbar without modifying the behavior provided by default in Flutter?
I am trying to change the size of the icons ("Back" provided by Navigator and "Drawer" provided by Scaffold) in appbar in my ThemeData, modifying iconTheme and primaryIconTheme:

```<code>ThemeData(
    primarySwatch: Colors.blue,
    iconTheme: IconThemeData(color: Colors.grey, size: 32),
    primaryIconTheme: IconThemeData(color: Colors.grey, size: 32)
  ),
</code>```

This lines only changes the color of the icons, but the size does not change.

I do not need to change the behavior that Flutter handles this button, only the size of them.

答:
The AppBar widget uses a BackButton widget, so that change is not possible unless you modify it from the framework in a different branch, but the best approach is to use the Leading property and the condition ModalRoute.of(context)?.canPop to check whether the current route can be popped. For example:

AppBar(
      leading: ModalRoute.of(context)?.canPop == true
          ? IconButton(
              icon: Icon(
                Icons.arrow_back,
                size: 60,
              ),
            )
          : null,
      title: Text(
        "Example",
      ),
    )

Body:
I am trying to change the size of the icons ("Back" provided by Navigator and "Drawer" provided by Scaffold) in appbar in my ThemeData, modifying iconTheme and primaryIconTheme:

ThemeData(
    primarySwatch: Colors.blue,
    iconTheme: IconThemeData(color: Colors.grey, size: 32),
    primaryIconTheme: IconThemeData(color: Colors.grey, size: 32)
  ),

This lines only changes the color of the icons, but the size does not change.

I do not need to change the behavior that Flutter handles this button, only the size of them.


问:
Non-overloaded C++ Function That Can Print a vector and a vector of vectors?
Consider the following overloaded function that can print a 1d vector and a vector of vector of several types like strings, ints, doubles etc.

```<code>template<typename T>
void p(const vector<vector<T>>& vec) {
    int count = 0;
    for (vector<T> innerVec: vec) {
        cout << count++ << ": ";
        for (T e :innerVec) {
            cout << e << ' ';
        }
        cout << '\n';
    }
    cout << '\n';
}

template<typename T>
void p(const vector<T>& vec) {
    for (T e: vec) {
        cout << e << ' ';
    }
    cout << '\n';
}
</code>```

Is there anyway I can merge these two functions into 1? I tried using SFINAE and tag dispatching but all the solutions I could come up with need a macro or multiple functions and I don't want this.

I know the question might seem odd since my solution works, but I prefer having just one function in my code. This is because I want to implement a function that can detect if I am passing in a map, vector, vector of vectors, unordered_set, multimap, etc and just print that STL data structure and having one overloaded function for each specialization is a bit annoying as it gets large quick.

答:
I answered a similar question today. Check it out there: https://stackoverflow.com/a/60298735/8192043

Pasting the solution here:

This should work for your case. Note that I'm using a trait as implemented here in this amazing solution by @Jarod42 https://stackoverflow.com/a/29634934/8192043.

```<code>template<template<typename ...> typename C, typename D, typename ... Others>
void foo(const C<D, Others...> &object)
{
    if constexpr(is_iterable<D>::value)
    {
       for(const auto& v : object)
       {
           for (const auto& w : v)
           {...}
       }
    }
    else
    {
       for (const auto& w : object)
       {...}
    }
}
</code>```

Live Code

Body:
Consider the following overloaded function that can print a 1d vector and a vector of vector of several types like strings, ints, doubles etc.

template<typename T>
void p(const vector<vector<T>>& vec) {
    int count = 0;
    for (vector<T> innerVec: vec) {
        cout << count++ << ": ";
        for (T e :innerVec) {
            cout << e << ' ';
        }
        cout << '\n';
    }
    cout << '\n';
}

template<typename T>
void p(const vector<T>& vec) {
    for (T e: vec) {
        cout << e << ' ';
    }
    cout << '\n';
}

Is there anyway I can merge these two functions into 1? I tried using SFINAE and tag dispatching but all the solutions I could come up with need a macro or multiple functions and I don't want this.

I know the question might seem odd since my solution works, but I prefer having just one function in my code. This is because I want to implement a function that can detect if I am passing in a map, vector, vector of vectors, unordered_set, multimap, etc and just print that STL data structure and having one overloaded function for each specialization is a bit annoying as it gets large quick.

Body:
I answered a similar question today. Check it out there: https://stackoverflow.com/a/60298735/8192043

Pasting the solution here:

This should work for your case. Note that I'm using a trait as implemented here in this amazing solution by @Jarod42 https://stackoverflow.com/a/29634934/8192043.

template<template<typename ...> typename C, typename D, typename ... Others>
void foo(const C<D, Others...> &object)
{
    if constexpr(is_iterable<D>::value)
    {
       for(const auto& v : object)
       {
           for (const auto& w : v)
           {...}
       }
    }
    else
    {
       for (const auto& w : object)
       {...}
    }
}

Live Code


问:
Collapsing a 10 period curve to 4 periods
I have a 10 period cost curve table below.  How do I programmatically collapse/condense/shrink this to 4 periods.  I'm using VBA but I should be able to follow other languages.  The routine should work for whatever period you pass to it.  For example, if I pass it a 7 it should condense the percentages to 7 periods.  If I pass it 24 then expand the percentages to 24 periods, spreading the percentages based on the original curve.  Any help or example will be appreciated.  Thanks...

```
ORIGINAL
Period  Pct
1       10.60%
2       19.00%
3       18.30%
4       14.50%
5       10.70%
6        8.90%
7        6.50%
8        3.10%
9        3.00%
10       5.40%
```

```
COLLAPSED
Period  Pct
1       38.75%
2       34.35%
3       16.95%
4        9.95%
```

EDITED:  I've added sample code below as to what I have so far.  It only works for periods 1, 2, 3, 5, 9, 10.  Maybe someone can help modify it to work for any period.  Disclaimer, I'm not a programmer so my coding is bad.  Plus, I have no clue as to what I'm doing.

```
Sub Collapse_Periods()
    Dim aPct As Variant
    Dim aPer As Variant
    aPct = Array(0.106, 0.19, 0.183, 0.145, 0.107, 0.089, 0.065, 0.031, 0.03, 0.054)
    aPer = Array(1, 2, 3, 5, 9, 10)
    For i = 0 To UBound(aPer)
        pm = 10 / aPer(i)
        pct1 = 1
        p = 0
        ttl = 0
        For j = 1 To aPer(i)
            pct = 0
            k = 1
            Do While k <= pm
                pct = pct + aPct(p) * pct1
                pct1 = 1
                p = p + 1
                If k <> pm And k = Int(pm) Then
                    pct1 = (pm - Int(pm)) * j
                    pct = pct + (pct1 * aPct(p))
                    pct1 = 1 - pct1
                End If
                k = k + 1
            Loop
            Debug.Print aPer(i) & " : " & j & " : " & pct
            ttl = ttl + pct
        Next j
        Debug.Print "Total:  " & ttl
    Next i
End Sub
```

Body:
I have a 10 period cost curve table below.  How do I programmatically collapse/condense/shrink this to 4 periods.  I'm using VBA but I should be able to follow other languages.  The routine should work for whatever period you pass to it.  For example, if I pass it a 7 it should condense the percentages to 7 periods.  If I pass it 24 then expand the percentages to 24 periods, spreading the percentages based on the original curve.  Any help or example will be appreciated.  Thanks...

ORIGINAL
Period  Pct
1       10.60%
2       19.00%
3       18.30%
4       14.50%
5       10.70%
6        8.90%
7        6.50%
8        3.10%
9        3.00%
10       5.40%

COLLAPSED
Period  Pct
1       38.75%
2       34.35%
3       16.95%
4        9.95%

EDITED:  I've added sample code below as to what I have so far.  It only works for periods 1, 2, 3, 5, 9, 10.  Maybe someone can help modify it to work for any period.  Disclaimer, I'm not a programmer so my coding is bad.  Plus, I have no clue as to what I'm doing.

Sub Collapse_Periods()
    Dim aPct As Variant
    Dim aPer As Variant
    aPct = Array(0.106, 0.19, 0.183, 0.145, 0.107, 0.089, 0.065, 0.031, 0.03, 0.054)
    aPer = Array(1, 2, 3, 5, 9, 10)
    For i = 0 To UBound(aPer)
        pm = 10 / aPer(i)
        pct1 = 1
        p = 0
        ttl = 0
        For j = 1 To aPer(i)
            pct = 0
            k = 1
            Do While k <= pm
                pct = pct + aPct(p) * pct1
                pct1 = 1
                p = p + 1
                If k <> pm And k = Int(pm) Then
                    pct1 = (pm - Int(pm)) * j
                    pct = pct + (pct1 * aPct(p))
                    pct1 = 1 - pct1
                End If
                k = k + 1
            Loop
            Debug.Print aPer(i) & " : " & j & " : " & pct
            ttl = ttl + pct
        Next j
        Debug.Print "Total:  " & ttl
    Next i
End Sub


问:
What Angular files are safe to delete when sharing a project?
I would like to share an Angular project, it is mostly the basic application created by

```<code>ng new my-app
</code>```

but it is 340MB (100MB zipped).  Are there any temporary folders etc that can be safely deleted in Angular?

I tried googling this but cannot find anything related.

答:
If they will be building and running npm i then you can drop these folders

dist

dist-dev

node_modules

That should eliminate the bulk of the mg.

Body:
I would like to share an Angular project, it is mostly the basic application created by

ng new my-app

but it is 340MB (100MB zipped).  Are there any temporary folders etc that can be safely deleted in Angular?

I tried googling this but cannot find anything related.


问:
"cpio: premature end of archive" when using lsinitramfs
I am trying to unpack an initramfs image obtained from an embedded system, but I get errors like cpio: premature end of archive when using any utility for unpacking the file. I'll paste the file signature and some of the things I've tried down below:

```<code>$ file initramfs
initramfs: u-boot legacy uImage, OE and Crypt, Linux/ARM, RAMDisk Image (gzip), 6722916 bytes, Wed Jun 19 11:31:12 2019, Load Address: 0x00000000, Entry Point: 0x00000000, Header CRC: 0x9D0680ED, Data CRC: 0x2A1021B1
</code>```

```<code>$ lsinitramfs initramfs
cpio: premature end of archive
</code>```

```<code>$ zcat initramfs | cpio -idmv

gzip: initramfs: not in gzip format
cpio: premature end of archive
</code>```

```<code>$ xz -dc < initramfs | cpio -idmv
xz: (stdin): File format not recognized
cpio: premature end of archive
</code>```

Edit: I forgot to mention that I have tried all of these commands on ARM as well with the exact same results.

答:
As shown in this post you can unpack uImage files using the following command:

```<code>tail -c+65 < initramfs | gunzip > unpacked_initramfs
</code>```

The resultant unpacked_initramfs file should have a signature like this:

```<code>$ file unpacked_initramfs
unpacked_initramfs: ASCII cpio archive (SVR4 with no CRC)
</code>```

Then you can run whatever commands you need on that file (for example: lsinitramfs unpacked_initramfs).

Body:
I am trying to unpack an initramfs image obtained from an embedded system, but I get errors like cpio: premature end of archive when using any utility for unpacking the file. I'll paste the file signature and some of the things I've tried down below:

$ file initramfs
initramfs: u-boot legacy uImage, OE and Crypt, Linux/ARM, RAMDisk Image (gzip), 6722916 bytes, Wed Jun 19 11:31:12 2019, Load Address: 0x00000000, Entry Point: 0x00000000, Header CRC: 0x9D0680ED, Data CRC: 0x2A1021B1

$ lsinitramfs initramfs
cpio: premature end of archive

$ zcat initramfs | cpio -idmv

gzip: initramfs: not in gzip format
cpio: premature end of archive

$ xz -dc < initramfs | cpio -idmv
xz: (stdin): File format not recognized
cpio: premature end of archive

Edit: I forgot to mention that I have tried all of these commands on ARM as well with the exact same results.

Body:
As shown in this post you can unpack uImage files using the following command:

tail -c+65 < initramfs | gunzip > unpacked_initramfs

The resultant unpacked_initramfs file should have a signature like this:

$ file unpacked_initramfs
unpacked_initramfs: ASCII cpio archive (SVR4 with no CRC)

Then you can run whatever commands you need on that file (for example: lsinitramfs unpacked_initramfs).


问:
For security compliance ,create Azure policy for key vault where access should be granted to AD groups only, not Individual users
Create Azure policy for key vault where access should be granted to AD groups, MSIs and SPNs. Individual users must not have access. Reader role should be assigned to protect key access. What will be the content of policyRule block?</p>

答: Policy is not user-aware so this will not be possible. This would have to be solved using RBAC. </p>


问:
Opencart product sku on order maill?
I need to have SKU on order confirmation in the email the user receive "OC 3.0.3.2".
I've tried to implement this solution that found in other site but it only display a blank space.

In catalog/controller/mail/order.php file

Find each $this->load->model('tool/upload');

Add below $this->load->model('catalog/product');

Find each $data['products'][] = array(

Add above $product_info = $this->model_catalog_product->getProduct($order_product['product_id']);

Find each 'model'    => $order_product['model'],

Add below 'sku'     => $product_info['sku'],

Then, in catalog/view/theme/default/template/mail/order_add.twig file

Find {{ product.model }}

Add below {{ product.sku }}

How can I solve this issue as soon as possible?

答:
In catalog/view/theme/default/template/mail/order_add.twig file

Find:

```<code><td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; background-color: #EFEFEF; font-weight: bold; text-align: left; padding: 7px; color: #222222;">{{ text_model }}</td>
</code>```

Add Below:

```<code><td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; background-color: #EFEFEF; font-weight: bold; text-align: left; padding: 7px; color: #222222;">{{ text_sku }}</td>
</code>```

Find:

```<code><td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: left; padding: 7px;">{{ product.model }}</td>
</code>```

Add Below:

```<code><td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: left; padding: 7px;">{{ product.sku }}</td>
</code>```

Find:

```<code><td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: right; padding: 7px;" colspan="4"><b>{{ total.title }}:</b></td>
</code>```

Change to:

```<code><td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: right; padding: 7px;" colspan="5"><b>{{ total.title }}:</b></td>
</code>```

If your controller file is correct you should get your desired result.

Title: Opencart product sku on order maill?

Body:
In catalog/view/theme/default/template/mail/order_add.twig file

Find:

<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; background-color: #EFEFEF; font-weight: bold; text-align: left; padding: 7px; color: #222222;">{{ text_model }}</td>

Add Below:

<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; background-color: #EFEFEF; font-weight: bold; text-align: left; padding: 7px; color: #222222;">{{ text_sku }}</td>

Find:

<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: left; padding: 7px;">{{ product.model }}</td>

Add Below:

<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: left; padding: 7px;">{{ product.sku }}</td>

Find:

<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: right; padding: 7px;" colspan="4"><b>{{ total.title }}:</b></td>

Change to:

<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: right; padding: 7px;" colspan="5"><b>{{ total.title }}:</b></td>

If your controller file is correct you should get your desired result.