答:
The <colgroup> element can only apply the following style properties (see spec) to the  elements:

border

background

width

visibility

In this case, you can use the :first-child pseudo-selector to limit the overflow of the first  element of each row.

.mytable {
  table-layout: fixed;
  width: 1000px;
}

th,
td {
  padding: 5px;
}

.ten {
  width: 100px;
}

td:first-child {
  word-wrap: break-word;
}

.others {
  font-size: 13px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border=1 class="mytable">

  <colgroup>
    <col class="ten" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
  </colgroup>

  <thead>
    <tr>
      <th>VERY LONG COLUMN</th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
      <th>H</th>
      <th>I</th>
      <th>J</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
  </tbody>
</table></code>```

Title: overflow:hidden not working in colgroups for very long cells

Body:
I have searched for quite a bit in stackoverflow and google. But failed to find a solution.
I have a 11 column table, of which the first column can get long text (without spaces). I have adapted to colgroup approach but it is not working for me.

.mytable {
  table-layout: fixed;
  width: 1000px;
}

th,
td {
  padding: 5px;
}

.ten {
  width: 100px;
  overflow: hidden;
}

.others {
  font-size: 13px;
}

  <colgroup>
    <col class="ten" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
  </colgroup>

      VERY LONG COLUMN
      A
      B
      C
      D
      E
      F
      G
      H
      I
      J

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

      looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
      not so long
      small
      small
      small
      small
      small
      small
      small
      small
      small

I need to have a fixed width table. And I am looking for a solution where i can wrap the text. I tried with word-wrap: break-word; but it gives me the exact output.
Any help is much appreciated.

Solutions I have tried:

Word-wrap in an HTML table

how-do-i-wrap-text-with-no-whitespace-inside-a-td

Body:
The <colgroup> element can only apply the following style properties (see spec) to the <td> elements:

border

background

width

visibility

In this case, you can use the :first-child pseudo-selector to limit the overflow of the first <td> element of each row.

.mytable {
  table-layout: fixed;
  width: 1000px;
}

th,
td {
  padding: 5px;
}

.ten {
  width: 100px;
}

td:first-child {
  word-wrap: break-word;
}

.others {
  font-size: 13px;
}

<table border=1 class="mytable">

  <colgroup>
    <col class="ten" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
    <col class="others" />
  </colgroup>

  <thead>
    <tr>
      <th>VERY LONG COLUMN</th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
      <th>H</th>
      <th>I</th>
      <th>J</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
    <tr>
      <td>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong</td>
      <td>not so long</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
      <td>small</td>
    </tr>
  </tbody>
</table>


来源: stackexchange

问:
How to delete all data from core data when persistentContainer is not in App delegate method in swift
I am new in Swift and I want to delete all data from core data. I have seen several examples but in all of them persistentContainer is in AppDelegate and in my case persistentContainer is not in AppDelegate. It is in a different class as shown below:

```<code>class CoreDataStack: NSObject {

    static let sharedInstance = CoreDataStack()
    private override init() {}

    func applicationDocumentsDirectory() {
        if let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last {
            print(url.absoluteString)
        }
    }
    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "Database")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {

                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
            print(storeDescription)

        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {

                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}
</code>```

In the AppDelegate method I am just calling it as

```<code>CoreDataStack.sharedInstance.applicationDocumentsDirectory()

func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        CoreDataStack.sharedInstance.saveContext()
    }
</code>```

I tried this code but it does not work for me.

答:
One of the solutions can be to use NSBatchDeleteRequest for all entities in the persistentContainer. You can add these methods to your CoreDataStack:

```<code>func deleteAllEntities() {
    let entities = persistentContainer.managedObjectModel.entities
    for entity in entities {
        delete(entityName: entity.name!)
    }
}

func delete(entityName: String) {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        debugPrint(error)
    }
}
</code>```

The whole code can be found here

ContentLicense: CC BY-SA 4.0

Body:
I am new in Swift and I want to delete all data from core data. I have seen several examples but in all of them persistentContainer is in AppDelegate and in my case persistentContainer is not in AppDelegate. It is in a different class as shown below:

class CoreDataStack: NSObject {

    static let sharedInstance = CoreDataStack()
    private override init() {}

    func applicationDocumentsDirectory() {
        if let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last {
            print(url.absoluteString)
        }
    }
    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "Database")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {

                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
            print(storeDescription)

        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {

                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

In the AppDelegate method I am just calling it as

CoreDataStack.sharedInstance.applicationDocumentsDirectory()

func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        CoreDataStack.sharedInstance.saveContext()
    }

I tried this code but it does not work for me.

Body:
One of the solutions can be to use NSBatchDeleteRequest for all entities in the persistentContainer. You can add these methods to your CoreDataStack:

func deleteAllEntities() {
    let entities = persistentContainer.managedObjectModel.entities
    for entity in entities {
        delete(entityName: entity.name!)
    }
}

func delete(entityName: String) {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        debugPrint(error)
    }
}

The whole code can be found here


问:
Self XSS vs Reflected XSS
What is the difference between self XSS and reflected XSS?
If I find a XSS vulnerability, how do I know whether it is self XSS or reflected XSS ?
I have tried reading a lot of articles on Google but am still confused.
Thanks in advance!</p>

答:
Reflected XSS occurs when user input included in the url address is reflected in the page source un-unescape .

Now, a lot of things can be user input such as your input in search form , the url adress itself . an example is

https://vulnerable.com/

lets say after visiting the url and you check the page source in your browser and you see  somewhere in the page source . This is a reflected xss and can be used to exploit other users since anyone who visited that link will have the xss fired and their cookies stolen if lacking the httponly flag

Self XSS
self Xss is an xss that executes in the context of the user who submits the payload . Say web app has profile function and in the profile function you have an option to specify a nickname . now in this web app you cant view other user profiles , meaning thier is no way to make another user view your profile . Most bank apps are like this. Now, if the nick name parameter is vulnerable to xss , The xss here would be self xss because only you can view your user profile and the xss will only execute in your own context . You can agree that stealing your own cookies isnt of any impact

Title: Self XSS vs Reflected XSS

Body:
Reflected XSS occurs when user input included in the url address is reflected in the page source un-unescape .

Now, a lot of things can be user input such as your input in search form , the url adress itself . an example is

https://vulnerable.com/<script>alert(1)</script>

lets say after visiting the url and you check the page source in your browser and you see <script>alert(1)</script> somewhere in the page source . This is a reflected xss and can be used to exploit other users since anyone who visited that link will have the xss fired and their cookies stolen if lacking the httponly flag

Self XSS
self Xss is an xss that executes in the context of the user who submits the payload . Say web app has profile function and in the profile function you have an option to specify a nickname . now in this web app you cant view other user profiles , meaning thier is no way to make another user view your profile . Most bank apps are like this. Now, if the nick name parameter is vulnerable to xss , The xss here would be self xss because only you can view your user profile and the xss will only execute in your own context . You can agree that stealing your own cookies isnt of any impact


问:
Angular animation is blocked after login popup
I created an animation which fired after the social login is failed. It's working in chrome but not in safari. There after the animation works in safari, too. I don't have any idea, why.

See the following video, what I mean:
https://drive.google.com/file/d/1VdaNDjPnh4F2wULHy3CQZ5nvqZcQU33m/view?usp=sharing

I reload the page

Click the facebook login button

Show the login popup and thereafter it doesn't happened anything

Click again the facebook login button and the animation works

In chrome the animation works at first time too. So this bug be only safari.

This is my animation definition:

```<code>animations: [
    trigger('showConditions', [
      state('show', style({ left: '0' })),
      state('hide', style({ left: '100%' })),
      transition('show <=> hide', [
        animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)')
      ]),
    ]),
    trigger('showSignin', [
      state('show', style({ left: '0' })),
      state('hide', style({ left: '-100%' })),
      transition('show <=> hide', [
        animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)')
      ]),
    ])
  ],
</code>```

And the animation fired when the showConditions parameter change:

```<code>ngOnInit() {
    this.authSubscription = this.store.select('auth').subscribe((state: any) => {
      if (!!state.error) {
        this.error = state.error;
      }
      if (state.login.showConditions) {
        this.showConditions = state.login.showConditions;
        this.accessToken = state.provider.accessToken;
        this.provider = state.provider.type;
      }
      console.log(this.showConditions);
    });
  }
