问:
Sticky multiple row header and multiple columns using vanilla JavaScript in a container I can't control
My code will return the HTML for a table that will be put inside of a container (such as a div). I have no control of this root container/div but my code can put anything inside, like nesting a div if necessary.

The table will have rows and columns that may extend beyond the viewport of the parent container.

The table will have 2-3 rows in a thead that need to be stuck/frozen on vertical scroll.

The table will have X # of columns that need to be stuck/frozen on horizontal scroll.

I am trying to use position: sticky but not having luck.

I saw Sticky multiple table header (thead) rows using only css/bootstrap but that doesn't work cause it requires setting an explicit height for each of the rows in he thead and I can't do that since the content in the thead rows may be of variable height.

In the example below, I included the root/parent container div but that is for example. I can't change it's properties. I can add more divs inside if needed.

table, th, td
{
  border: 1px solid black;
  border-collapse: collapse;
}

thead
{
  position: sticky;
  z-index: 1;
  background-color: red;
}

tbody td.stuck
{
  background-color: blue;
  position: sticky;
  z-index: 1
}

/* I have no control of this DIV */
/* I am just putting it here for an example */
div
{
  position: absolute;
  top: 20px;
  left: 30px;
  width: 500px;
  height: 200px;
  overflow: auto;
  background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <table>
    <thead>
      <tr>
        <td colspan="20">one</td>
      </tr>
      <tr>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
      </tr>
     </thead>
     <tbody>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
    </tbody>
   </table>
</div></code>```

答:
Here's a solutions just using top and left of those sticky elements.

If the td.stuck cannot be a fixed width, you could throw a javascript to calculate the width.

table, th, td
{
  border: 1px solid black;
  border-collapse: separate;
  border-spacing: 0;
}

thead
{
  position: sticky;
  top: 0;
  z-index: 2;
  background-color: red;
}

tbody td.stuck
{
  background-color: blue;
  position: sticky;
  left: 0;
  z-index: 1;
}

tbody td.stuck:nth-child(2) {
  left: 51px;
}

/* I have no control of this DIV */
/* I am just putting it here for an example */
div
{
  position: absolute;
  top: 20px;
  left: 30px;
  width: 500px;
  height: 200px;
  overflow: auto;
  background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <table>
    <thead>
      <tr>
        <td colspan="20">one</td>
      </tr>
      <tr>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
      </tr>
     </thead>
     <tbody>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
    </tbody>
   </table>
</div></code>```

Body:
My code will return the HTML for a table that will be put inside of a container (such as a div). I have no control of this root container/div but my code can put anything inside, like nesting a div if necessary.

The table will have rows and columns that may extend beyond the viewport of the parent container.

The table will have 2-3 rows in a thead that need to be stuck/frozen on vertical scroll.

The table will have X # of columns that need to be stuck/frozen on horizontal scroll.

I am trying to use position: sticky but not having luck.

I saw Sticky multiple table header (thead) rows using only css/bootstrap but that doesn't work cause it requires setting an explicit height for each of the rows in he thead and I can't do that since the content in the thead rows may be of variable height.

In the example below, I included the root/parent container div but that is for example. I can't change it's properties. I can add more divs inside if needed.

table, th, td
{
  border: 1px solid black;
  border-collapse: collapse;
}

thead
{
  position: sticky;
  z-index: 1;
  background-color: red;
}

tbody td.stuck
{
  background-color: blue;
  position: sticky;
  z-index: 1
}

/* I have no control of this DIV */
/* I am just putting it here for an example */
div
{
  position: absolute;
  top: 20px;
  left: 30px;
  width: 500px;
  height: 200px;
  overflow: auto;
  background-color: yellow;
}

        one

        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header
        header

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell
        cell

Body:
Here's a solutions just using top and left of those sticky elements.

If the td.stuck cannot be a fixed width, you could throw a javascript to calculate the width.

table, th, td
{
  border: 1px solid black;
  border-collapse: separate;
  border-spacing: 0;
}

thead
{
  position: sticky;
  top: 0;
  z-index: 2;
  background-color: red;
}

tbody td.stuck
{
  background-color: blue;
  position: sticky;
  left: 0;
  z-index: 1;
}

tbody td.stuck:nth-child(2) {
  left: 51px;
}

/* I have no control of this DIV */
/* I am just putting it here for an example */
div
{
  position: absolute;
  top: 20px;
  left: 30px;
  width: 500px;
  height: 200px;
  overflow: auto;
  background-color: yellow;
}

<div>
  <table>
    <thead>
      <tr>
        <td colspan="20">one</td>
      </tr>
      <tr>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
        <th>header</th>
      </tr>
     </thead>
     <tbody>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
      <tr>
        <td class="stuck">cell</td>
        <td class="stuck">cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
        <td>cell</td>
      </tr>
    </tbody>
   </table>
</div>


来源: stackexchange

问:
How do i close a old window each time a new window is oppened in tkinter
I have a simplified code below of 2 separate screens. How do I have it so that when one screen is opened the old one is then closed?

Whilst i don't have multiple screens in this example i would like to be able to to this for 6-9 screens dependent upon GUI design.

any help on the subject would be greatly appreciated.

```<code>from tkinter import *
import os
import time
from tkinter import simpledialog

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("530x290")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()

    calibration1 = StringVar()
    calibration2 = StringVar()
    calibration3 = StringVar()

    global calibration1_entry
    global calibration2_entry
    global calibration3_entry

    calibration1_entry= Entry(screen2, textvariable = calibration1).place(x=350, y=70)
    calibration2_entry = Entry(screen2, textvariable = calibration2).place(x=350, y=120)
    calibration3_entry = Entry(screen2, textvariable = calibration3).place(x=350, y=170)

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("530x290")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()

    screen.mainloop()

main_screen()
</code>```

答:
You can assign screen2 to be None at the beginning and make sure to destroy and reopen it, if it isn't None:

```<code>def login():
    global screen2

    if screen2 is None: # if screen2 is not Toplevel
        screen2 = Toplevel(screen)
    else:
        screen2.destroy() # destroy and start new screen
        screen2 = Toplevel(screen)
    ...
    ...

def main_screen():
    global screen2,screen

    screen = Tk()
    screen2 = None # Assign to None at the beginning
    ...
    ...
</code>```

This will also make sure no two Toplevel is open at the same time.

ContentLicense: CC BY-SA 4.0

Body:
I have a simplified code below of 2 separate screens. How do I have it so that when one screen is opened the old one is then closed?

Whilst i don't have multiple screens in this example i would like to be able to to this for 6-9 screens dependent upon GUI design.

any help on the subject would be greatly appreciated.

from tkinter import *
import os
import time
from tkinter import simpledialog

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("530x290")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()

    calibration1 = StringVar()
    calibration2 = StringVar()
    calibration3 = StringVar()

    global calibration1_entry
    global calibration2_entry
    global calibration3_entry

    calibration1_entry= Entry(screen2, textvariable = calibration1).place(x=350, y=70)
    calibration2_entry = Entry(screen2, textvariable = calibration2).place(x=350, y=120)
    calibration3_entry = Entry(screen2, textvariable = calibration3).place(x=350, y=170)

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("530x290")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()

    screen.mainloop()

main_screen()

Body:
You can assign screen2 to be None at the beginning and make sure to destroy and reopen it, if it isn't None:

def login():
    global screen2

    if screen2 is None: # if screen2 is not Toplevel
        screen2 = Toplevel(screen)
    else:
        screen2.destroy() # destroy and start new screen
        screen2 = Toplevel(screen)
    ...
    ...

def main_screen():
    global screen2,screen

    screen = Tk()
    screen2 = None # Assign to None at the beginning
    ...
    ...

This will also make sure no two Toplevel is open at the same time.


问:
How to get the dynamic height of UIView which contains two or more UILabels vertically?
I am trying to find the dynamic height of a UIView at the run time. So, for this I calculated the run time height of UILabels in it and the constraint constants and add them all to get the desired height. But this doesn't seems to be the correct way of doing it, because in case I alter the count of UILabel or constraints in future then I do have to change the code to calculate the dynamic height. So, is there any way to get the height of UIView at run time with any number of labels and constraints in it?

MY CODE

Here uiview is UIView of which I need to calculate the dynamic height, label1 and label2 are the UILabels in which I inserted text programatically. height is a string extension to find dynamic height of UILabel. label1TopConstraint, label1BottonContraint, label2BottomConstraint are constraints IBOutlets.

```<code>let label1Height = label1.text!.height(withConstrainedWidth: label1.frame.width, font: label1.font)
let label2Height = label2.text!.height(withConstrainedWidth: label2.frame.width, font: label2.font)
uiviewHeight = label1Height + label2Height + label1TopConstraint.constant + label1BottonContraint.constant + label2BottomConstraint.constant
</code>```

答:
Why do you need those runtime calculations if you already use AutoLayout and can rely on constraints? Here's an example:

A view, containing two labels:

import UIKit

final class LabelsView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .red

        let label1 = UILabel()
        label1.translatesAutoresizingMaskIntoConstraints = false
        label1.text = "Label 1"
        label1.backgroundColor = .red

        addSubview(label1)
        NSLayoutConstraint.activate([label1.widthAnchor.constraint(equalTo: widthAnchor),
                                     label1.centerXAnchor.constraint(equalTo: centerXAnchor),
                                     label1.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5),
                                     label1.topAnchor.constraint(equalTo: topAnchor)])

        let label2 = UILabel()
        label2.translatesAutoresizingMaskIntoConstraints = false
        label2.text = "Label 2"
        label2.backgroundColor = .green

        addSubview(label2)
        NSLayoutConstraint.activate([label2.widthAnchor.constraint(equalTo: widthAnchor),
                                     label2.centerXAnchor.constraint(equalTo: centerXAnchor),
                                     label2.heightAnchor.constraint(equalTo: label1.heightAnchor),
                                     label2.bottomAnchor.constraint(equalTo: bottomAnchor)])
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
```
<p>An example usage outcome:</p>
<p><img src="https://i.stack.imgur.com/UDKpz.png" alt="enter image description here" /></p>
<p>Here's a view that reuses the first one (among others):</p>
<pre class="lang-swift prettyprint-override"><code>final class AnotherView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .blue

        let labelsView = LabelsView()
        labelsView.translatesAutoresizingMaskIntoConstraints = false

        addSubview(labelsView)
        NSLayoutConstraint.activate([labelsView.widthAnchor.constraint(equalTo: widthAnchor),
                                     labelsView.centerXAnchor.constraint(equalTo: centerXAnchor),
                                     labelsView.topAnchor.constraint(equalTo: topAnchor, constant: 10.0)])

        let yetAnotherView = UIView()
        yetAnotherView.translatesAutoresizingMaskIntoConstraints = false
        yetAnotherView.backgroundColor = .white

        addSubview(yetAnotherView)
        NSLayoutConstraint.activate([yetAnotherView.widthAnchor.constraint(equalTo: widthAnchor),
                                     yetAnotherView.centerXAnchor.constraint(equalTo: centerXAnchor),
                                     yetAnotherView.heightAnchor.constraint(equalTo: labelsView.heightAnchor),
                                     yetAnotherView.topAnchor.constraint(equalTo: labelsView.bottomAnchor,
                                                                         constant: 10.0)])
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
</code>```