</code>```

And I use this animation the following:

```<code><div class="carousel-item active" [@showSignin]="!showConditions ? 'show' : 'hide'">...</div>
</code>```

Thanks your help!
Tamas

答:
I found a solution for this problem. It was needed to use ngZone. So, I call a dispatch function in case of success fb login. If I put this function into the ngZone.run() function, then it works fine. My solution looks like the following:

```<code>this.ngZone.run(() => {
                this.store.dispatch(AuthActions.signInWithProviderStart({ accessToken, provider: 'facebook' }));
            });
</code>```

I've created an instance for NgZone before.

More info for NgZone here: https://angular.io/api/core/NgZone

Body:
I created an animation which fired after the social login is failed. It's working in chrome but not in safari. There after the animation works in safari, too. I don't have any idea, why.

See the following video, what I mean:
https://drive.google.com/file/d/1VdaNDjPnh4F2wULHy3CQZ5nvqZcQU33m/view?usp=sharing

I reload the page

Click the facebook login button

Show the login popup and thereafter it doesn't happened anything

Click again the facebook login button and the animation works

In chrome the animation works at first time too. So this bug be only safari.

This is my animation definition:

animations: [
    trigger('showConditions', [
      state('show', style({ left: '0' })),
      state('hide', style({ left: '100%' })),
      transition('show <=> hide', [
        animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)')
      ]),
    ]),
    trigger('showSignin', [
      state('show', style({ left: '0' })),
      state('hide', style({ left: '-100%' })),
      transition('show <=> hide', [
        animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)')
      ]),
    ])
  ],

And the animation fired when the showConditions parameter change:

ngOnInit() {
    this.authSubscription = this.store.select('auth').subscribe((state: any) => {
      if (!!state.error) {
        this.error = state.error;
      }
      if (state.login.showConditions) {
        this.showConditions = state.login.showConditions;
        this.accessToken = state.provider.accessToken;
        this.provider = state.provider.type;
      }
      console.log(this.showConditions);
    });
  }

And I use this animation the following:

...

Thanks your help!
Tamas

Body:
I found a solution for this problem. It was needed to use ngZone. So, I call a dispatch function in case of success fb login. If I put this function into the ngZone.run() function, then it works fine. My solution looks like the following:

this.ngZone.run(() => {
                this.store.dispatch(AuthActions.signInWithProviderStart({ accessToken, provider: 'facebook' }));
            });

I've created an instance for NgZone before.

More info for NgZone here: https://angular.io/api/core/NgZone


问:
how can i remove this ..plz tell me because i tried everyting .is there any probelm in this code
this is the code I currently have

```<code>create or replace procedure airline(flight_no      in airline_details.flight_no%type,
                                    airline        in airline_details.airline%type,
                                    source         in airline_details.source%type,
                                    destination    in airline_details.destination%type,
                                    departure_time in airline_details.depart_time%type,
                                    arrival_time   in airline_details.arrive_time%type,
                                    ticket_class   in airline_details.ticket_class%type,
                                    ticket_fare    in airline_details.ticket_fare%type)
                                   is
begin
    insert into airline_details
    values
      (flight_no,
       airline,
       source,
       destination,
       depart_time,
       arrive_time,
       ticket_class,
       ticket_fare);
end;
/
</code>```

and calling as

```<code>begin
  airline('PK-710', 'PIA', 'ISB', 'KHI', '10:00 AM', '12:00 AM', 'Economy', 85000);
end;
/
</code>```

```<code>ERROR at line 2:
ORA-06550: line 2, column 1:
PLS-00905: object SCOTT.AIRLINE is invalid
ORA-06550: line 2, column 1:
PL/SQL: Statement ignored
</code>```

答:
As Barbaros Özhan mentioned in your comment, there are mismatches in your formal argument names and the arguments you are passing in the Insert statement.
departure_time arrival_time

Here is the corrected code

```<code>CREATE OR REPLACE PROCEDURE airline(
    flight_no        IN   airline_details.flight_no%TYPE,
    airline          IN   airline_details.airline%TYPE,
    source           IN   airline_details.source%TYPE,
    destination      IN   airline_details.destination%TYPE,
    departure_time   IN   airline_details.depart_time%TYPE,
    arrival_time     IN   airline_details.arrive_time%TYPE,
    ticket_class     IN   airline_details.ticket_class%TYPE,
    ticket_fare      IN   airline_details.ticket_fare%TYPE
)IS
BEGIN
    INSERT INTO airline_details VALUES(
        flight_no,
        airline,
        source,
        destination,
        departure_time,
        arrival_time,
        ticket_class,
        ticket_fare
    );

END;
/
</code>```

Make sure the table airline_details is present is the current schema or you are using the schema name before the table name, for example, schema_in_which_table_is_present.tablename.

And for this error

```<code>begin
  airline('PK-710', 'PIA', 'ISB', 'KHI', '10:00 AM', '12:00 AM', 'Economy', 85000);
end;
/
</code>```

Try recompiling procedure with corrections.

Body:
this is the code I currently have

create or replace procedure airline(flight_no      in airline_details.flight_no%type,
                                    airline        in airline_details.airline%type,
                                    source         in airline_details.source%type,
                                    destination    in airline_details.destination%type,
                                    departure_time in airline_details.depart_time%type,
                                    arrival_time   in airline_details.arrive_time%type,
                                    ticket_class   in airline_details.ticket_class%type,
                                    ticket_fare    in airline_details.ticket_fare%type)
                                   is
begin
    insert into airline_details
    values
      (flight_no,
       airline,
       source,
       destination,
       depart_time,
       arrive_time,
       ticket_class,
       ticket_fare);
end;
/

and calling as

begin
  airline('PK-710', 'PIA', 'ISB', 'KHI', '10:00 AM', '12:00 AM', 'Economy', 85000);
end;
/

ERROR at line 2:
ORA-06550: line 2, column 1:
PLS-00905: object SCOTT.AIRLINE is invalid
ORA-06550: line 2, column 1:
PL/SQL: Statement ignored

Body:
As Barbaros Özhan mentioned in your comment, there are mismatches in your formal argument names and the arguments you are passing in the Insert statement.
departure_time arrival_time

Here is the corrected code

CREATE OR REPLACE PROCEDURE airline(
    flight_no        IN   airline_details.flight_no%TYPE,
    airline          IN   airline_details.airline%TYPE,
    source           IN   airline_details.source%TYPE,
    destination      IN   airline_details.destination%TYPE,
    departure_time   IN   airline_details.depart_time%TYPE,
    arrival_time     IN   airline_details.arrive_time%TYPE,
    ticket_class     IN   airline_details.ticket_class%TYPE,
    ticket_fare      IN   airline_details.ticket_fare%TYPE
)IS
BEGIN
    INSERT INTO airline_details VALUES(
        flight_no,
        airline,
        source,
        destination,
        departure_time,
        arrival_time,
        ticket_class,
        ticket_fare
    );

END;
/

Make sure the table airline_details is present is the current schema or you are using the schema name before the table name, for example, schema_in_which_table_is_present.tablename.

And for this error

begin
  airline('PK-710', 'PIA', 'ISB', 'KHI', '10:00 AM', '12:00 AM', 'Economy', 85000);
end;
/

Try recompiling procedure with corrections.


问:
Same results are getting updated in all rows by using where clause in SQL Server
I'm running a stored procedure inside a foreach loop in c#. After completion, all the rows of a column are getting updated with the top most value. Below is the stored procedure:

```<code>ALTER PROCEDURE [dbo].[getservername8]
    @number varchar(255)
AS
    DECLARE @server_name varchar(500)

    SELECT @server_name = short_description
    FROM [Event_alerts].[dbo].[event_alerts]

    DECLARE @s AS varchar(50)

    SELECT @s = SUBSTRING(@server_name, CHARINDEX('-', @server_name) + 15, 50)

    UPDATE event_alerts
    SET server_name = @s
    WHERE number = @number
</code>```

This is the C# code:

```<code>using (SqlCommand command2 = new SqlCommand("getservername8", conn))
{
    command2.CommandType = CommandType.StoredProcedure;

    command2.Parameters.AddWithValue("@number",number);
    command2.Parameters["@number"].Direction = ParameterDirection.Input;

    command2.ExecuteNonQuery();
}
</code>```

Any help would be much appreciated

答:
Your code has a valid where clause, so it should only be updating the matching rows.  I can only speculate that all rows have the same value for number.

However, you seem to have an error in the definition of @server_name -- and that might be the problem you are referring to.  There is no where clause so it is set to an arbitrary value -- possibly from what you would call "the last row".  Although that nomenclature is a misinterpretation of what happens.

Your SP is too complex anyway.  I suspect that you intend:

```<code>alter procedure [dbo].[getservername8] (
    @number varchar(255)
) as
begin
    update ea
        set server_name = substring(short_description, charindex('-', short_description) + 15, 50)
        from event_alerts ea
        where number = @number;
end;  -- getservername8
</code>```

Also note the good programming practices:

The statements end in a semicolon.

The body of the SP uses begin/end.

The end is tagged with the name of the SP.

Body:
I'm running a stored procedure inside a foreach loop in c#. After completion, all the rows of a column are getting updated with the top most value. Below is the stored procedure:

ALTER PROCEDURE [dbo].[getservername8]
    @number varchar(255)
AS
    DECLARE @server_name varchar(500)

    SELECT @server_name = short_description
    FROM [Event_alerts].[dbo].[event_alerts]

    DECLARE @s AS varchar(50)

    SELECT @s = SUBSTRING(@server_name, CHARINDEX('-', @server_name) + 15, 50)

    UPDATE event_alerts
    SET server_name = @s
    WHERE number = @number

This is the C# code:

using (SqlCommand command2 = new SqlCommand("getservername8", conn))
{
    command2.CommandType = CommandType.StoredProcedure;

    command2.Parameters.AddWithValue("@number",number);
    command2.Parameters["@number"].Direction = ParameterDirection.Input;

    command2.ExecuteNonQuery();
}

Any help would be much appreciated

Body:
Your code has a valid where clause, so it should only be updating the matching rows.  I can only speculate that all rows have the same value for number.

However, you seem to have an error in the definition of @server_name -- and that might be the problem you are referring to.  There is no where clause so it is set to an arbitrary value -- possibly from what you would call "the last row".  Although that nomenclature is a misinterpretation of what happens.

Your SP is too complex anyway.  I suspect that you intend:

alter procedure [dbo].[getservername8] (
    @number varchar(255)
) as
begin
    update ea
        set server_name = substring(short_description, charindex('-', short_description) + 15, 50)
        from event_alerts ea
        where number = @number;
end;  -- getservername8

Also note the good programming practices:

The statements end in a semicolon.

The body of the SP uses begin/end.

The end is tagged with the name of the SP.


问:
How to open specific web browsers using hyperlinks?
I have a simple app which contains a link, I want on mobile apps eg LinkedIn  people to click this link and open it in a browser eg safari

I tried this

```<code><a href="safari-https://meed.audiencevideo.com">May open on Safari</a>'
</code>```

When I click this link it opens in a native LinkedIn app browser in iPhone

what do I need to change to get this working?

答:
you can configure the edge browser such way- but i couldnt found any solution for other browsers</p>

```<code><a href="microsoft-edge:https://meed.audiencevideo.com">May open on edge</a>'
</code>```

Body:
I have a simple app which contains a link, I want on mobile apps eg LinkedIn  people to click this link and open it in a browser eg safari

I tried this

May open on Safari'

When I click this link it opens in a native LinkedIn app browser in iPhone

what do I need to change to get this working?

Body:
you can configure the edge browser such way- but i couldnt found any solution for other browsers

<a href="microsoft-edge:https://meed.audiencevideo.com">May open on edge</a>'


问:
error in xpstar90.dll at the time of database creation?
I'm facing the problem when i am creating database in SQL server management studio 2008. it is showing error that xpstar90.dll DLL find could not load (response 126).</p>

答: Another reason I found for this is that the user does not have access to one of the directories containing xpstar90.dll.  In my case, when the admin added management studio to my PC, she did not enable read access to C:\program files\Microsoft Sql Server\MSSQL.1.  That being the case, it generated the error that it could not find xpstar90.dll even though it was on the machine.</p>

ContentLicense: CC BY-SA 3.0


问:
iterator.cycle function called twice return the same iterator (with same memory adress)
On python 3.7, I expect to get a new memory address (and cycle) each time I call iterator.cycle, however, this piece of code duplicates 2 iterators on 4:

```<code>from itertools import cycle

cycles = [[None] * 2] * 2
s = set()
for i in range(2):
    for j in range(2):
        c =  cycle("ab")
        cycles[i][j] =c
        s.add(hex(id(c)))
        print(hex(id(c)))

print(len(s))
</code>```

It prints:

```<code>0x7efe576cc370
0x7efe576cc3c0
0x7efe576cc410
0x7efe576cc370
3
</code>```

So object 0x7efe576cc370 is used twice. On the other hand, this code works:

```<code>from itertools import cycle

cycles = []

for _ in range(1000):
    c = cycle("ab")
    cycles.append(c)

s = set([hex(id(c)) for c in cycles])
print(len(s)) # 1000
</code>```

答:
The issue here is the way that you are constructing the cycles object.

When you use the * operator on a list, the new list that is returned contains multiple references to the original list, not copies of the original list.

As a result, cycles is a two item list, where both elements point to the same list, and thus changes made to cycles[1][0] also apply to  cycles[0][0]

When you assign to cycles[1][0], you also overwrite the item at cycles[0][0], which deletes the previous item.

As to why this means s has a length of 3, this is due to the way the object allocator / garbage collector interact.

For anything but the innermost list, you should use a list comprehension to construct the object.

```<code> cycles = [[None] * 2 for _ in range(2)]
</code>```

This will produce a list that is suitably constructed, and you code will work fine

Body:
On python 3.7, I expect to get a new memory address (and cycle) each time I call iterator.cycle, however, this piece of code duplicates 2 iterators on 4:

from itertools import cycle

cycles = [[None] * 2] * 2
s = set()
for i in range(2):
    for j in range(2):
        c =  cycle("ab")
        cycles[i][j] =c
        s.add(hex(id(c)))
        print(hex(id(c)))

print(len(s))

It prints:

0x7efe576cc370
0x7efe576cc3c0
0x7efe576cc410
0x7efe576cc370
3

So object 0x7efe576cc370 is used twice. On the other hand, this code works:

from itertools import cycle

cycles = []

for _ in range(1000):
    c = cycle("ab")
    cycles.append(c)

s = set([hex(id(c)) for c in cycles])
print(len(s)) # 1000

Body:
The issue here is the way that you are constructing the cycles object.

When you use the * operator on a list, the new list that is returned contains multiple references to the original list, not copies of the original list.

As a result, cycles is a two item list, where both elements point to the same list, and thus changes made to cycles[1][0] also apply to  cycles[0][0]

When you assign to cycles[1][0], you also overwrite the item at cycles[0][0], which deletes the previous item.

As to why this means s has a length of 3, this is due to the way the object allocator / garbage collector interact.

For anything but the innermost list, you should use a list comprehension to construct the object.

 cycles = [[None] * 2 for _ in range(2)]

This will produce a list that is suitably constructed, and you code will work fine


问:
How to change horizontal scroll bar width in Material Table?
Is it possible to change the thickness of the horizontal scroll bar of Material-Table? I've tried adding the scrollBarWidth property and the scrollPadding property to the style prop in the table component, but it didn't work. Is it possible to change the width at all?

答:
You can modify it, via inspect elements, and find the specific class

Example

by putting css in your material table class in elements; you'll see it early the result without reloading the pages .

and if you put it to the code use :host ::ng-deep to reflect your changes.

Example

```<code>:host ::ng-deep .mat-menu-panel {
    min-width: 112px;
    max-width: 400px;
    overflow: auto;
 }
</code>```

Body:
You can modify it, via inspect elements, and find the specific class

Example

by putting css in your material table class in elements; you'll see it early the result without reloading the pages .

and if you put it to the code use :host ::ng-deep to reflect your changes.

Example

:host ::ng-deep .mat-menu-panel {
    min-width: 112px;
    max-width: 400px;
    overflow: auto;
 }


问:
Grouped and reversed bar plot in base R when the length of variables are not equal
I'm trying to make a bar plot in base R, so not with ggplot, that is grouped and reversed, and I found a lot of similar questions and answers but it seems none of them works for me.
My database is about Eurovision song contest 2007, this is the link towards it: https://www.kaggle.com/datagraver/eurovision-song-contest-scores-19752019

and this is the code for cleaning and getting the database I'm working with:

```<code>cela_baza <- read.csv("eurovision_song_contest_1975_2019.csv", stringsAsFactors = FALSE)