An example usage output:

Body:
I am trying to find the dynamic height of a UIView at the run time. So, for this I calculated the run time height of UILabels in it and the constraint constants and add them all to get the desired height. But this doesn't seems to be the correct way of doing it, because in case I alter the count of UILabel or constraints in future then I do have to change the code to calculate the dynamic height. So, is there any way to get the height of UIView at run time with any number of labels and constraints in it?

MY CODE

Here uiview is UIView of which I need to calculate the dynamic height, label1 and label2 are the UILabels in which I inserted text programatically. height is a string extension to find dynamic height of UILabel. label1TopConstraint, label1BottonContraint, label2BottomConstraint are constraints IBOutlets.

let label1Height = label1.text!.height(withConstrainedWidth: label1.frame.width, font: label1.font)
let label2Height = label2.text!.height(withConstrainedWidth: label2.frame.width, font: label2.font)
uiviewHeight = label1Height + label2Height + label1TopConstraint.constant + label1BottonContraint.constant + label2BottomConstraint.constant

Body:
Why do you need those runtime calculations if you already use AutoLayout and can rely on constraints? Here's an example:

A view, containing two labels:

import UIKit

final class LabelsView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .red

        let label1 = UILabel()
        label1.translatesAutoresizingMaskIntoConstraints = false
        label1.text = "Label 1"
        label1.backgroundColor = .red

        addSubview(label1)
        NSLayoutConstraint.activate([label1.widthAnchor.constraint(equalTo: widthAnchor),
                                     label1.centerXAnchor.constraint(equalTo: centerXAnchor),
                                     label1.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.5),
                                     label1.topAnchor.constraint(equalTo: topAnchor)])

        let label2 = UILabel()
        label2.translatesAutoresizingMaskIntoConstraints = false
        label2.text = "Label 2"
        label2.backgroundColor = .green

        addSubview(label2)
        NSLayoutConstraint.activate([label2.widthAnchor.constraint(equalTo: widthAnchor),
                                     label2.centerXAnchor.constraint(equalTo: centerXAnchor),
                                     label2.heightAnchor.constraint(equalTo: label1.heightAnchor),
                                     label2.bottomAnchor.constraint(equalTo: bottomAnchor)])
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

An example usage outcome:

Here's a view that reuses the first one (among others):

final class AnotherView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .blue

        let labelsView = LabelsView()
        labelsView.translatesAutoresizingMaskIntoConstraints = false

        addSubview(labelsView)
        NSLayoutConstraint.activate([labelsView.widthAnchor.constraint(equalTo: widthAnchor),
                                     labelsView.centerXAnchor.constraint(equalTo: centerXAnchor),
                                     labelsView.topAnchor.constraint(equalTo: topAnchor, constant: 10.0)])

        let yetAnotherView = UIView()
        yetAnotherView.translatesAutoresizingMaskIntoConstraints = false
        yetAnotherView.backgroundColor = .white

        addSubview(yetAnotherView)
        NSLayoutConstraint.activate([yetAnotherView.widthAnchor.constraint(equalTo: widthAnchor),
                                     yetAnotherView.centerXAnchor.constraint(equalTo: centerXAnchor),
                                     yetAnotherView.heightAnchor.constraint(equalTo: labelsView.heightAnchor),
                                     yetAnotherView.topAnchor.constraint(equalTo: labelsView.bottomAnchor,
                                                                         constant: 10.0)])
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

An example usage output:


问:
How to implement vertical scrolling of a grid items within a grid in material ui?
How does one add vertical scrolling functionality to a grid container, such that its components can be vertically scrolled through if the height of the components exceeds some max?</p>

答:
Assuming you're using the latest MUI, it can be as simple as adding overflowY: 'scroll' and setting a maxHeight via the Grid container's sx prop (or its parent element).  For example:

```<code>      <Grid
        sx={{ overflowY: "scroll", maxHeight: "250px" }}
        container
        spacing={2}
      >
        ...
      </Grid>
</code>```

Working CodeSandbox: https://codesandbox.io/s/mui-5-scrollable-grid-gjxfq?file=/demo.js

Body:
Assuming you're using the latest MUI, it can be as simple as adding overflowY: 'scroll' and setting a maxHeight via the Grid container's sx prop (or its parent element).  For example:

      <Grid
        sx={{ overflowY: "scroll", maxHeight: "250px" }}
        container
        spacing={2}
      >
        ...
      </Grid>

Working CodeSandbox: https://codesandbox.io/s/mui-5-scrollable-grid-gjxfq?file=/demo.js


问:
Alternative way to populate selected value in HTML.Dropdownlistfor in MVC3.0
In the below code, though model.Title is holding the proper selected value, Its not getting set in the ddl, having id 'Title'.

Can I set the selected value in any other way? (like in document ready?)

```<code>    <td>
@Html.DropDownListFor(model => model.Title, Model.TitleList, !Model.IsTitleEditable ? (object)new { id = "Title", @disabled = "disabled", @style = "width:250px;" } : (object)new { id = "Title", @style = "width:250px" })
</td>
</code>```

In my controller the selectlist is getting filled as below:

```<code>model.TitleList = new SelectList(GetAllTitles(), "Code","Value");
</code>```

In this case as I m using the other overloaded method, how to set the selectedValue property of this selectList?

答:
If you create model.TitleList as an IEnumerable<SelectListItem>, where you set both Text an Value of the SelectListItems and the model.Value is one of the Values of the SelectListItems then everything should work. So:

```<code>model.TitleList = GetAllTitles()
            .ToList()
            .Select(i => new SelectListItem {
                                Value = i.Id.ToString(),
                                Text = i.Description });

model.Title = 5;
</code>```

and in your View:

```<code><td>
@Html.DropDownListFor(model => model.Title,
                      Model.TitleList,
                      !Model.IsTitleEditable
                         ? (object)new { @disabled = "disabled", @style = "width:250px;" }
                         : (object)new { @style = "width:250px" })
</td>
</code>```

Note that the id = "Title" is not necessary in the HtmlAttributes, the helper will create an Id for you.

EDIT
There is some confusion about the Selected property on the SelectListItem. This is NOT used when using a DropDownListFor, it in only used in a DropDownList. So for a DropDownListFor you set the propert of your model to the value you want selected (the model.Title = 5; mentioned above).

ContentLicense: CC BY-SA 3.0

Body:
In the below code, though model.Title is holding the proper selected value, Its not getting set in the ddl, having id 'Title'.

Can I set the selected value in any other way? (like in document ready?)

@Html.DropDownListFor(model => model.Title, Model.TitleList, !Model.IsTitleEditable ? (object)new { id = "Title", @disabled = "disabled", @style = "width:250px;" } : (object)new { id = "Title", @style = "width:250px" })

In my controller the selectlist is getting filled as below:

model.TitleList = new SelectList(GetAllTitles(), "Code","Value");

In this case as I m using the other overloaded method, how to set the selectedValue property of this selectList?

Body:
If you create model.TitleList as an IEnumerable<SelectListItem>, where you set both Text an Value of the SelectListItems and the model.Value is one of the Values of the SelectListItems then everything should work. So:

model.TitleList = GetAllTitles()
            .ToList()
            .Select(i => new SelectListItem {
                                Value = i.Id.ToString(),
                                Text = i.Description });

model.Title = 5;

and in your View:

<td>
@Html.DropDownListFor(model => model.Title,
                      Model.TitleList,
                      !Model.IsTitleEditable
                         ? (object)new { @disabled = "disabled", @style = "width:250px;" }
                         : (object)new { @style = "width:250px" })
</td>

Note that the id = "Title" is not necessary in the HtmlAttributes, the helper will create an Id for you.

EDIT
There is some confusion about the Selected property on the SelectListItem. This is NOT used when using a DropDownListFor, it in only used in a DropDownList. So for a DropDownListFor you set the propert of your model to the value you want selected (the model.Title = 5; mentioned above).


问:
Alternative to 'tensorflow.contrib' with tensorflow=2.0.0
I am using TensorFlow version=2.0.0, python version=3.7.9 and I was trying to import the following:

```<code>import tensorflow.contrib.layers as layers
</code>```

I get this error:

```<code>Exception has occurred: ModuleNotFoundError
No module named 'tensorflow.contrib'
</code>```

As I read in this thread, tensorflow.contrib doesn't exist in 2.0. Does anyone know an alternative to it? I am trying to upgrade my code from 1.0 to 2.0 as I don't want to use tf 1.0. I am using this package to build up a RNN cell.

答:
tf.contrib is deprecated in Tensorflow 2.x.

Replace import tensorflow.contrib.layers as layers

with

```<code>from tensorflow.keras.layers import RNN
</code>```

Body:
I am using TensorFlow version=2.0.0, python version=3.7.9 and I was trying to import the following:

import tensorflow.contrib.layers as layers

I get this error:

Exception has occurred: ModuleNotFoundError
No module named 'tensorflow.contrib'

As I read in this thread, tensorflow.contrib doesn't exist in 2.0. Does anyone know an alternative to it? I am trying to upgrade my code from 1.0 to 2.0 as I don't want to use tf 1.0. I am using this package to build up a RNN cell.

Body:
tf.contrib is deprecated in Tensorflow 2.x.

Replace import tensorflow.contrib.layers as layers

with

from tensorflow.keras.layers import RNN


问:
Alexa slot AMAZON.DATE handle dates without years
I am building an Alexa skill and using AMAZON.DATE slot type to get a date.

My problem is that when a user says a date without a year, Alexa processes it and returns the date string with a future date.

Example - Today is 2017-09-20, User asks Alexa about date 'Sixth June', Alexa returns 2018-06-06.

I want to use the closest past date instead of closest future dates, for the case when the user doesn't specify a year in the utterance. If the user specifies a year, I don't want to change the date year.

I can't handle this on AWS Lambda using Python, as Alexa sends the complete date string, no matter if the user provides the year or not, in the JSON body.