evro2007_pocetna<-cela_baza[cela_baza$Year=='2007',]

evro2007_aggr<-aggregate(evro2007_pocetna$Points~evro2007_pocetna$From.country+
                         evro2007_pocetna$To.country,FUN=mean)

colnames(evro2007_aggr) <- c('From country', 'To country','Points')

evro2007<-evro2007_aggr[!(evro2007_aggr$`From country`==evro2007_aggr$`To country`),]

nrow(subset(evro2007, evro2007$Points== 0 ))

evro2007_zero<- subset(evro2007, evro2007$Points> 0 )
</code>```

What I need is a bar plot with number of points on x-axis and countries that participated in competition on y-axis, each country has three grouped bars of different color: first represents how many points that country gave to Serbia (winner), second points to Ukraine (2nd place) and third points to Russia (3rd place). So it is grouped and reversed, and I found code for that, but my problem is that not all of the participating countries gave points to these three countries I need so always occurs some errors.

Code for ggplot will work too, I can't install it on my old PC, but I will ask someone to do it for me, as long as I have the code, thanks for all the help in advance!

答:
It's possible to do what you're describing, but the resulting plot is horrible because of the number of countries on the x axis (42, with three bars each), and the limitations of base R's barplot.

Here's how we can get the data in the correct format:

winners <- evro2007[evro2007$`To country` == "Ukraine" |
           evro2007$`To country` == "Russia" |
           evro2007$`To country` == "Serbia",]
self <- data.frame(`From country` = c("Serbia", "Ukraine", "Russia"),
                   `To country` = c("Serbia", "Ukraine", "Russia"),
                   Points = c(0, 0, 0), stringsAsFactors = FALSE)
names(self) <- names(winners)
winners <- rbind(winners, self)
winners <- winners[order(winners$`From country`, winners$`To country`),]
```

<p>However, the base R barplot looks like this:</p>

```barplot(Points ~ `To country` + `From country`,
        data = winners, beside = TRUE, cex.names = 0.3)
```

<p><img src="https://i.stack.imgur.com/MSpOh.png" alt="enter image description here"></p>

<p>The countries are illegible, and the plot difficult to interpret.</p>

<p>Whereas, using <code>ggplot</code>:</p>

```winners$`To country` <- factor(winners$`To country`,
                               levels = c("Serbia", "Ukraine", "Russia"))

ggplot(winners, aes(`To country`, Points, fill = `To country`)) +
  geom_col() +
  facet_wrap(.~`From country`) +
  theme(axis.text.x = element_blank())
```

We get this:

Body:
I'm trying to make a bar plot in base R, so not with ggplot, that is grouped and reversed, and I found a lot of similar questions and answers but it seems none of them works for me.
My database is about Eurovision song contest 2007, this is the link towards it: https://www.kaggle.com/datagraver/eurovision-song-contest-scores-19752019

and this is the code for cleaning and getting the database I'm working with:

cela_baza <- read.csv("eurovision_song_contest_1975_2019.csv", stringsAsFactors = FALSE)

evro2007_pocetna<-cela_baza[cela_baza$Year=='2007',]

evro2007_aggr<-aggregate(evro2007_pocetna$Points~evro2007_pocetna$From.country+
                         evro2007_pocetna$To.country,FUN=mean)

colnames(evro2007_aggr) <- c('From country', 'To country','Points')

evro2007<-evro2007_aggr[!(evro2007_aggr$`From country`==evro2007_aggr$`To country`),]

nrow(subset(evro2007, evro2007$Points== 0 ))

evro2007_zero<- subset(evro2007, evro2007$Points> 0 )

What I need is a bar plot with number of points on x-axis and countries that participated in competition on y-axis, each country has three grouped bars of different color: first represents how many points that country gave to Serbia (winner), second points to Ukraine (2nd place) and third points to Russia (3rd place). So it is grouped and reversed, and I found code for that, but my problem is that not all of the participating countries gave points to these three countries I need so always occurs some errors.

Code for ggplot will work too, I can't install it on my old PC, but I will ask someone to do it for me, as long as I have the code, thanks for all the help in advance!

Body:
It's possible to do what you're describing, but the resulting plot is horrible because of the number of countries on the x axis (42, with three bars each), and the limitations of base R's barplot.

Here's how we can get the data in the correct format:

winners <- evro2007[evro2007$`To country` == "Ukraine" |
           evro2007$`To country` == "Russia" |
           evro2007$`To country` == "Serbia",]
self <- data.frame(`From country` = c("Serbia", "Ukraine", "Russia"),
                   `To country` = c("Serbia", "Ukraine", "Russia"),
                   Points = c(0, 0, 0), stringsAsFactors = FALSE)
names(self) <- names(winners)
winners <- rbind(winners, self)
winners <- winners[order(winners$`From country`, winners$`To country`),]

However, the base R barplot looks like this:

barplot(Points ~ `To country` + `From country`,
        data = winners, beside = TRUE, cex.names = 0.3)

The countries are illegible, and the plot difficult to interpret.

Whereas, using ggplot:

winners$`To country` <- factor(winners$`To country`,
                               levels = c("Serbia", "Ukraine", "Russia"))

ggplot(winners, aes(`To country`, Points, fill = `To country`)) +
  geom_col() +
  facet_wrap(.~`From country`) +
  theme(axis.text.x = element_blank())

We get this:


问:
how to use monaco editor without node.js
I need to integrate monaco-editor on a web page with a pure client-side solution, and without node.js.

I found an nice answer by @SimperT How to implement monaco-editor on a webpage without nodejs and electron but his repository is outdated (js is a wild world), and I had an extra constraint that files can only be served locally (no cdn, its for an intranet, without external access).

So, this is a bit a message in a bottle, but if someone has clues or directions on how to do it, I'm all ear... (If I come up with a solution, I'll post it here)

答:
The question was a bit clunky. Nonetheless, may my errors benefit to others: the issue was in the require variable which was not properly set.

With the package found here : https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.23.0.tgz

Unzipped and properly served statically. Path is monaco-editor-x.xx.x/package/min/vs/[editor/].

Here is the html page served (with cherrypy) :

<!doctype html>

        <meta charset="utf-8">
        <title>monaco editor</title>

        <link rel="stylesheet" data-name="vs/editor/editor.main" href="_static/js/ext/monaco-editor/min/vs/editor/editor.main.css">

monaco editor