I don't know if it is even possible to handle such user inputs with Alexa. Is there something I can do about the AMAZON.DATE slot or some other way to handle such user utterances?

答:
After converting Alexa's slot input date string to a js date object, (probably with amazon-date-parser) the below could work</p>
```<code>if (dateobj > new Date()) {
      var currentMonth = new Date().getMonth()
      var dateMonth = dateobj.getMonth()
      var offset = dateMonth > currentMonth ? 1 : 0 //  if current month is to be set with past year use >=
      dateobj.setFullYear(new Date().getFullYear() - offset);
 }
</code>```

Body:
After converting Alexa's slot input date string to a js date object, (probably with amazon-date-parser) the below could work

if (dateobj > new Date()) {
      var currentMonth = new Date().getMonth()
      var dateMonth = dateobj.getMonth()
      var offset = dateMonth > currentMonth ? 1 : 0 //  if current month is to be set with past year use >=
      dateobj.setFullYear(new Date().getFullYear() - offset);
 }


问:
How do I set a option to selected using styled-components?
How do I use styled-component attributes to set the selected property of my styled option so that the option is selected within the select element depending on whether or not the isSelected property is truthy?

Right now I have this:

```<code>export const MyOption = styled.option.attrs(props => ({
    selected: {props.isSelected ? "selected" : ""}
})``;
</code>```

答:
What you've got there is actually almost exactly how you do it.

The only thing you need to change is that you are setting the attrs selected to an object using curly-brackets {} when you should be using normal brackets () to do the logic.

```<code>export const MyOption = styled.option.attrs(props => ({
    selected: (props.isSelected ? "selected" : ""),
 }))``;
</code>```

Body:
How do I use styled-component attributes to set the selected property of my styled option so that the option is selected within the select element depending on whether or not the isSelected property is truthy?

Right now I have this:

export const MyOption = styled.option.attrs(props => ({
    selected: {props.isSelected ? "selected" : ""}
})``;

Body:
What you've got there is actually almost exactly how you do it.

The only thing you need to change is that you are setting the attrs selected to an object using curly-brackets {} when you should be using normal brackets () to do the logic.

export const MyOption = styled.option.attrs(props => ({
    selected: (props.isSelected ? "selected" : ""),
 }))``;


问:
How I can import code from subdirectory into lib file?
My package has a structure like this.

```<code>src
├── block.rs
├── main.rs
└── traits
    ├── hashable.rs
    └── mod.rs
</code>```

In hashable.rs,

```<code>pub trait Hashable {
    fn bytes(&self) -> Vec<u8>;

    fn hash(&self) -> Vec<u8> {
        crypto_hash::digest(crypto_hash::Algorithm::SHA256, &self.bytes());
    }
}
</code>```

I tried to use mod to import Hashable trait from block.rs like this

```<code>mod traits;

type BlockHash = Vec<u8>;

pub struct Block {
    pub index: u32,
    pub timestamp: u128,
    pub payload: String,
    pub nonce: u64,
    pub hash: BlockHash,
    pub prev_hash: BlockHash,
}

impl Block {
    pub fn new(index: u32, timestamp: u128, payload: String, nonce: u64, prev_hash: BlockHash) -> Self {
        Block {
            index,
            timestamp,
            payload,
            nonce,
            hash: vec![0; 32],
            prev_hash,
        }
    }
}
</code>```

but this didn't work. I just can use this from main.rs file, so how I can use Hashable trait from block.rs file.

答:
When you say "This didn't work", you mean, you got an error message like?

error[E0583]: file not found for module `traits`
 --> src/block.rs:1:1
  |
1 | mod traits;
  | ^^^^^^^^^^^
  |
  = help: to create the module `traits`, create file "src/block/traits.rs" or "src/block/traits/mod.rs"

For more information about this error, try `rustc --explain E0583`.
```

If so, you have two options:

If your "traits" are actually logically a part of the "block"s, do move src/traits to a new folder src/block/traits

Or, more likely: Move the mod traits; declaration to src/main.rs, and add a use crate::traits; or use super::traits; to src/block.rs.

Body:
My package has a structure like this.

src
├── block.rs
├── main.rs
└── traits
    ├── hashable.rs
    └── mod.rs

In hashable.rs,

pub trait Hashable {
    fn bytes(&self) -> Vec<u8>;

    fn hash(&self) -> Vec<u8> {
        crypto_hash::digest(crypto_hash::Algorithm::SHA256, &self.bytes());
    }
}

I tried to use mod to import Hashable trait from block.rs like this

mod traits;

type BlockHash = Vec<u8>;

pub struct Block {
    pub index: u32,
    pub timestamp: u128,
    pub payload: String,
    pub nonce: u64,
    pub hash: BlockHash,
    pub prev_hash: BlockHash,
}

impl Block {
    pub fn new(index: u32, timestamp: u128, payload: String, nonce: u64, prev_hash: BlockHash) -> Self {
        Block {
            index,
            timestamp,
            payload,
            nonce,
            hash: vec![0; 32],
            prev_hash,
        }
    }
}

but this didn't work. I just can use this from main.rs file, so how I can use Hashable trait from block.rs file.

Body:
When you say "This didn't work", you mean, you got an error message like?

error[E0583]: file not found for module `traits`
 --> src/block.rs:1:1
  |
1 | mod traits;
  | ^^^^^^^^^^^
  |
  = help: to create the module `traits`, create file "src/block/traits.rs" or "src/block/traits/mod.rs"

For more information about this error, try `rustc --explain E0583`.

If so, you have two options:

If your "traits" are actually logically a part of the "block"s, do move src/traits to a new folder src/block/traits

Or, more likely: Move the mod traits; declaration to src/main.rs, and add a use crate::traits; or use super::traits; to src/block.rs.


问:
what does "NYI" refer to in the comments of OpenCascade source code
I noticed it first in BRepCheck_Analyzer.hxx:

class BRepCheck_Analyzer
{
public:

  DEFINE_STANDARD_ALLOC

  //! Constructs a shape validation object defined by the shape S.
  //! <S> is the  shape  to control.  <GeomControls>  If
  //! False   only topological informaions  are checked.
  //! The geometricals controls are
  //! For a Vertex :
  //! BRepCheck_InvalidToleranceValue  NYI
  //! For an Edge :
  //! BRepCheck_InvalidCurveOnClosedSurface,
  //! BRepCheck_InvalidCurveOnSurface,
  //! BRepCheck_InvalidSameParameterFlag,
  //! BRepCheck_InvalidToleranceValue  NYI
```

and my guess is "Not Yet Implemented", but it appears throughout the code base and some cases those make less sense for those references.  It comes up a lot in french comments, maybe it's something else in that language, or it's an author's initials?

For example, BRepCheck_InvalidToleranceValue is noted as NYI above, but it does seem to be used.

答:
I guess that you are pretty right in your assumptions - NYI over the code looks like somebody's acronym / nickname:

// NYI 971219 : on ne tient pas compte de l'orientation de E = arete-mere de l'interference I

...

// NYI XPU: 16-05-97: INTPATCH -> the parametrization of a point on a

// periodized curve is INSUFFICIENT : parVP on line can be either 0.

// or period.

Before wide adoption of modern code versioning systems like SVN/git, it was a common practice to put an acronym, bug number and date of modifications into the code.

These comments might be 20+ years old, so it would be difficult and not very  useful to figure out who might be a real author.

Body:
I noticed it first in BRepCheck_Analyzer.hxx:

class BRepCheck_Analyzer
{
public:

  DEFINE_STANDARD_ALLOC

  //! Constructs a shape validation object defined by the shape S.
  //! <S> is the  shape  to control.  <GeomControls>  If
  //! False   only topological informaions  are checked.
  //! The geometricals controls are
  //! For a Vertex :
  //! BRepCheck_InvalidToleranceValue  NYI
  //! For an Edge :
  //! BRepCheck_InvalidCurveOnClosedSurface,
  //! BRepCheck_InvalidCurveOnSurface,
  //! BRepCheck_InvalidSameParameterFlag,
  //! BRepCheck_InvalidToleranceValue  NYI

and my guess is "Not Yet Implemented", but it appears throughout the code base and some cases those make less sense for those references.  It comes up a lot in french comments, maybe it's something else in that language, or it's an author's initials?

For example, BRepCheck_InvalidToleranceValue is noted as NYI above, but it does seem to be used.


问:
Learning about Computer Vision
I am really intrigued by the field of computer vision and the potential it has. Are there any examples (preferably implemented in .NET) which I can study along with a reference book?</p>

答:
OpenCV (Open Computer Vision) is the most popular library, and it has been wrapped for C#:

http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx

Some discussion about this wrapper and the library in general is here:

http://coolthingoftheday.blogspot.com/2008/08/opencv-open-source-computer-vision-for.html

-Adam

OwnerDisplayName: Ali Kazmi

ContentLicense: CC BY-SA 2.5

Title: Learning about Computer Vision

LastEditorDisplayName: Gortok

OwnerDisplayName: Adam Davis


问:
LINQ vs context.entity.Where()
Are these two blocks exactly the same? Does one have any advantage over the other?</p>

```<code>        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }
</code>```

答:
<s>Well the first selects from context.Table1, the second selects from context.LINTE. So they select from totally different collections.

Also the first selects on a UserCode column and the second on a CodeUsager column..
</s>

Apart from that (is the first just a translation of the second and you forgot to translate the second) the code is the same. The C# compiler will just translate the second query into the first one and they will behave identically.

Title: LINQ vs context.entity.Where()

Body:
Are these two blocks exactly the same? Does one have any advantage over the other?

        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }


问:
Android RadioButton button not appearing in editor
Here is my activity_main.xml :

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/white">
    <include layout="@layout/toolbar"></include>

    <RadioGroup
        android:id="@+id/choixPersonnage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/boutonGuerrier"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/personnage1"
            android:textSize="20sp"/>

        <RadioButton
            android:id="@+id/boutonMage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/personnage2"
            android:textSize="20sp"/>
    </RadioGroup>

</LinearLayout>
</code>```

And here is what appears in my editor:

Both button texts work, but the RadioButton buttons just do not appear, nor do they take space. They are just not there...

In all the Radio Button problems I found, no one seemed to have the same problem I do. Anyone could help me out here with this basic thing?

答: I Just Copy Your Code And It's Working Fine

Body:
Here is my activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/white">
    <include layout="@layout/toolbar"></include>

    <RadioGroup
        android:id="@+id/choixPersonnage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/boutonGuerrier"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/personnage1"
            android:textSize="20sp"/>

        <RadioButton
            android:id="@+id/boutonMage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/personnage2"
            android:textSize="20sp"/>
    </RadioGroup>

</LinearLayout>

And here is what appears in my editor:

Both button texts work, but the RadioButton buttons just do not appear, nor do they take space. They are just not there...

In all the Radio Button problems I found, no one seemed to have the same problem I do. Anyone could help me out here with this basic thing?


问:
Django How to check a request is Ajax
The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header.</p>

答:
```<code>def is_ajax(request):
  return request.headers.get('x-requested-with') == 'XMLHttpRequest'
</code>```

Title: Django How to check a request is Ajax


问:
Why Allow ADL lookup for template name binding?
I Know for dependent names, the binding must be deferred to point of instantiation.
Think about the following code:

```<code>#include <iostream>

using namespace std;

template <class T>
void g(T a)
{
    f(a);
}

namespace MyNamespace
{
    class X{};
    void f(X) {  cout << "f(X)\n"; }
}

void f(int i) { cout << "f(int)\n"; }

int main()
{
    g(MyNamespace::X{});   //1. print f(x)
    //g(1);                //2. not compile
    return 0;
}
</code>```

for 1, all compilers I tested(VC++, gcc, clang) could find MyNamespace::f(X) by ADL. That's fine, it is in accordance with standard. However, gcc and clang cannot compile 2. because the standard does not allow directly searching functions in the instantiation context. That's the standard requires (Fine, vc++ violates the standard in this respect).

I know the standard does not allow searching functions in template instantiation context is a safeguard to ODR. However, why does it allow ADL examines function declarations that are visible from the template instantiation context? Will this cause violation of ODR as well? Consider the follow:

```<code>//ff.h
#include <iostream>

namespace N
{
    class X {};
    int g(X, int i);
}

template<typename T>
double ff(T t, double d)
{
    return g(t, d);
}

//ff.cpp
#include "ff.h"

int N::g(X, int i) { std::cout << "g(X,int)" << std::endl; return i; }

double x1 = ff(N::X{}, 1.1);

//main.cpp
#include "ff.h"

namespace N
{
    double g(X, double d) { std::cout << "g(X,double)" << std::endl; return d; }
}

auto x2 = ff(N::X{}, 2.2);

int main()
{
    extern double x1;
    std::cout<<"x1 = " << x1 << std::endl;
    std::cout << "x2 = " << x2 << std::endl;
    return 0;
}
</code>```

There are two places that instantiate the function template ff： ff(N::X, double), one in ff.cpp, one in main.cpp. In main.cpp, the namespace is changed and a better matching function double g(X, double) is added in main.cpp before the instantiation of ff. Therefore, the instantiation in main.cpp could pick up this better matching functiong, anyway both g are equal in the scope of main.cpp. But the instantiation in ff.cpp could only choose the first g declared in ff.h. This obviously violates ODR, though I tested all 3 compilers pick up int g(X, int), but that seems the compilers are smart enough to detect this illness in the generated code and optimized out the duplicated specialization. The compilers are not obliged to catch problems of this kind. So why standard allows ADL in this case, that could lead to potential violation to ODR?

答: Your main.cpp does something untoward by defining a new overload for a function taking N::X in that namespace; this is usually considered part of the interface of N::X and should be declared whereever N::X is.  That logic doesn't apply to the normal lookup, since something declared in the global namespace after the template can't reasonably be assumed to be desired by the template author.

Body:
I Know for dependent names, the binding must be deferred to point of instantiation.
Think about the following code:

#include <iostream>

using namespace std;

template <class T>
void g(T a)
{
    f(a);
}

namespace MyNamespace
{
    class X{};
    void f(X) {  cout << "f(X)\n"; }
}

void f(int i) { cout << "f(int)\n"; }

int main()
{
    g(MyNamespace::X{});   //1. print f(x)
    //g(1);                //2. not compile
    return 0;
}

for 1, all compilers I tested(VC++, gcc, clang) could find MyNamespace::f(X) by ADL. That's fine, it is in accordance with standard. However, gcc and clang cannot compile 2. because the standard does not allow directly searching functions in the instantiation context. That's the standard requires (Fine, vc++ violates the standard in this respect).

I know the standard does not allow searching functions in template instantiation context is a safeguard to ODR. However, why does it allow ADL examines function declarations that are visible from the template instantiation context? Will this cause violation of ODR as well? Consider the follow:

//ff.h
#include <iostream>

namespace N
{
    class X {};
    int g(X, int i);
}

template<typename T>
double ff(T t, double d)
{
    return g(t, d);
}

//ff.cpp
#include "ff.h"

int N::g(X, int i) { std::cout << "g(X,int)" << std::endl; return i; }

double x1 = ff(N::X{}, 1.1);

//main.cpp
#include "ff.h"

namespace N
{
    double g(X, double d) { std::cout << "g(X,double)" << std::endl; return d; }
}

auto x2 = ff(N::X{}, 2.2);

int main()
{
    extern double x1;
    std::cout<<"x1 = " << x1 << std::endl;
    std::cout << "x2 = " << x2 << std::endl;
    return 0;
}

There are two places that instantiate the function template ff： ff(N::X, double), one in ff.cpp, one in main.cpp. In main.cpp, the namespace is changed and a better matching function double g(X, double) is added in main.cpp before the instantiation of ff. Therefore, the instantiation in main.cpp could pick up this better matching functiong, anyway both g are equal in the scope of main.cpp. But the instantiation in ff.cpp could only choose the first g declared in ff.h. This obviously violates ODR, though I tested all 3 compilers pick up int g(X, int), but that seems the compilers are smart enough to detect this illness in the generated code and optimized out the duplicated specialization. The compilers are not obliged to catch problems of this kind. So why standard allows ADL in this case, that could lead to potential violation to ODR?


问:
What are the steps involved in creating a Tensorflow.lite model?
What are the steps involved in creating and training a Tensorflow model to use in an Android app ?

Below is what I think needs to be done in my scenario (based on what I've researched)

I know I need to gather training images of various car parts and label them using  labelImg . Then split into training and testing folders.

Create and train the model .

Export it to a .tflite format to later be used in the Android app.

Questions.

What resources can/should I use ?

The biggest one would be, what coding examples or coding resources should I follow to create the TF Model ?

I would highly appreciate being pointed in the right direction as to where I should start.

答:
To answer your question:
Can I write the above training model in Python locally on my PC or do I have to use Google colab?
--> You can try both seperately, both work.
What resources can/should I use ?
--> If your refering to GPU you can use that through colab [runtime->change runtime->hardware/device and GPU]
The biggest one would be, what coding examples or coding resources should I follow to create the TF Model ?
-->Please refer to this link and let us know [https://www.tensorflow.org/lite/examples]</p>


问:
android - MotionEvent.ACTION_UP is never called
I want to do some works while the user hold his hand on a view and stop it when he release it. My code is below:

```<code>viewHolder.plus.setOnTouchListener(new View.OnTouchListener() {
        private Handler mHandler;
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if(mHandler==null)
                        mHandler = new Handler();
                    mHandler.postDelayed(mAction, 500);
                    return true;
                case MotionEvent.ACTION_UP:
                    Log.v("this","cancel");
                    if (mHandler != null) {
                        mHandler.removeCallbacks(mAction);
                        mHandler = null;
                        Log.v("this", "c cancel");
                    }
                    break;
            }
            return false;
        }

        Runnable mAction = new Runnable() {
            @Override public void run() {
                ChangeTedad(item.getid(), "plus");
                Log.v("this","Cc");
                mHandler.postDelayed(this, 500);
            }
        };

    });