```

Body:
The question was a bit clunky. Nonetheless, may my errors benefit to others: the issue was in the require variable which was not properly set.

With the package found here : https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.23.0.tgz

Unzipped and properly served statically. Path is monaco-editor-x.xx.x/package/min/vs/[editor/].

Here is the html page served (with cherrypy) :

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>monaco editor</title>

        <!-- MONACO CSS -->
        <link rel="stylesheet" data-name="vs/editor/editor.main" href="_static/js/ext/monaco-editor/min/vs/editor/editor.main.css">
    </head>

    <body style="background-color: rgb(140, 190, 190);">
        <h1>monaco editor</h1>
        <div id="monaco_editor" style="height:400px">
        </div>

        <!-- MONACO JS -->
        <script>var require = { paths: { 'vs': '_static/js/ext/monaco-editor/min/vs' } };</script>

        <script src="_static/js/ext/monaco-editor/min/vs/loader.js"></script>
        <script src="_static/js/ext/monaco-editor/min/vs/editor/editor.main.nls.js"></script>
        <script src="_static/js/ext/monaco-editor/min/vs/editor/editor.main.js"></script>

        <script>
        // CREATE AN EDITOR
        var h_div = document.getElementById('monaco_editor');
        var editor = monaco.editor.create(h_div, {
            value: [
                'function x() {',
                '\tconsole.log("Hello world!");',
                '}'
            ].join('\n'),
            language: 'javascript'
        });
        </script>
    </body>
</html>


问:
How to write to a Variable in script component
I want to write a value to a variable in package using script component using C#.

presently i am using these code:

```<code>public class ScriptMain : UserComponent
{
string s, r, m;
public override void PreExecute()
{
    base.PreExecute();

}

public override void PostExecute()
{
    base.PostExecute();

    Variables.SNumber = s;
    Variables.RNumber = r;
    Variables.MNumber = m;
   }

public override void Input0_ProcessInputRow(Input0Buffer Row)
{

    if (Row.Col1.Equals("MyName"))
    {

       s = Row.Column4.Substring(122, 5).Trim();
       r  = Row.Column8.Substring(5, 14).Trim();
       m = Row.Column8.Substring(66, 4).Trim() + "." + Row.Column8.Substring(70,
              2).Trim();
   }

}

}
</code>```

SNumber,Mnumber and RNumber are my global variables in the packages.After the script component iam using derived column to assign the values.
But the variables has no value.Plz help me.
Thanks

答:
The process that you are trying to achieve in the question can be done with the help of the Output Columns in Script Component Transformation task instead of using the variables. The below example explains how this can be achieved and also it demonstrates how variables can be used within the script component. However the same functionality can be achieved using Derived Column Transformation task as well.

This example reads a CSV file and based on the first column value, it will extract value from second column starting from a give position and length. All these values will be stored in a variable.

Step-by-step process:

Create a CSV file as shown in screenshot #1. If the first column has the value Customer, we will extract 6 characters from 9th character on the second column value. If the first column has the value Vendor, we will extract 7 characters from 21st character on the second column value. For every other value, the package will assume value zero for second column value.

Create a table named dbo.Destination using the script under SQL Scripts section. The package will insert the CSV data into this table.

On the SSIS package, create 6 variables as shown in screenshot #2. Configure an OLE DB connection to connect to the SQL Server instance. Configure a Flat File connection to read the CSV file as shown in screenshots #3 - #6. Also, place a Data Flow Task on the Control Flow tab of the package.

Configure the Data Flow Tab with a Flat File Source, Script Component Transformation Task (Refer screenshot #7) and an OLE DB Destination.

Configure the Flat File Source task as shown in screenshots #8 and #9.

Configure the Script Component transformation task as shown in screenshots #10 and #11. A new Output Column named SNumber of data type four-byte signed integer [DT_I4] is created to store the extracted value. Replace the Script Component code with code displayed under Script Component Code section. PreExecute method reads the package variables' values and the method Input0_ProcessInputRow processes the logic to populate the Output Column SNumber.

Configure the OLE DB Destination task as shown in screenshots #12 and #13.

Screenshot #14 shows sample package execution.

Screenshot #15 shows the data in the table dbo.Destination after the package execution.

Hope that helps.

SQL Scripts:
.

```<code>CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Header] [varchar](50) NOT NULL,
    [Value] [varchar](50) NOT NULL,
    [SNumber] [int] NOT NULL,
 CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO
</code>```

Script Component Code:

C# code that can be used only in SSIS 2008 and above.
.

```<code>/* Microsoft SQL Server Integration Services Script Component
*  Write scripts using Microsoft Visual C# 2008.
*  ScriptMain is the entry point class of the script.*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
    IDTSVariables100 varCollection = null;
    string customer = string.Empty;
    int customerPosition = 0;
    int customerLength = 0;
    string vendor = string.Empty;
    int vendorPosition = 0;
    int vendorLength = 0;

    public override void PreExecute()
    {
        this.VariableDispenser.LockForRead("User::Customer");
        this.VariableDispenser.LockForRead("User::CustomerPosition");
        this.VariableDispenser.LockForRead("User::CustomerLength");
        this.VariableDispenser.LockForRead("User::Vendor");
        this.VariableDispenser.LockForRead("User::VendorPosition");
        this.VariableDispenser.LockForRead("User::VendorLength");
        this.VariableDispenser.GetVariables(out varCollection);

        customer = varCollection["User::Customer"].Value.ToString();
        customerPosition = Convert.ToInt32(varCollection["User::CustomerPosition"].Value);
        customerLength = Convert.ToInt32(varCollection["User::CustomerLength"].Value);
        vendor = varCollection["User::Vendor"].Value.ToString();
        vendorPosition = Convert.ToInt32(varCollection["User::VendorPosition"].Value);
        vendorLength = Convert.ToInt32(varCollection["User::VendorLength"].Value);

        base.PreExecute();
    }

    public override void PostExecute()
    {
        base.PostExecute();
    }

    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        if (Row.Header.ToString().Trim() == customer)
        {
            Row.SNumber = Convert.ToInt32(Row.Value.Substring(customerPosition, customerLength));
        }
        else if (Row.Header.ToString().Trim() == vendor)
        {
            Row.SNumber = Convert.ToInt32(Row.Value.Substring(vendorPosition, vendorLength));
        }
        else
        {
            Row.SNumber = 0;
        }
    }

}
</code>```

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Screenshot #5:

Screenshot #6:

Screenshot #7:

Screenshot #8:

Screenshot #9:

Screenshot #10:

Screenshot #11:

Screenshot #12:

Screenshot #13:

Screenshot #14:

Screenshot #15:

ContentLicense: CC BY-SA 2.5

Body:
I want to write a value to a variable in package using script component using C#.

presently i am using these code:

public class ScriptMain : UserComponent
{
string s, r, m;
public override void PreExecute()
{
    base.PreExecute();

}

public override void PostExecute()
{
    base.PostExecute();

    Variables.SNumber = s;
    Variables.RNumber = r;
    Variables.MNumber = m;
   }

public override void Input0_ProcessInputRow(Input0Buffer Row)
{

    if (Row.Col1.Equals("MyName"))
    {

       s = Row.Column4.Substring(122, 5).Trim();
       r  = Row.Column8.Substring(5, 14).Trim();
       m = Row.Column8.Substring(66, 4).Trim() + "." + Row.Column8.Substring(70,
              2).Trim();
   }

}

}

SNumber,Mnumber and RNumber are my global variables in the packages.After the script component iam using derived column to assign the values.
But the variables has no value.Plz help me.
Thanks

Body:
The process that you are trying to achieve in the question can be done with the help of the Output Columns in Script Component Transformation task instead of using the variables. The below example explains how this can be achieved and also it demonstrates how variables can be used within the script component. However the same functionality can be achieved using Derived Column Transformation task as well.

This example reads a CSV file and based on the first column value, it will extract value from second column starting from a give position and length. All these values will be stored in a variable.

Step-by-step process:

Create a CSV file as shown in screenshot #1. If the first column has the value Customer, we will extract 6 characters from 9th character on the second column value. If the first column has the value Vendor, we will extract 7 characters from 21st character on the second column value. For every other value, the package will assume value zero for second column value.

Create a table named dbo.Destination using the script under SQL Scripts section. The package will insert the CSV data into this table.

On the SSIS package, create 6 variables as shown in screenshot #2. Configure an OLE DB connection to connect to the SQL Server instance. Configure a Flat File connection to read the CSV file as shown in screenshots #3 - #6. Also, place a Data Flow Task on the Control Flow tab of the package.

Configure the Data Flow Tab with a Flat File Source, Script Component Transformation Task (Refer screenshot #7) and an OLE DB Destination.

Configure the Flat File Source task as shown in screenshots #8 and #9.

Configure the Script Component transformation task as shown in screenshots #10 and #11. A new Output Column named SNumber of data type four-byte signed integer [DT_I4] is created to store the extracted value. Replace the Script Component code with code displayed under Script Component Code section. PreExecute method reads the package variables' values and the method Input0_ProcessInputRow processes the logic to populate the Output Column SNumber.

Configure the OLE DB Destination task as shown in screenshots #12 and #13.

Screenshot #14 shows sample package execution.

Screenshot #15 shows the data in the table dbo.Destination after the package execution.

Hope that helps.

SQL Scripts:
.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Header] [varchar](50) NOT NULL,
    [Value] [varchar](50) NOT NULL,
    [SNumber] [int] NOT NULL,
 CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

Script Component Code:

C# code that can be used only in SSIS 2008 and above.
.

/* Microsoft SQL Server Integration Services Script Component
*  Write scripts using Microsoft Visual C# 2008.
*  ScriptMain is the entry point class of the script.*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
    IDTSVariables100 varCollection = null;
    string customer = string.Empty;
    int customerPosition = 0;
    int customerLength = 0;
    string vendor = string.Empty;
    int vendorPosition = 0;
    int vendorLength = 0;

    public override void PreExecute()
    {
        this.VariableDispenser.LockForRead("User::Customer");
        this.VariableDispenser.LockForRead("User::CustomerPosition");
        this.VariableDispenser.LockForRead("User::CustomerLength");
        this.VariableDispenser.LockForRead("User::Vendor");
        this.VariableDispenser.LockForRead("User::VendorPosition");
        this.VariableDispenser.LockForRead("User::VendorLength");
        this.VariableDispenser.GetVariables(out varCollection);

        customer = varCollection["User::Customer"].Value.ToString();
        customerPosition = Convert.ToInt32(varCollection["User::CustomerPosition"].Value);
        customerLength = Convert.ToInt32(varCollection["User::CustomerLength"].Value);
        vendor = varCollection["User::Vendor"].Value.ToString();
        vendorPosition = Convert.ToInt32(varCollection["User::VendorPosition"].Value);
        vendorLength = Convert.ToInt32(varCollection["User::VendorLength"].Value);

        base.PreExecute();
    }

    public override void PostExecute()
    {
        base.PostExecute();
    }

    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        if (Row.Header.ToString().Trim() == customer)
        {
            Row.SNumber = Convert.ToInt32(Row.Value.Substring(customerPosition, customerLength));
        }
        else if (Row.Header.ToString().Trim() == vendor)
        {
            Row.SNumber = Convert.ToInt32(Row.Value.Substring(vendorPosition, vendorLength));
        }
        else
        {
            Row.SNumber = 0;
        }
    }

}

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Screenshot #5:

Screenshot #6:

Screenshot #7:

Screenshot #8:

Screenshot #9:

Screenshot #10:

Screenshot #11:

Screenshot #12:

Screenshot #13:

Screenshot #14:

Screenshot #15:


问:
get response.status in .then in Java Script
I tried to check if the status of my request is 200 (OK), but I do not know how to do these things together because the first and second .then, are not "like each other":

function f(path) {
    await fetch(path)
            .then(response => {
                // console.log(response.status);
                if (response.status != 200) {
                    throw response.status;
                } else {
                    // do something
                }
            })
            .then(response => response.json())
            .then(...method for the response.json()...)
            .catch(error => {
                // print some error message
            }
}
```

The second then failed and returned error.

I have a problem when I throw that.

It prints to the error to the console (when I check by changing the path to wrong path and I want to see if I treat errors).

what can I do?

答:
You're checking it correctly in your first fulfillment handler (then callback), although I'd just use !response.ok. You don't usually need the status in the subsequent handlers.

But the problem with your first fulfillment handler is that it's not returning anything, so the subsequent fulfillment handler only sees undefined. Instead, return the promise from json():

```<code>function f(path) {
    fetch(path)
        .then(response => {
            if (!response.ok) {
                // Note: Strongly recommend using Error for exceptions/rejections
                throw new Error("HTTP error " + response.status);
            }
            return response.json();
        })
        .then(data => {
            // ...use the data here...
        })
        .catch(error => {
            // ...show/handle error here...
        });
}
</code>```

Note that you can't use await in a traditional function, only in an async function. But you don't need it if you're using .then and .catch. I've removed it above.

If for some reason you wanted the status in subsequent fulfillment handlers, you'd have to return it from the first fulfillment handler. For instance:

```<code>function f(path) {
    fetch(path)
        .then(response => {
            if (!response.ok) {
                // Note: Strongly recommend using Error for exceptions/rejections
                throw new Error("HTTP error " + response.status);
            }
            return response.json().then(data => ({status: response.status, data}));
        })
        .then(({status, data}) => {
            // ...use `status` and `data` here...
        })
        .catch(error => {
            // ...show/handle error here...
        });
}
</code>```

In that, I've used a nested fulfillment handler on the promise from json(), and then returned an object with status and data on it.

Body:
I tried to check if the status of my request is 200 (OK), but I do not know how to do these things together because the first and second .then, are not "like each other":

function f(path) {
    await fetch(path)
            .then(response => {
                // console.log(response.status);
                if (response.status != 200) {
                    throw response.status;
                } else {
                    // do something
                }
            })
            .then(response => response.json())
            .then(...method for the response.json()...)
            .catch(error => {
                // print some error message
            }
}

The second then failed and returned error.

I have a problem when I throw that.

It prints to the error to the console (when I check by changing the path to wrong path and I want to see if I treat errors).

what can I do?

Body:
You're checking it correctly in your first fulfillment handler (then callback), although I'd just use !response.ok. You don't usually need the status in the subsequent handlers.

But the problem with your first fulfillment handler is that it's not returning anything, so the subsequent fulfillment handler only sees undefined. Instead, return the promise from json():

function f(path) {
    fetch(path)
        .then(response => {
            if (!response.ok) {
                // Note: Strongly recommend using Error for exceptions/rejections
                throw new Error("HTTP error " + response.status);
            }
            return response.json();
        })
        .then(data => {
            // ...use the data here...
        })
        .catch(error => {
            // ...show/handle error here...
        });
}

Note that you can't use await in a traditional function, only in an async function. But you don't need it if you're using .then and .catch. I've removed it above.

If for some reason you wanted the status in subsequent fulfillment handlers, you'd have to return it from the first fulfillment handler. For instance:

function f(path) {
    fetch(path)
        .then(response => {
            if (!response.ok) {
                // Note: Strongly recommend using Error for exceptions/rejections
                throw new Error("HTTP error " + response.status);
            }
            return response.json().then(data => ({status: response.status, data}));
        })
        .then(({status, data}) => {
            // ...use `status` and `data` here...
        })
        .catch(error => {
            // ...show/handle error here...
        });
}

In that, I've used a nested fulfillment handler on the promise from json(), and then returned an object with status and data on it.


答:
You need to return in your then chain, which at a glance appears to be one too many. Check out the following example...

fetch(path)
  .then(r => r.ok ? r.json() : Promise.reject('oops')) // .statusText, etc
  .then(r => {
    // [...]
  })
  .catch(e => console.error(e)); // oops
```

Title: get response.status in .then in Java Script


答:
a) I don't think you need await keyword since you're using .then() chaining.

b) You have to return something from the first then so as to get that in the next .then()

function f(path) {
await fetch(path)
        .then(response => {
            // console.log(response.status);
            if (response.status != 200) {
                throw response.status;
            } else {
                // do something
                 // After doing what you need return the response
                return response
            }
        })
        .then(response => response.json())
        .then(...method for the response.json()...)
        .catch(error => {
          // print some error message
          }
}```


问:
How to combine two flat lists into one nested object
I have three lists which contains three same properties in each collection. I want to combine a result into one collection. Ex classes structure is as below

```<code>public class Order
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }

    // Few other Properties of OrderDetail
}
public class PaymentDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form PaymentDetail
}

public class CouponUsageDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form CouponUsageDetail
}
</code>```

This type of output is coming from one API service where each class is in form of list object (JSON format) and we need to perform some operations on this. All three properties (ProductId,CustomerId, OrderId) contains same values in each collection which means all three properties are repeated in each collection. We need to perform some look ups on these collections. So in normal way what we can do with it is as - start a foreach from Order list and filter all three matching properties of PaymentDetail and CouponUsageDetail. But it would be costlier in term of performance when the data size is increased. So thought of making nesting structure upfront and avoid lookups. If we make the output nested as below this will help to avoid lookups on PaymentDetail and CouponUsageDetail.
Ex - we are receiving JOSN in below format

```<code>{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}
</code>```

and with this output we want to form object as

```<code>public class OrderDetails
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties of OrderDetail

    List<PaymentDetail> PaymentDetail { get; set; }
    List<CouponUsageDetail> CouponUsageDetail { get; set; }
}
</code>```

Can you guide, what would be the best optimum usage of linq where we can combine all these three matching properties and make it just one nested structure better?
Thank You!
 Note: I know this structure needs to be normalized but please ignore the normalization rule here as this is not in our control.

答:
You can use inheritance.

public class ResultCollection : Collection1
{
    List<Collection2> Collection2s { get; set; }
    List<Collection3> Collection3s { get; set; }
}
```

<p>and then</p>

<pre class="lang-cs prettyprint-override"><code>var result = new ResultCollection {
    PropId1 = Collection1.PropId1,
    PropId2 = Collection1.PropId2,
    ...
    Collection2s = Collection2,
    Collection3s = Collection3
}
</code>```

An automapper can be helpful here.

https://docs.automapper.org/en/stable/

Body:
I have three lists which contains three same properties in each collection. I want to combine a result into one collection. Ex classes structure is as below

public class Order
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }

    // Few other Properties of OrderDetail
}
public class PaymentDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form PaymentDetail
}

public class CouponUsageDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form CouponUsageDetail
}

This type of output is coming from one API service where each class is in form of list object (JSON format) and we need to perform some operations on this. All three properties (ProductId,CustomerId, OrderId) contains same values in each collection which means all three properties are repeated in each collection. We need to perform some look ups on these collections. So in normal way what we can do with it is as - start a foreach from Order list and filter all three matching properties of PaymentDetail and CouponUsageDetail. But it would be costlier in term of performance when the data size is increased. So thought of making nesting structure upfront and avoid lookups. If we make the output nested as below this will help to avoid lookups on PaymentDetail and CouponUsageDetail.
Ex - we are receiving JOSN in below format

{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}

and with this output we want to form object as

public class OrderDetails
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties of OrderDetail

    List<PaymentDetail> PaymentDetail { get; set; }
    List<CouponUsageDetail> CouponUsageDetail { get; set; }
}

Can you guide, what would be the best optimum usage of linq where we can combine all these three matching properties and make it just one nested structure better?
Thank You!
 Note: I know this structure needs to be normalized but please ignore the normalization rule here as this is not in our control.

Body:
You can use inheritance.

public class ResultCollection : Collection1
{
    List<Collection2> Collection2s { get; set; }
    List<Collection3> Collection3s { get; set; }
}

and then

var result = new ResultCollection {
    PropId1 = Collection1.PropId1,
    PropId2 = Collection1.PropId2,
    ...
    Collection2s = Collection2,
    Collection3s = Collection3
}

An automapper can be helpful here.

https://docs.automapper.org/en/stable/


问:
Why do access tokens issued by AAD contain information about the user?
I read a lot about OAuth 2.0 and OpenId Connect and in theory I understand both concepts now.

But if I go into practice, some things are still confusing for me and I hope you can enlighten me in some way...

First thing is, that in all code samples how to secure a .net core API in an AAD-environment I find lines like this in the configure-section:

```<code>app.UseAuthentication()
</code>```

and lines like this in the ConfigureServices section:

```<code>        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://login.microsoftonline.com/xxxxxxxx";
            options.Audience = "xxxx-xxx-xxx-xxx-xxxx";
        });
</code>```

However, to access my API I am not using an ID token, but an access token what is Authorization, not "Authentication" like in the code samples.

This works - but I do not understand it 100%.

So my first question is:

Is the access token also "authenticating" in some way?

The second thing:

I read that access tokens have no standardized format. They can be JWT or not, can have an audience or not etc. For this reason you could even put user information in the token like microsoft does. The access tokens contain claims like a "family name" or "given name" etc.

Id tokens in contrast have a standardized format to ensure that authentication is done in the same way by everyone.

If people are accessing my apis with an access token, I can read their name or e-mail address with "user.identity.name" for example. This value I can use to store the information who edited something or who inserted something.

So I am fetching information about the user with access tokens!

So my second question is:

Am I doing the right thing here? Or should this be done in another way.

and:

Should access tokens ever contain information about the user?

答:
Is the access token also "authenticating" in some way?

Yes.
Your API is validating the access token when it receives it.
This is the authentication part, when your API verifies that the token signature is valid, came from the Azure AD tenant that you trust, that it is meant for your API and that it has not expired.

The authorization is when you check what permissions the token contains.
Your API can define different permissions that are given to client applications, allowing them different levels of access.
A valid token can pass authentication, but it might not pass authorization if it lacks the necessary permissions.

Am I doing the right thing here? Or should this be done in another way.

Fundamentally your are doing the correct thing.
The token tells you who the user is that is using the client application, and if you need to know who it was who did something, that's the info you use.
However, if you really want to connect an action to a user, I suggest you use their object identifier / object id / oid instead of their name / username as those can change.
Unless you just want their display name.

Should access tokens ever contain information about the user?

In the context of Azure AD, an access token will always contain info about the user if a client application is accessing an API on behalf of a user.
This includes authentication flows like authorization code, device code, implicit, and on-behalf-of.
They all use delegated permissions aka scopes to call APIs on behalf of the user.
Thus the token contains info about the calling app and the user.

If an app acquires an access token using the client credentials flow where a user is not involved, there will be no user info in the token.
In this case, application permissions are used instead of delegated permissions in Azure AD.
An application acts as itself, not on behalf of any user.

If your API supports both of these scenarios, sometimes the tokens contain user info and sometimes not.

The part about token formats is basically correct from a specification standpoint.
OAuth doesn't define a strict format for access tokens, while OpenID Connect does define one for ID tokens.

Using an access token to call your API is definitely correct.
The ID token is only meant for the app that initiated the user authentication, not for any APIs that it calls.
That's what access tokens are for.

Body:
I read a lot about OAuth 2.0 and OpenId Connect and in theory I understand both concepts now.

But if I go into practice, some things are still confusing for me and I hope you can enlighten me in some way...

First thing is, that in all code samples how to secure a .net core API in an AAD-environment I find lines like this in the configure-section:

app.UseAuthentication()

and lines like this in the ConfigureServices section:

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://login.microsoftonline.com/xxxxxxxx";
            options.Audience = "xxxx-xxx-xxx-xxx-xxxx";
        });

However, to access my API I am not using an ID token, but an access token what is Authorization, not "Authentication" like in the code samples.

This works - but I do not understand it 100%.

So my first question is:

Is the access token also "authenticating" in some way?

The second thing:

I read that access tokens have no standardized format. They can be JWT or not, can have an audience or not etc. For this reason you could even put user information in the token like microsoft does. The access tokens contain claims like a "family name" or "given name" etc.

Id tokens in contrast have a standardized format to ensure that authentication is done in the same way by everyone.

If people are accessing my apis with an access token, I can read their name or e-mail address with "user.identity.name" for example. This value I can use to store the information who edited something or who inserted something.

So I am fetching information about the user with access tokens!

So my second question is:

Am I doing the right thing here? Or should this be done in another way.

and:

Should access tokens ever contain information about the user?


问:
How to show a legend in plotly (python) sankey?
I want to plot some sankey diagrams representing mass flows of different substances for a report. I want to put a legend to differentiate the substances but I don't know how to do it. I've tried showlegend without success

```<code>import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ['household','industry','waste'],
      color = "blue"
    ),
    link = dict(
      source = [0,1,0,1], # indices correspond to labels, eg A1, A2, A2, B1, ...
      target = [2,2,2,2],
      value = [7190,2074,4483,74.50],
      label = ['aluminium','aluminium','copper','copper'],
      color = ['#d7d6d6','#d7d6d6','#f3cf07','#f3cf07']
  ))])
fig.update_layout(showlegend=True)
fig.show()
</code>```

答:
It seems that Plotly Sankey traces don't actual support legends, despite the docs currently seeming to indicate they do.

I've created a corresponding issue on the Plotly repo; looks like the resolution may be improving the docs to make this clearer.

Body:
I want to plot some sankey diagrams representing mass flows of different substances for a report. I want to put a legend to differentiate the substances but I don't know how to do it. I've tried showlegend without success

import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ['household','industry','waste'],
      color = "blue"
    ),
    link = dict(
      source = [0,1,0,1], # indices correspond to labels, eg A1, A2, A2, B1, ...
      target = [2,2,2,2],
      value = [7190,2074,4483,74.50],
      label = ['aluminium','aluminium','copper','copper'],
      color = ['#d7d6d6','#d7d6d6','#f3cf07','#f3cf07']
  ))])
fig.update_layout(showlegend=True)
fig.show()


问:
Sonata admin bundle: display role wise sidebar menu
I successfully setup sonata admin bundle with acl editor. I am easily able to set user wise permission on object as well as roles users using acl editor. but when i trying to login using particular role then i cannot see in sidebar menu which i permitted to particular role.

e.g

i have roles like ROLE_MASTER_ADMIN, ROLE_SUPER_ADMIN, ROLE_VENDOR, ROLE_RETAILER. i have set two menu for now using USERBUNDLE i.e. users and group. which is shown for two roles ROLE_MASTER_ADMIN, ROLE_SUPER_ADMIN with full list, edit, delete, undelete, operator, master and owner permissions.

Then i set permissions for ROLE_VENDOR which has access of users list, edit, delete and undelete. same as i set permission for ROLE_RETAILER which has access of groups list, edit, delete and undelete.

after login with ROLE_VENDOR, ROLE_RETAILER users i am not able to see anything in sidebar menu.

i need help to implement this. thanks in advance.

this is what i set in my config.yml file

sonata_admin:
   dashboard:
      groups:
        sonata_user:
            label: sonata_user
            label_catalogue: SonataUserBundle
            icon: ''
            items:
                -
                  admin:    sonata.user.admin.user
                  route:    admin_sonata_user_user_list
                  label:    users
                  roles:    ['ROLE_MASTER_ADMIN', 'ROLE_SUPER_ADMIN', 'ROLE_VENDOR']
                -
                  admin:    sonata.user.admin.group
                  route:    admin_sonata_user_group_list
                  label:    groups
                  roles:    ['ROLE_MASTER_ADMIN', 'ROLE_SUPER_ADMIN', 'ROLE_RETAILER']
            roles: ['ROLE_MASTER_ADMIN', 'ROLE_SUPER_ADMIN', 'ROLE_VENDOR', 'ROLE_RETAILER']

but it shows me error like below:

An exception has been thrown during the rendering of a template ("Warning: get_class() expects parameter 1 to be object, string given").

UPDATED
Command Output

=> php app/console sonata:admin:generate-object-acl

Welcome to the AdminBundle object ACL generator

This command helps you to generate ACL entities for the objects handled by the AdminBundle.

If the step option is used, you will be asked if you want to generate the object ACL entities for each Admin.
You must use the shortcut notation like AcmeDemoBundle:User if you want to set an object owner.

generate ACLs for sonata.user.admin.user

[TOTAL] generated class ACEs for 4 objects (added 0, updated 4)

generate ACLs for sonata.user.admin.group

[TOTAL] generated class ACEs for 0 objects (added 0, updated 0)

=> php app/console sonata:admin:setup-acl

Starting ACL AdminBundle configuration

install ACL for sonata.user.admin.user

update role: ROLE_SONATA_USER_ADMIN_USER_ROLE_RETAILER, permissions: ["LIST"]

update role: ROLE_SONATA_USER_ADMIN_USER_ROLE_VENDOR, permissions: ["LIST","EDIT","CREATE"]

update role: ROLE_SONATA_USER_ADMIN_USER_ROLE_MASTER_ADMIN, permissions: ["MASTER"]

install ACL for sonata.user.admin.group

update role: ROLE_SONATA_USER_ADMIN_GROUP_ROLE_RETAILER, permissions: ["LIST"]

update role: ROLE_SONATA_USER_ADMIN_GROUP_ROLE_VENDOR, permissions: ["LIST","EDIT","CREATE"]

update role: ROLE_SONATA_USER_ADMIN_GROUP_ROLE_MASTER_ADMIN, permissions: ["MASTER"]

答:
You need to add next config to your services.yaml:</p>

```<code>security.acl.permission.map:
  class: Sonata\AdminBundle\Security\Acl\Permission\AdminPermissionMap
</code>```

Body:
You need to add next config to your services.yaml:

security.acl.permission.map:
  class: Sonata\AdminBundle\Security\Acl\Permission\AdminPermissionMap


问:
Testing file upload in lumen 5.5
I'm using Lumen 5.5, and I wrote simple app that upload files.

I wrote test like this (following this tutorial)

```<code><?php

class UploadImageTest extends TestCase
{

    Use DatabaseMigrations;

    public function testUploadingImageSuccessfully()
    {
        $this->json('POST', '/images', [
            'image' => UploadedFile::fake()->image('image.jpg')
        ])->assertResponseOk()
    }

}
</code>```

problem is that in my controller, $request->file('image') returns null.

```<code><?php

use Illuminate\Http\Request;

class UploadController extends Controller
{

    public function upload(Request $request)
    {
        if ($request->file('image')) { // always return null
            return "File is uploaded!";
        }

        return "File is not uploaded!";
    }

}
</code>```

I checked other questions (like this one) and tried given solutions with no luck!

答:
this is working for me. just simple. this can submit file upload.

1.condition without authentication

5*1000 is file size (in KB). so i made a test with 5 MB file.

```<code>use Faker\Factory as Faker;
use Illuminate\Http\UploadedFile;

class SampleTest extends TestCase
{
    public function testItCanCreateUser()
    {
        $faker = Faker::create();
        $files = [
            'file' => UploadedFile::fake()->create('file.jpg', 5*1000)
        ];
        $response = $this->call('POST', '/chunk', [], [], $files);
        $this->assertEquals(200, $response->getStatusCode());
    }
}
</code>```

2.condition with authentication (logged in user)

```<code>use Faker\Factory as Faker;
use Illuminate\Http\UploadedFile;

class SampleTest extends TestCase
{
    public function testItCanUpdateProfileUser()
    {
        $faker = Faker::create();
        $files = [
            'file' => UploadedFile::fake()->create('file.jpg', 5*1000)
        ];

        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'your-jwt-token'
        ];
        $servers = [];
        foreach ($headers as $k => $header) {
            $servers["HTTP_" . $k] = $header;
        }

        $response = $this->call('POST', '/chunk', [], [], $files, $servers);
        $this->assertEquals(200, $response->getStatusCode());
    }
}
</code>```

you need to add HTTP_ on every request header. i'm not sure why. but it will work.

Title: Testing file upload in lumen 5.5

Body:
I'm using Lumen 5.5, and I wrote simple app that upload files.

I wrote test like this (following this tutorial)

<?php

class UploadImageTest extends TestCase
{

    Use DatabaseMigrations;

    public function testUploadingImageSuccessfully()
    {
        $this->json('POST', '/images', [
            'image' => UploadedFile::fake()->image('image.jpg')
        ])->assertResponseOk()
    }

}

problem is that in my controller, $request->file('image') returns null.

<?php

use Illuminate\Http\Request;

class UploadController extends Controller
{

    public function upload(Request $request)
    {
        if ($request->file('image')) { // always return null
            return "File is uploaded!";
        }

        return "File is not uploaded!";
    }

}

I checked other questions (like this one) and tried given solutions with no luck!

Body:
this is working for me. just simple. this can submit file upload.

1.condition without authentication

5*1000 is file size (in KB). so i made a test with 5 MB file.

use Faker\Factory as Faker;
use Illuminate\Http\UploadedFile;

class SampleTest extends TestCase
{
    public function testItCanCreateUser()
    {
        $faker = Faker::create();
        $files = [
            'file' => UploadedFile::fake()->create('file.jpg', 5*1000)
        ];
        $response = $this->call('POST', '/chunk', [], [], $files);
        $this->assertEquals(200, $response->getStatusCode());
    }
}

2.condition with authentication (logged in user)

use Faker\Factory as Faker;
use Illuminate\Http\UploadedFile;

class SampleTest extends TestCase
{
    public function testItCanUpdateProfileUser()
    {
        $faker = Faker::create();
        $files = [
            'file' => UploadedFile::fake()->create('file.jpg', 5*1000)
        ];

        $headers = [
            'Accept' => 'application/json',
            'Authorization' => 'your-jwt-token'
        ];
        $servers = [];
        foreach ($headers as $k => $header) {
            $servers["HTTP_" . $k] = $header;
        }

        $response = $this->call('POST', '/chunk', [], [], $files, $servers);
        $this->assertEquals(200, $response->getStatusCode());
    }
}

you need to add HTTP_ on every request header. i'm not sure why. but it will work.


问:
Is it okay to use functions to stay organized in C?
I'm a relatively new C programmer, and I've noticed that many conventions from other higher-level OOP languages don't exactly hold true on C.

Is it okay to use short functions to have your coding stay organized (even though it will likely be called only once)? An example of this would be 10-15 lines in something like void init_file(void), then calling it first in main().

答:
Functions are absolutely necessary to stay organized. You need to first design the problem, and then depending on the different functionality you need to split them into functions. Some segment of code which is used multiple times, probably needs to be written in a function.

I think first thinking about what problem you have in hand, break down the components and for each component try writing a function. When writing the function see if there are some code segment doing the same thing, then break it into a sub function, or if there is a sub module then it is also a candidate for another function. But at some time this breaking job should stop, and it depends on you. Generally, do not make many too big functions and not many too small functions.

When construction the function please consider the design to have high cohesion and low coupling.

EDIT1::

you might want to also consider separate modules. For example if you need to use a stack or queue for some application. Make it separate modules whose functions could be called from other functions. This way you can save re-coding commonly used modules by programming them as a group of functions stored separately.