</code>```

the problem is , ACTION_UP is never called and the runnable stays run forever .

How to stop the runnable when the user un touch it ?

答:
You can also add your ACTION_UP logic codes to ACTION_CANCEL, cause of, if you touch the view and release it , it will call to ACTION_UP, but if you are at view pressed state and you move even 1 Pixel, it will NOT call ACTION_UP, and call only ACTION_CANCEL. Hope this will help for you.

```<code>viewHolder.plus.setOnTouchListener(new View.OnTouchListener() {
        private Handler mHandler;
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if(mHandler==null)
                        mHandler = new Handler();
                    mHandler.postDelayed(mAction, 500);
                    return true;
                case MotionEvent.ACTION_UP:
                    Log.v("this","cancel");
                    if (mHandler != null) {
                        mHandler.removeCallbacks(mAction);
                        mHandler = null;
                        Log.v("this", "c cancel");
                    }
                    break;
                case MotionEvent.ACTION_CANCEL:
                    Log.v("this","cancel");
                    if (mHandler != null) {
                        mHandler.removeCallbacks(mAction);
                        mHandler = null;
                        Log.v("this", "c cancel");
                    }
                    break;
            }
            return false;
        }

        Runnable mAction = new Runnable() {
            @Override public void run() {
                ChangeTedad(item.getid(), "plus");
                Log.v("this","Cc");
                mHandler.postDelayed(this, 500);
            }
        };

    });
</code>```

Body:
I want to do some works while the user hold his hand on a view and stop it when he release it. My code is below:

viewHolder.plus.setOnTouchListener(new View.OnTouchListener() {
        private Handler mHandler;
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if(mHandler==null)
                        mHandler = new Handler();
                    mHandler.postDelayed(mAction, 500);
                    return true;
                case MotionEvent.ACTION_UP:
                    Log.v("this","cancel");
                    if (mHandler != null) {
                        mHandler.removeCallbacks(mAction);
                        mHandler = null;
                        Log.v("this", "c cancel");
                    }
                    break;
            }
            return false;
        }

        Runnable mAction = new Runnable() {
            @Override public void run() {
                ChangeTedad(item.getid(), "plus");
                Log.v("this","Cc");
                mHandler.postDelayed(this, 500);
            }
        };

    });

the problem is , ACTION_UP is never called and the runnable stays run forever .

How to stop the runnable when the user un touch it ?

Body:
You can also add your ACTION_UP logic codes to ACTION_CANCEL, cause of, if you touch the view and release it , it will call to ACTION_UP, but if you are at view pressed state and you move even 1 Pixel, it will NOT call ACTION_UP, and call only ACTION_CANCEL. Hope this will help for you.

viewHolder.plus.setOnTouchListener(new View.OnTouchListener() {
        private Handler mHandler;
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if(mHandler==null)
                        mHandler = new Handler();
                    mHandler.postDelayed(mAction, 500);
                    return true;
                case MotionEvent.ACTION_UP:
                    Log.v("this","cancel");
                    if (mHandler != null) {
                        mHandler.removeCallbacks(mAction);
                        mHandler = null;
                        Log.v("this", "c cancel");
                    }
                    break;
                case MotionEvent.ACTION_CANCEL:
                    Log.v("this","cancel");
                    if (mHandler != null) {
                        mHandler.removeCallbacks(mAction);
                        mHandler = null;
                        Log.v("this", "c cancel");
                    }
                    break;
            }
            return false;
        }

        Runnable mAction = new Runnable() {
            @Override public void run() {
                ChangeTedad(item.getid(), "plus");
                Log.v("this","Cc");
                mHandler.postDelayed(this, 500);
            }
        };

    });


问:
Cannot render elements from each block
I'm trying to render msg from all_msgs array.

  {#each all_msgs as msg}

{msg}

  {/each}

```

I can see the numbers can be rendered as html text. But couldn't render other texts when all_msgs is updated by the two subscribe methods. I can see all_msgs in the console having the texts but can't be seen in html. The o/p of the screen and console.log of all_msgs is also shared.

答:
Solved it: reactivity is assignment based. Below code works:

  {#each all_msgs as msg}

{msg}

  {/each}

```

Title: Cannot render elements from each block

Body:
I'm trying to render msg from all_msgs array.

  {#each all_msgs as msg}

{msg}

  {/each}

I can see the numbers can be rendered as html text. But couldn't render other texts when all_msgs is updated by the two subscribe methods. I can see all_msgs in the console having the texts but can't be seen in html. The o/p of the screen and console.log of all_msgs is also shared.

Body:
Solved it: reactivity is assignment based. Below code works:

<script>
  import { sender_msgs } from "../var_store";
  import { receiver_msgs } from "../var_store";
  let all_msgs = [];
  // $: msgs = all_msgs;
  sender_msgs.subscribe((e) => {
    all_msgs.push(`Sender: ${e.slice(-1)[0]}`);
    all_msgs = all_msgs;
  });
  receiver_msgs.subscribe((e) => {
    all_msgs.push(`Receiver: ${e.slice(-1)[0]}`);
    all_msgs = all_msgs;
  });
</script>

<div class="chat-window">
  {#each all_msgs as msg}
    <div>{msg}</div>
  {/each}
</div>

<style>
  .chat-window {
    width: 500px;
    border: 1px solid #000;
  }
</style>


问:
How to make code that runs a process once per file parallel?
```<code>import cv2
import time
import glob

img_array = []
start_time = time.time()
for files in glob.glob("C:/pictures/*.jpg"):
    a = cv2.imread(files)
    img_array.append(a)
    height, width,layer = a.shape
    size = (width, height)
video = cv2.VideoWriter('C:/pictures/project.avi', cv2.VideoWriter_fourcc(*'mp4v'), 15, size)

for value in range(len(img_array)):
    video.write(img_array[value])
video.release()
print("--- %s seconds ---" % (time.time() - start_time))
</code>```

This is the serial code I made first. The program is merging several images and making video using cv2 library.

```<code>import cv2
import time
import glob
from multiprocessing import Process
img_array = []
def convert():
    start_time = time.time()
    for files in glob.glob("C:/pictures/*.jpg"):
        a = cv2.imread(files)
        img_array.append(a)
        height, width,layer = a.shape
        size = (width, height)
        video = cv2.VideoWriter('C:/pictures/project.avi', cv2.VideoWriter_fourcc(*'mp4v'), 15, size)
    for value in range(len(img_array)):
        video.write(img_array[value])
    video.release()
    print("--- %s seconds ---" % (time.time() - start_time))
if __name__ == '__main__':
    procs =[]
    proc = Process(target = convert, args='')
    procs.append(proc)
    proc.start()
    for proc in procs:
        proc.join()
</code>```

And this is the parallel version of the upper serial code.
I used multiprocessing-Process. But parallel should be faster than serial but my code, parallel version is usually slower or similar to serial. I am even not sure my parallel code is the correct way to convert my serial code to parallel.
If anyone could help me, I would really appreciate it.

```<code>import cv2
import time
import glob
import multiprocessing

shape = 1000,1000
img_array = []

def convert(files):
    a = cv2.imread(files)
    resized = cv2.resize(a,shape)
    img_array.append(resized)
    video = cv2.VideoWriter('C:/pictures/project.avi', cv2.VideoWriter_fourcc(*'mp4v'), 15, shape)

    for i in range(len(img_array)):
        video.write(img_array[i])
    video.release()

if __name__ == '__main__':
    start_time = time.time()
    p = multiprocessing.Pool()
    for files in glob.glob("C:/pictures/*.jpg"):
        p.apply_async(convert, [files])
    p.close()
    p.join()
    print("--- %s seconds ---" % (time.time() - start_time))
</code>```

This is code for the comment below.

答:
Below is an example of my multiprocessing code. The following code processes multiple files at once within a specified folder. Simply, create a folder where you'd like to dump all your files for parallel processing. I named my folder, "Folder." It is also important to create another folder for where your test file will live for initializing the function. This file can be an excel test dummy. For this example, I created a folder titled, "mastertemp" and added a test file titled, "mastertemp.xlsx"

Also, with the code I provided, the multiprocessing speed is dependent on the number of CPUs available. I generally use Google Cloud - AI Notebooks. I'm able to set a specified number of CPUs. For instance, if I have 8 CPUs, the code will process 8 files simultaneously until there are no more files to process.

I hope this helps out!

```<code>import multiprocessing
import glob
from pathlib import Path
import pandas as pd
import os
import time

# MULTI-PROCESS

# created a 'mastertemp' folder and inserted a test excel file to launch the parallel process

file = 'mastertemp/mastertemp.xlsx'   # add a test file and set file equal to "mastertemp.xlsx"; initializing
def process(file):
    '''
    write your code here; what do you want to do with the files? Below, I simply am reading to df

    '''
    df = pd.read_excel(file)
    print(file)

p = multiprocessing.Pool()

# created a 'Folder' titled folder where all excel files will live
# f = excel files
for f in glob.glob("Folder/*.xlsx"):
    # launch a process for each file (ish).
    # The result will be approximately one process per CPU core available.
    p.apply_async(process, [f])
p.close()
p.join() # Wait for all child processes to close.
</code>```

Body:
import cv2
import time
import glob

img_array = []
start_time = time.time()
for files in glob.glob("C:/pictures/*.jpg"):
    a = cv2.imread(files)
    img_array.append(a)
    height, width,layer = a.shape
    size = (width, height)
video = cv2.VideoWriter('C:/pictures/project.avi', cv2.VideoWriter_fourcc(*'mp4v'), 15, size)

for value in range(len(img_array)):
    video.write(img_array[value])
video.release()
print("--- %s seconds ---" % (time.time() - start_time))

This is the serial code I made first. The program is merging several images and making video using cv2 library.

import cv2
import time
import glob
from multiprocessing import Process
img_array = []
def convert():
    start_time = time.time()
    for files in glob.glob("C:/pictures/*.jpg"):
        a = cv2.imread(files)
        img_array.append(a)
        height, width,layer = a.shape
        size = (width, height)
        video = cv2.VideoWriter('C:/pictures/project.avi', cv2.VideoWriter_fourcc(*'mp4v'), 15, size)
    for value in range(len(img_array)):
        video.write(img_array[value])
    video.release()
    print("--- %s seconds ---" % (time.time() - start_time))
if __name__ == '__main__':
    procs =[]
    proc = Process(target = convert, args='')
    procs.append(proc)
    proc.start()
    for proc in procs:
        proc.join()

And this is the parallel version of the upper serial code.
I used multiprocessing-Process. But parallel should be faster than serial but my code, parallel version is usually slower or similar to serial. I am even not sure my parallel code is the correct way to convert my serial code to parallel.
If anyone could help me, I would really appreciate it.

import cv2
import time
import glob
import multiprocessing

shape = 1000,1000
img_array = []

def convert(files):
    a = cv2.imread(files)
    resized = cv2.resize(a,shape)
    img_array.append(resized)
    video = cv2.VideoWriter('C:/pictures/project.avi', cv2.VideoWriter_fourcc(*'mp4v'), 15, shape)

    for i in range(len(img_array)):
        video.write(img_array[i])
    video.release()

if __name__ == '__main__':
    start_time = time.time()
    p = multiprocessing.Pool()
    for files in glob.glob("C:/pictures/*.jpg"):
        p.apply_async(convert, [files])
    p.close()
    p.join()
    print("--- %s seconds ---" % (time.time() - start_time))

This is code for the comment below.

Body:
Below is an example of my multiprocessing code. The following code processes multiple files at once within a specified folder. Simply, create a folder where you'd like to dump all your files for parallel processing. I named my folder, "Folder." It is also important to create another folder for where your test file will live for initializing the function. This file can be an excel test dummy. For this example, I created a folder titled, "mastertemp" and added a test file titled, "mastertemp.xlsx"

Also, with the code I provided, the multiprocessing speed is dependent on the number of CPUs available. I generally use Google Cloud - AI Notebooks. I'm able to set a specified number of CPUs. For instance, if I have 8 CPUs, the code will process 8 files simultaneously until there are no more files to process.

I hope this helps out!

import multiprocessing
import glob
from pathlib import Path
import pandas as pd
import os
import time

# MULTI-PROCESS

# created a 'mastertemp' folder and inserted a test excel file to launch the parallel process

file = 'mastertemp/mastertemp.xlsx'   # add a test file and set file equal to "mastertemp.xlsx"; initializing
def process(file):
    '''
    write your code here; what do you want to do with the files? Below, I simply am reading to df

    '''
    df = pd.read_excel(file)
    print(file)

p = multiprocessing.Pool()

# created a 'Folder' titled folder where all excel files will live
# f = excel files
for f in glob.glob("Folder/*.xlsx"):
    # launch a process for each file (ish).
    # The result will be approximately one process per CPU core available.
    p.apply_async(process, [f])
p.close()
p.join() # Wait for all child processes to close.


问:
How can you monkeypatch an input call from a nested function?
I am a novice python coder on my greatest of days.  I am in a class and using pytest to wrap my head around TDD.  Some of the functions in this code (based off of Dane Hillard's Bark) calls a function that prompts the user for input.  I need to automate the input of the nested function.

```<code>def get_user_input(label, required=True):
    value = input(f"{label}: ") or None
    while required and not value:
        value = input(f"{label}: ") or None
    return value

def get_new_bookmark_data():
    return {
        "title": get_user_input("Title"),
        "url": get_user_input("URL"),
        "notes": get_user_input("Notes", required=False),
    }
</code>```

I can't even wrap my head around how I should deal with test_get_user_input() much less the bookmark.

Here are some of the things I have tried:

```<code>def test_get_user_input(monkeypatch):
    uInput = 'a'
    monkeypatch.setattr('sys.stdin', uInput)
    assert barky.get_user_input() == 'A'
</code>```

I'm just not there yet.  Here is my repo: https://github.com/impilcature/Green-CIDM6330

答:
Mocking is done the same way in pytest as in unittest by using unittest.mock.patch, in your case by mocking the input function that lives in buildins. So you can just do:

from unittest.mock import patch

@patch("builtins.input")
def test_get_user_input(mocked):
    mocked.return_value = "a"
    assert get_user_input('foo') == 'a'
```
<p>That mocks <code>input</code> regardless of where it is called, so it doesn't matter if you call it in the tested function or in a function called by the tested function.</p>
<p>To be more consistent with the pytest way, you can install the pytest plugin pytest-mock which provides the <code>mocker</code> fixture, which is a wrapper around <code>unittest.mock</code>:</p>
<pre class="lang-py prettyprint-override"><code>def test_get_user_input(mocker):
    mocker.patch('builtins.input', return_value='a')
    assert get_user_input('foo') == 'a'
</code>```

If you want to test more than one input, you can use side_effect to provide subsequent inputs (here using the mocker fixture):

def test_get_new_bookmark_data(mocker):
    mocker.patch('builtins.input',
                 side_effect=["Some title", "Some URL", "Some notes"])
    assert get_new_bookmark_data() == {
        "title": "Some title",
        "url": "Some URL",
        "notes": "Some notes"
    }
```

Body:
I am a novice python coder on my greatest of days.  I am in a class and using pytest to wrap my head around TDD.  Some of the functions in this code (based off of Dane Hillard's Bark) calls a function that prompts the user for input.  I need to automate the input of the nested function.

def get_user_input(label, required=True):
    value = input(f"{label}: ") or None
    while required and not value:
        value = input(f"{label}: ") or None
    return value

def get_new_bookmark_data():
    return {
        "title": get_user_input("Title"),
        "url": get_user_input("URL"),
        "notes": get_user_input("Notes", required=False),
    }

I can't even wrap my head around how I should deal with test_get_user_input() much less the bookmark.

Here are some of the things I have tried:

def test_get_user_input(monkeypatch):
    uInput = 'a'
    monkeypatch.setattr('sys.stdin', uInput)
    assert barky.get_user_input() == 'A'

I'm just not there yet.  Here is my repo: https://github.com/impilcature/Green-CIDM6330

Body:
Mocking is done the same way in pytest as in unittest by using unittest.mock.patch, in your case by mocking the input function that lives in buildins. So you can just do:

from unittest.mock import patch

@patch("builtins.input")
def test_get_user_input(mocked):
    mocked.return_value = "a"
    assert get_user_input('foo') == 'a'

That mocks input regardless of where it is called, so it doesn't matter if you call it in the tested function or in a function called by the tested function.

To be more consistent with the pytest way, you can install the pytest plugin pytest-mock which provides the mocker fixture, which is a wrapper around unittest.mock:

def test_get_user_input(mocker):
    mocker.patch('builtins.input', return_value='a')
    assert get_user_input('foo') == 'a'

If you want to test more than one input, you can use side_effect to provide subsequent inputs (here using the mocker fixture):

def test_get_new_bookmark_data(mocker):
    mocker.patch('builtins.input',
                 side_effect=["Some title", "Some URL", "Some notes"])
    assert get_new_bookmark_data() == {
        "title": "Some title",
        "url": "Some URL",
        "notes": "Some notes"
    }