问:
Show SearchBuilder Form
DataTables website have the example (link below) for searchbuilder extension. In the example when button is clicked, it shows search Builder form (as shown in the image below).

https://datatables.net/extensions/searchbuilder/examples/initialisation/button.html

When I try to replicate, I am getting the box below. If I will click on "Add Condition", I will have the same form but it's an additional step to reach there.

$(document).ready(function() {
  $('#example').DataTable({
    buttons: [{
      extend: 'searchBuilder'
    }],
    language: {
      searchBuilder: {
        data: 'Column',
        add: 'Add Condition',
        button: {
          0: ' Filters',
          _: ' Filters (%d)'
        }
      }
    },
    dom: 'Bfrtip'
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js"></script>
  <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap4.min.js"></script>
  <script src="https://cdn.datatables.net/searchbuilder/1.3.0/js/dataTables.searchBuilder.min.js"></script>
  <script src="https://cdn.datatables.net/searchbuilder/1.3.0/js/searchBuilder.bootstrap4.min.js"></script>
  <script src="https://cdn.datatables.net/datetime/1.1.1/js/dataTables.dateTime.min.js"></script>
  <script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>

  <link href='https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css' rel='stylesheet' />
  <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css' rel='stylesheet' />
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap4.min.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/searchbuilder/1.3.0/css/searchBuilder.bootstrap4.min.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.1.1/css/dataTables.dateTime.min.css" />

</head>

<table id="example" class="table table-striped table-bordered nowrap" style="width:100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>61</td>
      <td>2011/04/25</td>
      <td>$320,800</td>
    </tr>
    <tr>
      <td>Garrett Winters</td>
      <td>Accountant</td>
      <td>Tokyo</td>
      <td>63</td>
      <td>2011/07/25</td>
      <td>$170,750</td>
    </tr>
    <tr>
      <td>Ashton Cox</td>
      <td>Junior Technical Author</td>
      <td>San Francisco</td>
      <td>66</td>
      <td>2009/01/12</td>
      <td>$86,000</td>
    </tr>
    <tr>
      <td>Cedric Kelly</td>
      <td>Senior Javascript Developer</td>
      <td>Edinburgh</td>
      <td>22</td>
      <td>2012/03/29</td>
      <td>$433,060</td>
    </tr>
    <tr>
      <td>Airi Satou</td>
      <td>Accountant</td>
      <td>Tokyo</td>
      <td>33</td>
      <td>2008/11/28</td>
      <td>$162,700</td>
    </tr>
    <tr>
      <td>Brielle Williamson</td>
      <td>Integration Specialist</td>
      <td>New York</td>
      <td>61</td>
      <td>2012/12/02</td>
      <td>$372,000</td>
    </tr>
    <tr>
      <td>Herrod Chandler</td>
      <td>Sales Assistant</td>
      <td>San Francisco</td>
      <td>59</td>
      <td>2012/08/06</td>
      <td>$137,500</td>
    </tr>
    <tr>
      <td>Rhona Davidson</td>
      <td>Integration Specialist</td>
      <td>Tokyo</td>
      <td>55</td>
      <td>2010/10/14</td>
      <td>$327,900</td>
    </tr>
    <tr>
      <td>Colleen Hurst</td>
      <td>Javascript Developer</td>
      <td>San Francisco</td>
      <td>39</td>
      <td>2009/09/15</td>
      <td>$205,500</td>
    </tr>
    <tr>
      <td>Sonya Frost</td>
      <td>Software Engineer</td>
      <td>Edinburgh</td>
      <td>23</td>
      <td>2008/12/13</td>
      <td>$103,600</td>
    </tr>
    <tr>
      <td>Jena Gaines</td>
      <td>Office Manager</td>
      <td>London</td>
      <td>30</td>
      <td>2008/12/19</td>
      <td>$90,560</td>
    </tr>
    <tr>
      <td>Quinn Flynn</td>
      <td>Support Lead</td>
      <td>Edinburgh</td>
      <td>22</td>
      <td>2013/03/03</td>
      <td>$342,000</td>
    </tr>
    <tr>
      <td>Charde Marshall</td>
      <td>Regional Director</td>
      <td>San Francisco</td>
      <td>36</td>
      <td>2008/10/16</td>
      <td>$470,600</td>
    </tr>
    <tr>
      <td>Haley Kennedy</td>
      <td>Senior Marketing Designer</td>
      <td>London</td>
      <td>43</td>
      <td>2012/12/18</td>
      <td>$313,500</td>
    </tr>
    <tr>
      <td>Tatyana Fitzpatrick</td>
      <td>Regional Director</td>
      <td>London</td>
      <td>19</td>
      <td>2010/03/17</td>
      <td>$385,750</td>
    </tr>
    <tr>
      <td>Michael Silva</td>
      <td>Marketing Designer</td>
      <td>London</td>
      <td>66</td>
      <td>2012/11/27</td>
      <td>$198,500</td>
    </tr>
    <tr>
      <td>Paul Byrd</td>
      <td>Chief Financial Officer (CFO)</td>
      <td>New York</td>
      <td>64</td>
      <td>2010/06/09</td>
      <td>$725,000</td>
    </tr>
    <tr>
      <td>Gloria Little</td>
      <td>Systems Administrator</td>
      <td>New York</td>
      <td>59</td>
      <td>2009/04/10</td>
      <td>$237,500</td>
    </tr>
    <tr>
      <td>Bradley Greer</td>
      <td>Software Engineer</td>
      <td>London</td>
      <td>41</td>
      <td>2012/10/13</td>
      <td>$132,000</td>
    </tr>
    <tr>
      <td>Dai Rios</td>
      <td>Personnel Lead</td>
      <td>Edinburgh</td>
      <td>35</td>
      <td>2012/09/26</td>
      <td>$217,500</td>
    </tr>
    <tr>
      <td>Jenette Caldwell</td>
      <td>Development Lead</td>
      <td>New York</td>
      <td>30</td>
      <td>2011/09/03</td>
      <td>$345,000</td>
    </tr>
    <tr>
      <td>Yuri Berry</td>
      <td>Chief Marketing Officer (CMO)</td>
      <td>New York</td>
      <td>40</td>
      <td>2009/06/25</td>
      <td>$675,000</td>
    </tr>
    <tr>
      <td>Caesar Vance</td>
      <td>Pre-Sales Support</td>
      <td>New York</td>
      <td>21</td>
      <td>2011/12/12</td>
      <td>$106,450</td>
    </tr>
    <tr>
      <td>Doris Wilder</td>
      <td>Sales Assistant</td>
      <td>Sydney</td>
      <td>23</td>
      <td>2010/09/20</td>
      <td>$85,600</td>
    </tr>
    <tr>
      <td>Angelica Ramos</td>
      <td>Chief Executive Officer (CEO)</td>
      <td>London</td>
      <td>47</td>
      <td>2009/10/09</td>
      <td>$1,200,000</td>
    </tr>
    <tr>
      <td>Gavin Joyce</td>
      <td>Developer</td>
      <td>Edinburgh</td>
      <td>42</td>
      <td>2010/12/22</td>
      <td>$92,575</td>
    </tr>
    <tr>
      <td>Jennifer Chang</td>
      <td>Regional Director</td>
      <td>Singapore</td>
      <td>28</td>
      <td>2010/11/14</td>
      <td>$357,650</td>
    </tr>
    <tr>
      <td>Brenden Wagner</td>
      <td>Software Engineer</td>
      <td>San Francisco</td>
      <td>28</td>
      <td>2011/06/07</td>
      <td>$206,850</td>
    </tr>
    <tr>
      <td>Fiona Green</td>
      <td>Chief Operating Officer (COO)</td>
      <td>San Francisco</td>
      <td>48</td>
      <td>2010/03/11</td>
      <td>$850,000</td>
    </tr>
    <tr>
      <td>Shou Itou</td>
      <td>Regional Marketing</td>
      <td>Tokyo</td>
      <td>20</td>
      <td>2011/08/14</td>
      <td>$163,000</td>
    </tr>
    <tr>
      <td>Michelle House</td>
      <td>Integration Specialist</td>
      <td>Sydney</td>
      <td>37</td>
      <td>2011/06/02</td>
      <td>$95,400</td>
    </tr>
    <tr>
      <td>Suki Burks</td>
      <td>Developer</td>
      <td>London</td>
      <td>53</td>
      <td>2009/10/22</td>
      <td>$114,500</td>
    </tr>
    <tr>
      <td>Prescott Bartlett</td>
      <td>Technical Author</td>
      <td>London</td>
      <td>27</td>
      <td>2011/05/07</td>
      <td>$145,000</td>
    </tr>
    <tr>
      <td>Gavin Cortez</td>
      <td>Team Leader</td>
      <td>San Francisco</td>
      <td>22</td>
      <td>2008/10/26</td>
      <td>$235,500</td>
    </tr>
    <tr>
      <td>Martena Mccray</td>
      <td>Post-Sales support</td>
      <td>Edinburgh</td>
      <td>46</td>
      <td>2011/03/09</td>
      <td>$324,050</td>
    </tr>
    <tr>
      <td>Unity Butler</td>
      <td>Marketing Designer</td>
      <td>San Francisco</td>
      <td>47</td>
      <td>2009/12/09</td>
      <td>$85,675</td>
    </tr>
    <tr>
      <td>Howard Hatfield</td>
      <td>Office Manager</td>
      <td>San Francisco</td>
      <td>51</td>
      <td>2008/12/16</td>
      <td>$164,500</td>
    </tr>
    <tr>
      <td>Hope Fuentes</td>
      <td>Secretary</td>
      <td>San Francisco</td>
      <td>41</td>
      <td>2010/02/12</td>
      <td>$109,850</td>
    </tr>
    <tr>
      <td>Vivian Harrell</td>
      <td>Financial Controller</td>
      <td>San Francisco</td>
      <td>62</td>
      <td>2009/02/14</td>
      <td>$452,500</td>
    </tr>
    <tr>
      <td>Timothy Mooney</td>
      <td>Office Manager</td>
      <td>London</td>
      <td>37</td>
      <td>2008/12/11</td>
      <td>$136,200</td>
    </tr>
    <tr>
      <td>Jackson Bradshaw</td>
      <td>Director</td>
      <td>New York</td>
      <td>65</td>
      <td>2008/09/26</td>
      <td>$645,750</td>
    </tr>
    <tr>
      <td>Olivia Liang</td>
      <td>Support Engineer</td>
      <td>Singapore</td>
      <td>64</td>
      <td>2011/02/03</td>
      <td>$234,500</td>
    </tr>
    <tr>
      <td>Bruno Nash</td>
      <td>Software Engineer</td>
      <td>London</td>
      <td>38</td>
      <td>2011/05/03</td>
      <td>$163,500</td>
    </tr>
    <tr>
      <td>Sakura Yamamoto</td>
      <td>Support Engineer</td>
      <td>Tokyo</td>
      <td>37</td>
      <td>2009/08/19</td>
      <td>$139,575</td>
    </tr>
    <tr>
      <td>Thor Walton</td>
      <td>Developer</td>
      <td>New York</td>
      <td>61</td>
      <td>2013/08/11</td>
      <td>$98,540</td>
    </tr>
    <tr>
      <td>Finn Camacho</td>
      <td>Support Engineer</td>
      <td>San Francisco</td>
      <td>47</td>
      <td>2009/07/07</td>
      <td>$87,500</td>
    </tr>
    <tr>
      <td>Serge Baldwin</td>
      <td>Data Coordinator</td>
      <td>Singapore</td>
      <td>64</td>
      <td>2012/04/09</td>
      <td>$138,575</td>
    </tr>
    <tr>
      <td>Zenaida Frank</td>
      <td>Software Engineer</td>
      <td>New York</td>
      <td>63</td>
      <td>2010/01/04</td>
      <td>$125,250</td>
    </tr>
    <tr>
      <td>Zorita Serrano</td>
      <td>Software Engineer</td>
      <td>San Francisco</td>
      <td>56</td>
      <td>2012/06/01</td>
      <td>$115,000</td>
    </tr>
    <tr>
      <td>Jennifer Acosta</td>
      <td>Junior Javascript Developer</td>
      <td>Edinburgh</td>
      <td>43</td>
      <td>2013/02/01</td>
      <td>$75,650</td>
    </tr>
    <tr>
      <td>Cara Stevens</td>
      <td>Sales Assistant</td>
      <td>New York</td>
      <td>46</td>
      <td>2011/12/06</td>
      <td>$145,600</td>
    </tr>
    <tr>
      <td>Hermione Butler</td>
      <td>Regional Director</td>
      <td>London</td>
      <td>47</td>
      <td>2011/03/21</td>
      <td>$356,250</td>
    </tr>
    <tr>
      <td>Lael Greer</td>
      <td>Systems Administrator</td>
      <td>London</td>
      <td>21</td>
      <td>2009/02/27</td>
      <td>$103,500</td>
    </tr>
    <tr>
      <td>Jonas Alexander</td>
      <td>Developer</td>
      <td>San Francisco</td>
      <td>30</td>
      <td>2010/07/14</td>
      <td>$86,500</td>
    </tr>
    <tr>
      <td>Shad Decker</td>
      <td>Regional Director</td>
      <td>Edinburgh</td>
      <td>51</td>
      <td>2008/11/13</td>
      <td>$183,000</td>
    </tr>
    <tr>
      <td>Michael Bruce</td>
      <td>Javascript Developer</td>
      <td>Singapore</td>
      <td>29</td>
      <td>2011/06/27</td>
      <td>$183,000</td>
    </tr>
    <tr>
      <td>Donna Snider</td>
      <td>Customer Support</td>
      <td>New York</td>
      <td>27</td>
      <td>2011/01/25</td>
      <td>$112,000</td>
    </tr>
  </tbody>
</table></code>```

答: It's a bug confirmed by the DataTables Team. Will be fixed in the next release.</p>

Title: Show SearchBuilder Form

Body:
DataTables website have the example (link below) for searchbuilder extension. In the example when button is clicked, it shows search Builder form (as shown in the image below).

https://datatables.net/extensions/searchbuilder/examples/initialisation/button.html

When I try to replicate, I am getting the box below. If I will click on "Add Condition", I will have the same form but it's an additional step to reach there.

$(document).ready(function() {
  $('#example').DataTable({
    buttons: [{
      extend: 'searchBuilder'
    }],
    language: {
      searchBuilder: {
        data: 'Column',
        add: 'Add Condition',
        button: {
          0: ' Filters',
          _: ' Filters (%d)'
        }
      }
    },
    dom: 'Bfrtip'
  });
});

  <link href='https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css' rel='stylesheet' />
  <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css' rel='stylesheet' />
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap4.min.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/searchbuilder/1.3.0/css/searchBuilder.bootstrap4.min.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.1.1/css/dataTables.dateTime.min.css" />

      Name
      Position
      Office
      Age
      Start date
      Salary

      Tiger Nixon
      System Architect
      Edinburgh
      61
      2011/04/25
      $320,800

      Garrett Winters
      Accountant
      Tokyo
      63
      2011/07/25
      $170,750

      Ashton Cox
      Junior Technical Author
      San Francisco
      66
      2009/01/12
      $86,000

      Cedric Kelly
      Senior Javascript Developer
      Edinburgh
      22
      2012/03/29
      $433,060

      Airi Satou
      Accountant
      Tokyo
      33
      2008/11/28
      $162,700

      Brielle Williamson
      Integration Specialist
      New York
      61
      2012/12/02
      $372,000

      Herrod Chandler
      Sales Assistant
      San Francisco
      59
      2012/08/06
      $137,500

      Rhona Davidson
      Integration Specialist
      Tokyo
      55
      2010/10/14
      $327,900

      Colleen Hurst
      Javascript Developer
      San Francisco
      39
      2009/09/15
      $205,500

      Sonya Frost
      Software Engineer
      Edinburgh
      23
      2008/12/13
      $103,600

      Jena Gaines
      Office Manager
      London
      30
      2008/12/19
      $90,560

      Quinn Flynn
      Support Lead
      Edinburgh
      22
      2013/03/03
      $342,000

      Charde Marshall
      Regional Director
      San Francisco
      36
      2008/10/16
      $470,600

      Haley Kennedy
      Senior Marketing Designer
      London
      43
      2012/12/18
      $313,500

      Tatyana Fitzpatrick
      Regional Director
      London
      19
      2010/03/17
      $385,750

      Michael Silva
      Marketing Designer
      London
      66
      2012/11/27
      $198,500

      Paul Byrd
      Chief Financial Officer (CFO)
      New York
      64
      2010/06/09
      $725,000

      Gloria Little
      Systems Administrator
      New York
      59
      2009/04/10
      $237,500

      Bradley Greer
      Software Engineer
      London
      41
      2012/10/13
      $132,000

      Dai Rios
      Personnel Lead
      Edinburgh
      35
      2012/09/26
      $217,500

      Jenette Caldwell
      Development Lead
      New York
      30
      2011/09/03
      $345,000

      Yuri Berry
      Chief Marketing Officer (CMO)
      New York
      40
      2009/06/25
      $675,000

      Caesar Vance
      Pre-Sales Support
      New York
      21
      2011/12/12
      $106,450

      Doris Wilder
      Sales Assistant
      Sydney
      23
      2010/09/20
      $85,600

      Angelica Ramos
      Chief Executive Officer (CEO)
      London
      47
      2009/10/09
      $1,200,000

      Gavin Joyce
      Developer
      Edinburgh
      42
      2010/12/22
      $92,575

      Jennifer Chang
      Regional Director
      Singapore
      28
      2010/11/14
      $357,650

      Brenden Wagner
      Software Engineer
      San Francisco
      28
      2011/06/07
      $206,850

      Fiona Green
      Chief Operating Officer (COO)
      San Francisco
      48
      2010/03/11
      $850,000

      Shou Itou
      Regional Marketing
      Tokyo
      20
      2011/08/14
      $163,000

      Michelle House
      Integration Specialist
      Sydney
      37
      2011/06/02
      $95,400

      Suki Burks
      Developer
      London
      53
      2009/10/22
      $114,500

      Prescott Bartlett
      Technical Author
      London
      27
      2011/05/07
      $145,000

      Gavin Cortez
      Team Leader
      San Francisco
      22
      2008/10/26
      $235,500

      Martena Mccray
      Post-Sales support
      Edinburgh
      46
      2011/03/09
      $324,050

      Unity Butler
      Marketing Designer
      San Francisco
      47
      2009/12/09
      $85,675

      Howard Hatfield
      Office Manager
      San Francisco
      51
      2008/12/16
      $164,500

      Hope Fuentes
      Secretary
      San Francisco
      41
      2010/02/12
      $109,850

      Vivian Harrell
      Financial Controller
      San Francisco
      62
      2009/02/14
      $452,500

      Timothy Mooney
      Office Manager
      London
      37
      2008/12/11
      $136,200

      Jackson Bradshaw
      Director
      New York
      65
      2008/09/26
      $645,750

      Olivia Liang
      Support Engineer
      Singapore
      64
      2011/02/03
      $234,500

      Bruno Nash
      Software Engineer
      London
      38
      2011/05/03
      $163,500

      Sakura Yamamoto
      Support Engineer
      Tokyo
      37
      2009/08/19
      $139,575

      Thor Walton
      Developer
      New York
      61
      2013/08/11
      $98,540

      Finn Camacho
      Support Engineer
      San Francisco
      47
      2009/07/07
      $87,500

      Serge Baldwin
      Data Coordinator
      Singapore
      64
      2012/04/09
      $138,575

      Zenaida Frank
      Software Engineer
      New York
      63
      2010/01/04
      $125,250

      Zorita Serrano
      Software Engineer
      San Francisco
      56
      2012/06/01
      $115,000

      Jennifer Acosta
      Junior Javascript Developer
      Edinburgh
      43
      2013/02/01
      $75,650

      Cara Stevens
      Sales Assistant
      New York
      46
      2011/12/06
      $145,600

      Hermione Butler
      Regional Director
      London
      47
      2011/03/21
      $356,250

      Lael Greer
      Systems Administrator
      London
      21
      2009/02/27
      $103,500

      Jonas Alexander
      Developer
      San Francisco
      30
      2010/07/14
      $86,500

      Shad Decker
      Regional Director
      Edinburgh
      51
      2008/11/13
      $183,000

      Michael Bruce
      Javascript Developer
      Singapore
      29
      2011/06/27
      $183,000

      Donna Snider
      Customer Support
      New York
      27
      2011/01/25
      $112,000


来源: stackexchange

问:
Using nginx-rtmp-module to save rtmp stream to mp4 instead of flv
I am trying to save an incoming rtmp stream on my server as an mp4 file. I am using the nginx-rtmp module and changing the container from flv to mp4  on the exec_record_done directive. This is done using ffmpeg as follows

```<code>ffmpeg -i input.flv output.mp4
</code>```

I am sending h264 video streams and aac audio streams (in an flv container), so as to keep it compatible even with mp4

I would like to know if it is possible to directly save the incoming stream as an mp4 and avoid the transcoding at the end of each session

I am guessing this will help avoid the abrupt CPU spikes that I see when a recording is done

nginx.conf

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 1024;
}

rtmp {
    server {
        listen 1935;
        chunk_size 4096;
        allow publish all;
        allow play all;

        application live {
            live on;

            record all;
            record_suffix .flv;
            record_path /tmp/videos/;
            record_unique on;

            exec_record_done ffmpeg -y -i $path  /home/ubuntu/videos/$basename.mp4;
        }
    }
}

</code>```

I thought this would be simple enough because the underlying streams remain the same. Any help is appreciated :)

答:
It's because your FFmpeg command is incorrect, try this:

```<code>exec_record_done ffmpeg -i $path -c copy /home/ubuntu/videos/$basename.mp4;
</code>```

Remember to add the -c copy to tell FFmpeg convert FLV to MP4 without transcoding.

Another solution is copying the HLS files and covert HLS to MP4 by yourself.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to save an incoming rtmp stream on my server as an mp4 file. I am using the nginx-rtmp module and changing the container from flv to mp4  on the exec_record_done directive. This is done using ffmpeg as follows

ffmpeg -i input.flv output.mp4

I am sending h264 video streams and aac audio streams (in an flv container), so as to keep it compatible even with mp4

I would like to know if it is possible to directly save the incoming stream as an mp4 and avoid the transcoding at the end of each session

I am guessing this will help avoid the abrupt CPU spikes that I see when a recording is done

nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 1024;
}

rtmp {
    server {
        listen 1935;
        chunk_size 4096;
        allow publish all;
        allow play all;

        application live {
            live on;

            record all;
            record_suffix .flv;
            record_path /tmp/videos/;
            record_unique on;

            exec_record_done ffmpeg -y -i $path  /home/ubuntu/videos/$basename.mp4;
        }
    }
}

I thought this would be simple enough because the underlying streams remain the same. Any help is appreciated :)

Body:
It's because your FFmpeg command is incorrect, try this:

exec_record_done ffmpeg -i $path -c copy /home/ubuntu/videos/$basename.mp4;

Remember to add the -c copy to tell FFmpeg convert FLV to MP4 without transcoding.

Another solution is copying the HLS files and covert HLS to MP4 by yourself.


问:
ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead
I am building a blog app in django. But, when I write a function for logging users out, I get this traceback error:

```<code>Internal Server Error: /users/logout/
Traceback (most recent call last):
  File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response
    self.check_response(response, callback)
  File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 309, in check_response
    "instead." % name
ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead.
</code>```

My logout_user view function is only two lines, so I can't seem to understand the error. Here is my view function:

```<code>@login_required
def logout_user(request):
    logout(request)
</code>```

Can anyone help me out?

答:
I had the same issue as you and fixed it as followed:

@login_required(login_url='users/login/')
def logout_user(request):
    logout(request)
    return redirect('homepage')
```
<p>where homepage is defined in views.py as:</p>
<pre class="lang-py prettyprint-override"><code>def homepage(request):
    return render(request, 'main/homepage.html')
</code>```

and imported into the main urls.py

from main.views import homepage

urlpatterns = [
path('', homepage, name='homepage'),
]
```

Body:
I am building a blog app in django. But, when I write a function for logging users out, I get this traceback error:

Internal Server Error: /users/logout/
Traceback (most recent call last):
  File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response
    self.check_response(response, callback)
  File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 309, in check_response
    "instead." % name
ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead.

My logout_user view function is only two lines, so I can't seem to understand the error. Here is my view function:

@login_required
def logout_user(request):
    logout(request)

Can anyone help me out?

Body:
I had the same issue as you and fixed it as followed:

@login_required(login_url='users/login/')
def logout_user(request):
    logout(request)
    return redirect('homepage')

where homepage is defined in views.py as:

def homepage(request):
    return render(request, 'main/homepage.html')

and imported into the main urls.py

from main.views import homepage

urlpatterns = [
path('', homepage, name='homepage'),
]


问:
Angular 11+ MatDialog: inner component's (ngComponentOutlet) html does not trigger <button (click)="close()"> method. Works on Angular 9
In fact, I'm having more issues with the ngComponentOutlet-embedded component inside the MatDialog. But let's start here.

What I'm building

I want to display an arbitrary Component inside a MatDialog. I've found a way, but while it works on Angular 9 (the version I've found an example written in), it does not work in Angular 11 (the version my project is based on) nor on Angular 13 (@latest).

Observations

when an inner HTML contains a <button (click)="close()">Close</button> and I click on the button, the inner Component's close() method is not triggered

it triggers the close() method if I bind it to the (mousedown) event instead of (click); probably works with other events but the (click) one

when I click on the button, instead the inner component is reloaded (see console logs in examples)

when I click anywhere on the dialog, the inner component is reloaded (see console logs in examples); does not happen in Angular 9

Angular 9 does not have this problem. I am using exactly the same app code in both examples below (both projects created with ng new, using different ng versions).

Repro examples

(stackblitz is ill, give it a few retries if it sneezes out 500s. Probably covid...)

Broken example (Angular 11)

Working example (Angular 9)

In the Angular 9 example, the MatDialog works as expected

In the Angular 11 example the MatDialog does not work as expected

I have tried Angular 13 (@latest), the problem persists

Questions

Why is this happening?

How do I get around this?

Raw files FFR

app.module.ts

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppComponent} from './app.component';
import {MatDialogModule} from '@angular/material/dialog';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {BaseDialogComponent, SampleInnerComponent} from './my-dialog.service';

@NgModule({
  declarations: [
    AppComponent,
    BaseDialogComponent, SampleInnerComponent
  ],
  imports: [
    BrowserModule,
    MatDialogModule, BrowserAnimationsModule
  ],
  exports: [BaseDialogComponent, SampleInnerComponent],
  providers: [BaseDialogComponent, SampleInnerComponent],
  bootstrap: [AppComponent],
  entryComponents: [BaseDialogComponent, SampleInnerComponent]
})
export class AppModule { }
```
<p><strong>app.component.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>import {Component} from '@angular/core';
import {MyDialogService} from './my-dialog.service';
import {MatDialogRef} from '@angular/material/dialog';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="toggle()">TOGGLE</button>
  `,
})
export class AppComponent {
  title = 'repro-broken';
  private dialogRef: MatDialogRef<any>;

  constructor(private dialogService: MyDialogService) {
  }

  toggle(): void {
    if (this.dialogRef) {
      this.dialogRef.close(undefined);
      this.dialogRef = undefined;
    } else {
      this.dialogRef = this.dialogService.open();
    }
  }
}
</code>```

my-dialog.service.ts

import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material/dialog';
import {Component, Inject, Injectable, Injector} from '@angular/core';
import {ReplaySubject} from 'rxjs';
import {tap} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MyDialogService {

  constructor(private dialog: MatDialog) {
  }

  open(): MatDialogRef<any> {
    const innerComp = new InjectedDialogRef();
    const dialogRef = this.dialog.open(BaseDialogComponent, {
      // width: '',
      // height: '',
      // closeOnNavigation: false,
      // disableClose: true,
      // backdropClass: [],
      // hasBackdrop: false,
      data: {component: SampleInnerComponent, data: innerComp}
    });

    innerComp.dialog$.next(dialogRef);
    return dialogRef;
  }

}

@Injectable()
export class InjectedDialogRef {
  dialog$ = new ReplaySubject<MatDialogRef<any>>(1);
}

@Component({
  selector: 'app-dialog-sample',
  template: `

Dialog Inner Component

    <button (click)="close()">Close</button>

  `,
})
export class SampleInnerComponent {
  public dialog: MatDialogRef<any>;

  constructor(private inj: InjectedDialogRef) {
    inj.dialog$
      .pipe(tap(evt => console.log('Got a dialog', evt)))
      .subscribe(dialog => this.dialog = dialog);
  }

  close(): void {
    console.log('Closing the dialog', this.dialog);
    this.dialog.close(undefined);
  }

  stuff(): void {
    console.log('Doing stuff');
  }
}

@Component({
  selector: 'app-dialog-base',
  template: `

MyTitle

      <ng-container *ngComponentOutlet="inner.component; injector:createInjector(inner.data)"></ng-container>

  `,
})
export class BaseDialogComponent {

  constructor(
    @Inject(MAT_DIALOG_DATA) public inner: any,
    private inj: Injector) {
    console.log('Opening base dialog');
  }

  createInjector(inj: InjectedDialogRef): Injector {
    return Injector.create({
      providers: [{provide: InjectedDialogRef, useValue: inj}],
      parent: this.inj
    });
  }
}

```

答:
Get rid of createInjector(inner.data) method call from the BaseDialogComponent template.

Instead create the injector and store it within the BaseDialogComponent property. Then assign that property to *ngComponentOutlet injector.

@Component({
  selector: 'app-dialog-base',
  template: `

MyTitle

      <ng-container *ngComponentOutlet="inner.component; injector:contentInjector"></ng-container>

  `,
})
export class BaseDialogComponent implements OnInit {
  contentInjector!: Injector; // Defined property to hold the content injector

  constructor(
    @Inject(MAT_DIALOG_DATA) public inner: any,
    private inj: Injector
  ) {
    console.log('Opening base dialog');
  }

  // Created the injector within ngOnInit
  ngOnInit() {
    this.contentInjector = this.createInjector(this.inner.data);
  }

  createInjector(inj: InjectedDialogRef): Injector {
    return Injector.create({
      providers: [{ provide: InjectedDialogRef, useValue: inj }],
      parent: this.inj,
    });
  }
}
```
<p><strong>Stackblitz</strong></p>
<hr>
<h2>Why the same code worked in Angular 9, but not in Angular 11 and above?</h2>
<p>First of all the issue(varying behavior) is not due to the code within Angular framework, but due to some code within Angular Material.</p>
<p>In Angular Material v11, the CDK overlay adds a <code>click</code> event listener on document <code>body</code> during <strong>capture</strong> phase. Hence whenever you clicked, the Change detection was triggered even before the click listener associated with the button got chance to execute, which is turn resulted into re-rendering of the view as <code>createInjector()</code> method always returned a new Injector instance when called.</p>
<p>Due to the same reason you observed the below behavior of component being reloaded/rendered:</p>
<blockquote>
<p>when I click anywhere on the dialog, the inner component is reloaded (see console logs in examples); does not happen in Angular 9</p>
</blockquote>
<p>click event listener in Angular Material v11</p>
<p>The Angular Material v9 doesn't include this <code>click</code> event listener code, hence the listener associated with the button executed and closed the dialog without causing any issue. The clicks within the overlay and not on "Close" button again didn't triggered any Change Detection, and hence no re-rendering happened.</p>
<p>You can replicate the same behavior in your Angular 9 code by adding a listener as below:</p>
<pre class="lang-ts prettyprint-override"><code>// AppComponent
constructor(private dialogService: MyDialogService) {
  document.body.addEventListener('click', () => console.log('clicked'), true);
}
</code>```

Body:
In fact, I'm having more issues with the ngComponentOutlet-embedded component inside the MatDialog. But let's start here.

What I'm building

I want to display an arbitrary Component inside a MatDialog. I've found a way, but while it works on Angular 9 (the version I've found an example written in), it does not work in Angular 11 (the version my project is based on) nor on Angular 13 (@latest).

Observations

when an inner HTML contains a <button (click)="close()">Close</button> and I click on the button, the inner Component's close() method is not triggered

it triggers the close() method if I bind it to the (mousedown) event instead of (click); probably works with other events but the (click) one

when I click on the button, instead the inner component is reloaded (see console logs in examples)

when I click anywhere on the dialog, the inner component is reloaded (see console logs in examples); does not happen in Angular 9

Angular 9 does not have this problem. I am using exactly the same app code in both examples below (both projects created with ng new, using different ng versions).

Repro examples

(stackblitz is ill, give it a few retries if it sneezes out 500s. Probably covid...)

Broken example (Angular 11)

Working example (Angular 9)

In the Angular 9 example, the MatDialog works as expected

In the Angular 11 example the MatDialog does not work as expected

I have tried Angular 13 (@latest), the problem persists

Questions

Why is this happening?

How do I get around this?

Raw files FFR

app.module.ts

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppComponent} from './app.component';
import {MatDialogModule} from '@angular/material/dialog';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {BaseDialogComponent, SampleInnerComponent} from './my-dialog.service';

@NgModule({
  declarations: [
    AppComponent,
    BaseDialogComponent, SampleInnerComponent
  ],
  imports: [
    BrowserModule,
    MatDialogModule, BrowserAnimationsModule
  ],
  exports: [BaseDialogComponent, SampleInnerComponent],
  providers: [BaseDialogComponent, SampleInnerComponent],
  bootstrap: [AppComponent],
  entryComponents: [BaseDialogComponent, SampleInnerComponent]
})
export class AppModule { }

app.component.ts

import {Component} from '@angular/core';
import {MyDialogService} from './my-dialog.service';
import {MatDialogRef} from '@angular/material/dialog';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="toggle()">TOGGLE</button>
  `,
})
export class AppComponent {
  title = 'repro-broken';
  private dialogRef: MatDialogRef<any>;

  constructor(private dialogService: MyDialogService) {
  }

  toggle(): void {
    if (this.dialogRef) {
      this.dialogRef.close(undefined);
      this.dialogRef = undefined;
    } else {
      this.dialogRef = this.dialogService.open();
    }
  }
}

my-dialog.service.ts

import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material/dialog';
import {Component, Inject, Injectable, Injector} from '@angular/core';
import {ReplaySubject} from 'rxjs';
import {tap} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MyDialogService {

  constructor(private dialog: MatDialog) {
  }

  open(): MatDialogRef<any> {
    const innerComp = new InjectedDialogRef();
    const dialogRef = this.dialog.open(BaseDialogComponent, {
      // width: '',
      // height: '',
      // closeOnNavigation: false,
      // disableClose: true,
      // backdropClass: [],
      // hasBackdrop: false,
      data: {component: SampleInnerComponent, data: innerComp}
    });

    innerComp.dialog$.next(dialogRef);
    return dialogRef;
  }

}

@Injectable()
export class InjectedDialogRef {
  dialog$ = new ReplaySubject<MatDialogRef<any>>(1);
}

@Component({
  selector: 'app-dialog-sample',
  template: `

Dialog Inner Component

    <button (click)="close()">Close</button>

  `,
})
export class SampleInnerComponent {
  public dialog: MatDialogRef<any>;

  constructor(private inj: InjectedDialogRef) {
    inj.dialog$
      .pipe(tap(evt => console.log('Got a dialog', evt)))
      .subscribe(dialog => this.dialog = dialog);
  }

  close(): void {
    console.log('Closing the dialog', this.dialog);
    this.dialog.close(undefined);
  }

  stuff(): void {
    console.log('Doing stuff');
  }
}

@Component({
  selector: 'app-dialog-base',
  template: `

MyTitle

      <ng-container *ngComponentOutlet="inner.component; injector:createInjector(inner.data)"></ng-container>

  `,
})
export class BaseDialogComponent {

  constructor(
    @Inject(MAT_DIALOG_DATA) public inner: any,
    private inj: Injector) {
    console.log('Opening base dialog');
  }

  createInjector(inj: InjectedDialogRef): Injector {
    return Injector.create({
      providers: [{provide: InjectedDialogRef, useValue: inj}],
      parent: this.inj
    });
  }
}

Body:
Get rid of createInjector(inner.data) method call from the BaseDialogComponent template.

Instead create the injector and store it within the BaseDialogComponent property. Then assign that property to *ngComponentOutlet injector.

@Component({
  selector: 'app-dialog-base',
  template: `
    <h2 mat-dialog-title>MyTitle</h2>
    <div mat-dialog-content>

    <!-- Removed createInjector(inner.data) method call and replaced with contentInjector property  -->
      <ng-container *ngComponentOutlet="inner.component; injector:contentInjector"></ng-container>

    </div>
  `,
})
export class BaseDialogComponent implements OnInit {
  contentInjector!: Injector; // Defined property to hold the content injector

  constructor(
    @Inject(MAT_DIALOG_DATA) public inner: any,
    private inj: Injector
  ) {
    console.log('Opening base dialog');
  }

  // Created the injector within ngOnInit
  ngOnInit() {
    this.contentInjector = this.createInjector(this.inner.data);
  }

  createInjector(inj: InjectedDialogRef): Injector {
    return Injector.create({
      providers: [{ provide: InjectedDialogRef, useValue: inj }],
      parent: this.inj,
    });
  }
}

Stackblitz

Why the same code worked in Angular 9, but not in Angular 11 and above?

First of all the issue(varying behavior) is not due to the code within Angular framework, but due to some code within Angular Material.

In Angular Material v11, the CDK overlay adds a click event listener on document body during capture phase. Hence whenever you clicked, the Change detection was triggered even before the click listener associated with the button got chance to execute, which is turn resulted into re-rendering of the view as createInjector() method always returned a new Injector instance when called.

Due to the same reason you observed the below behavior of component being reloaded/rendered:

when I click anywhere on the dialog, the inner component is reloaded (see console logs in examples); does not happen in Angular 9

click event listener in Angular Material v11

The Angular Material v9 doesn't include this click event listener code, hence the listener associated with the button executed and closed the dialog without causing any issue. The clicks within the overlay and not on "Close" button again didn't triggered any Change Detection, and hence no re-rendering happened.

You can replicate the same behavior in your Angular 9 code by adding a listener as below:

// AppComponent
constructor(private dialogService: MyDialogService) {
  document.body.addEventListener('click', () => console.log('clicked'), true);
}


问:
Unity Panel Interaction Issue
I have two panels in unity 2d directly overlapping each other and they use scroll panels so I can scroll down. I have it set so when one is accessed, the other is pulled up, but when they swap the other panel is grey and I cannot interact with it, but when I attempt to scroll the other panel scrolls instead, even though it is hidden and turned off.</p>

答:
I suspect that this is a bug in the code. It's possible, that when the user presses the scroll button in the first panel, and then releases the button, the second panel's scroll button thinks, it's already been pressed by the user, when in fact it isn't.

Set it up in such a way, that when you release the button on a scrollbar (the first scroll bar), it resets the click on the scrollbars connected to it (a second scroll bar).

Title: Unity Panel Interaction Issue


问:
How to use current company in BQL query
I need to know how I can get the user's current company so that I can use it in the Where clause of a BQL query.  I'm not talking about the tenant "company".  I'm talking about the companies that are defined on screen CS101500.  I'm not seeing anything on the AccessInfo that seems to indicate the current Company.  The current Branch ID is there but, I need the company to which the branch belongs.

Using version 21.203

TIA!

答:
You can try to use this code</p>
```<code> public int? GetOrganizationID(PXGraph graph, int? branchID)
 {
    int? accountID = ((Organization)OrganizationMaint.FindOrganizationByID(graph, PXAccess.GetParentOrganizationID(branchID))).BAccountID;
    return accountID;
 }
</code>```

Title: How to use current company in BQL query

Body:
You can try to use this code

 public int? GetOrganizationID(PXGraph graph, int? branchID)
 {
    int? accountID = ((Organization)OrganizationMaint.FindOrganizationByID(graph, PXAccess.GetParentOrganizationID(branchID))).BAccountID;
    return accountID;
 }


问:
Why is memset() incorrectly initializing int?
Why is the output of the following program 84215045?

```<code>int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}
</code>```

答:
```<code>memset(grid, 5, 100 * sizeof(int));
</code>```

You are setting 400 bytes, starting at (char*)grid and ending at (char*)grid + (100 * sizeof(int)), to the value 5 (the casts are necessary here because memset deals in bytes, whereas pointer arithmetic deals in objects.

84215045 in hex is 0x05050505; since int (on your platform/compiler/etc.) is represented by four bytes, when you print it, you get "four fives."

ContentLicense: CC BY-SA 3.0

Body:
Why is the output of the following program 84215045?

int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}

Body:
memset(grid, 5, 100 * sizeof(int));

You are setting 400 bytes, starting at (char*)grid and ending at (char*)grid + (100 * sizeof(int)), to the value 5 (the casts are necessary here because memset deals in bytes, whereas pointer arithmetic deals in objects.

84215045 in hex is 0x05050505; since int (on your platform/compiler/etc.) is represented by four bytes, when you print it, you get "four fives."


问:
python, How to find specific key value in json file then save whole line of json file？
I am a newbie and I need to export specific key value in json file,I searched a lot of sites but couldn't find the code I need, hope this helps me

my json file

```<code>
{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":26}}

</code>```

Need to export whole line json file where 'sex' is 'male' in JSON file

```<code>{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":26}}

</code>```

full code required

答:
Bearing in mind that the input file is not a JSON file per se. Each line is valid JSON and therefore has to be dealt with separately.

For example:

```<code>import json

with open ('foonew.txt', 'w', encoding='utf-8') as out:
    with open('foo.txt', encoding='utf-8') as j:
        for line in j:
            if (d := json.loads(line))['person']['sex'] == 'male':
                print(json.dumps(d), file=out)
</code>```

The output file will look like:

```<code>{"person": {"name": "LANA", "sex": "male", "age": 28}}
{"person": {"name": "KENN", "sex": "male", "age": 26}}
</code>```

Alternatively, to get a separate file for each gender then:

```<code>import json
sexes = []
with open('foo.txt', encoding='utf-8') as j:
    for line in j:
        d = json.loads(line)
        sex = d['person']['sex']
        if sex in sexes:
            mode = 'a'
        else:
            sexes.append(sex)
            mode = 'w'
        with open(f'{sex}.txt', mode, encoding='utf-8') as out:
            print(json.dumps(d), file=out)
</code>```

Body:
I am a newbie and I need to export specific key value in json file,I searched a lot of sites but couldn't find the code I need, hope this helps me

my json file

{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":26}}

Need to export whole line json file where 'sex' is 'male' in JSON file

{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":26}}

full code required

Body:
Bearing in mind that the input file is not a JSON file per se. Each line is valid JSON and therefore has to be dealt with separately.

For example:

import json

with open ('foonew.txt', 'w', encoding='utf-8') as out:
    with open('foo.txt', encoding='utf-8') as j:
        for line in j:
            if (d := json.loads(line))['person']['sex'] == 'male':
                print(json.dumps(d), file=out)

The output file will look like:

{"person": {"name": "LANA", "sex": "male", "age": 28}}
{"person": {"name": "KENN", "sex": "male", "age": 26}}

Alternatively, to get a separate file for each gender then:

import json
sexes = []
with open('foo.txt', encoding='utf-8') as j:
    for line in j:
        d = json.loads(line)
        sex = d['person']['sex']
        if sex in sexes:
            mode = 'a'
        else:
            sexes.append(sex)
            mode = 'w'
        with open(f'{sex}.txt', mode, encoding='utf-8') as out:
            print(json.dumps(d), file=out)


问:
Error about borrowing when nothing seems to be borrowed
Writing a function to find the corresponding value to a given query name as an argument out of url, I got an error following:

```<code>error[E0515]: cannot return value referencing local variable `url`
  --> src/main.rs:55:25
   |
51 |   let mut queries = url.query_pairs();
   |                     ----------------- `url` is borrowed here
...
55 |     Some((_, value)) => value
   |                         ^^^^^ returns a value referencing data owned by the current function
</code>```

code:

use url::{self, Url};

fn find_query(referer: String, query_name: &str) -> Cow<str> {
  let url_text = Url::parse(&referer).unwrap();
  let mut queries = url_text.query_pairs();
  let index_of_name = queries.find(|(key,_)| key == query_name);
  let result = match index_of_name {
    None => panic!("name didn't match any"),
    Some((_, value)) => value
  };
  result
}
```
<p>Although I fixed it with the modification below, I still don't see why I had this type of error even though <code>result</code> itself was not borrowed. The message in the error "returns a value referencing data owned by the current function" sounds right.</p>
<p>Can anyone break down the reason behind this error?</p>
<p>Thank you in advance.</p>
<p>fixed code:</p>
<pre class="lang-rust prettyprint-override"><code>use url::{self, Url};

fn find_query(referer: String, query_name: &str) -> String {
  let url_text = Url::parse(&referer).unwrap();
  let queries = url_text.query_pairs();
  let index_of_name = queries.into_owned().find(|(key,_)| key == query_name);
  let result = match index_of_name {
    None => panic!("name didn't match any"),
    Some((_, value)) => value
  };
  result
}
</code>```

答:
Writing:

let url: Url = todo!();
url.query_pairs()
```
<p>is the same as writing:</p>
<pre class="lang-rust prettyprint-override"><code>let url: Url = todo!();
Url::query_pairs(&url)  // notice the borrow of url here
</code>```

This is referred to as "unified function call syntax". Really, it's the foo.bar() syntax that is special, and Foo::foo(bar) is the "default" syntax.

You can also tell this is happening by looking at the function signature of query_pairs:

impl Url {
  pub fn query_pairs(&self) -> Parse<'_> {
    // ...
  }
}
```

The &self parameter denotes that this function takes the struct it is called on by immutable reference.

Hopefully this should illustrate why the call to into_owned() fixed the error

Body:
Writing a function to find the corresponding value to a given query name as an argument out of url, I got an error following:

error[E0515]: cannot return value referencing local variable `url`
  --> src/main.rs:55:25
   |
51 |   let mut queries = url.query_pairs();
   |                     ----------------- `url` is borrowed here
...
55 |     Some((_, value)) => value
   |                         ^^^^^ returns a value referencing data owned by the current function

code:

use url::{self, Url};

fn find_query(referer: String, query_name: &str) -> Cow<str> {
  let url_text = Url::parse(&referer).unwrap();
  let mut queries = url_text.query_pairs();
  let index_of_name = queries.find(|(key,_)| key == query_name);
  let result = match index_of_name {
    None => panic!("name didn't match any"),
    Some((_, value)) => value
  };
  result
}

Although I fixed it with the modification below, I still don't see why I had this type of error even though result itself was not borrowed. The message in the error "returns a value referencing data owned by the current function" sounds right.

Can anyone break down the reason behind this error?

Thank you in advance.

fixed code:

use url::{self, Url};

fn find_query(referer: String, query_name: &str) -> String {
  let url_text = Url::parse(&referer).unwrap();
  let queries = url_text.query_pairs();
  let index_of_name = queries.into_owned().find(|(key,_)| key == query_name);
  let result = match index_of_name {
    None => panic!("name didn't match any"),
    Some((_, value)) => value
  };
  result
}

Body:
Writing:

let url: Url = todo!();
url.query_pairs()

is the same as writing:

let url: Url = todo!();
Url::query_pairs(&url)  // notice the borrow of url here

This is referred to as "unified function call syntax". Really, it's the foo.bar() syntax that is special, and Foo::foo(bar) is the "default" syntax.

You can also tell this is happening by looking at the function signature of query_pairs:

impl Url {
  pub fn query_pairs(&self) -> Parse<'_> {
    // ...
  }
}

The &self parameter denotes that this function takes the struct it is called on by immutable reference.

Hopefully this should illustrate why the call to into_owned() fixed the error


问:
How to disable e.g. Dropout in tf.keras.Model to generate activation maximation images using transfer learning
I am using transfer learning and keras.applications.InceptionV3. I manage to train the model successfully.

However, when I want to generate "activation maximisation" images (e.g. the input image that maximizes the activation of one of the custom classes, ref eg  https://arxiv.org/pdf/1512.02017v3.pdf ) I struggle to use the pre-trained model since I do manage to use it in "fit" mode and disable all dropouts etc.

What I do is that I combine the pre-trained model in a tf.keras.Sequential to do gradient descent on the weights of the first layer (the input image).

Despite setting base_model.trainable = False however it seems as if the pre-trained model is put into training mode (although weights are not updated) when using model.fit(data) on the outer sequential model.

Is there any way to force the base_model (a child of a Sequential) to be in "predict" mode when calling fit on the outer?

答:
I just came across the same question. After reading some documentation and having a look on the source code of TensorFlows implementations of tf.keras.layers.Layer, tf.keras.layers.Dense, and tf.keras.layers.BatchNormalization I got the following understanding.

If training = False is passed on calling the layer, it will run in inference mode. This has nothing to do with the attribute trainable, which means something different. It would probably lead to less misunderstanding, if they would have called it training_mode instead.

When doing Transfer Learning or Fine Tuning training = False should be passed on calling the base model itself. As far as I saw until now this will only affect layers like tf.keras.layers.Dropout and tf.keras.layers.BatchNormalization and will have not effect on the other layers.

Running in inference mode via training = False will result in tf.layers.Dropout not to apply the dropout rate at all.

As tf.layers.Dropout has no trainable weights, setting the attribute trainable = False will have no effect at all,


问:
CUDA example in Julia doesn't use GPU
I'm doing my first steps on running Julia 1.6.5 code on GPU. For some reason, it seems the GPU is not being used at all. These are the steps:

First of all, my GPU passed on the test recommended at CUDA Julia Docs:

```<code># install the package
using Pkg
Pkg.add("CUDA")

# smoke test (this will download the CUDA toolkit)
using CUDA
CUDA.versioninfo()

using Pkg
Pkg.test("CUDA")    # takes ~40 minutes if using 1 thread
</code>```

Secondly, the below code took around 8 minutes (real time) for supposedly running on my GPU. It loads and multiplies, for 10 times, two matrices 10000 x 10000:

```<code>using CUDA
using Random
N = 10000

a_d = CuArray{Float32}(undef, (N, N))
b_d = CuArray{Float32}(undef, (N, N))
c_d = CuArray{Float32}(undef, (N, N))

for i in 1:10
    global a_d = randn(N, N)
    global b_d = randn(N, N)

    global c_d = a_d * b_d
end

global a_d = nothing
global b_d = nothing
global c_d = nothing
GC.gc()
</code>```

Outcome on terminal as follows:

```<code>(base) ciro@ciro-G3-3500:~/projects/julia/cuda$ time julia cuda-gpu.jl

real    8m13,016s
user    50m39,146s
sys 13m16,766s
</code>```

Then, an equivalent code for the CPU is run. Execution time was also equivalent:

```<code>using Random
N = 10000

for i in 1:10
    a = randn(N, N)
    b = randn(N, N)

    c = a * b
end
</code>```

Execution:

```<code>(base) ciro@ciro-G3-3500:~/projects/julia/cuda$ time julia cuda-cpu.jl

real    8m2,689s
user    50m9,567s
sys 13m3,738s
</code>```

Moreover, by following the info on NVTOP screen command, it is weird to see the GPU memory and cores being loaded/unloaded accordingly, besides still using the same 800% CPUs (or eight cores) of my regular CPU, which is the same usage the CPU-version has.

Any hint is greatly appreciated.

答:
After playing a little bit, the following code also works. Interesting to note the declaration "global" on c_d variable. Without it, the system complained about ambiguity between the (global) CuArray c_d and the assumption of a different (unintended local) variable c_d.

```<code>using CUDA
using Random
N = 10000

a_d = CuArray{Float32}(undef, (N, N))
b_d = CuArray{Float32}(undef, (N, N))
c_d = CuArray{Float32}(undef, (N, N))

for i in 1:10
    randn!(a_d)
    randn!(b_d)

    global c_d = a_d * b_d
end

global a_d = nothing
global b_d = nothing
global c_d = nothing
GC.gc()
</code>```

The outcome on a relatively modest GPU confirms the result:

```<code>(base) ciro@ciro-Inspiron-7460:~/projects/julia/cuda$ time julia cuda-gpu.jl

real    0m38,243s
user    0m36,810s
sys 0m1,413s
</code>```

Title: CUDA example in Julia doesn't use GPU

Body:
I'm doing my first steps on running Julia 1.6.5 code on GPU. For some reason, it seems the GPU is not being used at all. These are the steps:

First of all, my GPU passed on the test recommended at CUDA Julia Docs:

# install the package
using Pkg
Pkg.add("CUDA")

# smoke test (this will download the CUDA toolkit)
using CUDA
CUDA.versioninfo()

using Pkg
Pkg.test("CUDA")    # takes ~40 minutes if using 1 thread

Secondly, the below code took around 8 minutes (real time) for supposedly running on my GPU. It loads and multiplies, for 10 times, two matrices 10000 x 10000:

using CUDA
using Random
N = 10000

a_d = CuArray{Float32}(undef, (N, N))
b_d = CuArray{Float32}(undef, (N, N))
c_d = CuArray{Float32}(undef, (N, N))

for i in 1:10
    global a_d = randn(N, N)
    global b_d = randn(N, N)

    global c_d = a_d * b_d
end

global a_d = nothing
global b_d = nothing
global c_d = nothing
GC.gc()

Outcome on terminal as follows:

(base) ciro@ciro-G3-3500:~/projects/julia/cuda$ time julia cuda-gpu.jl

real    8m13,016s
user    50m39,146s
sys 13m16,766s

Then, an equivalent code for the CPU is run. Execution time was also equivalent:

using Random
N = 10000

for i in 1:10
    a = randn(N, N)
    b = randn(N, N)

    c = a * b
end

Execution:

(base) ciro@ciro-G3-3500:~/projects/julia/cuda$ time julia cuda-cpu.jl

real    8m2,689s
user    50m9,567s
sys 13m3,738s

Moreover, by following the info on NVTOP screen command, it is weird to see the GPU memory and cores being loaded/unloaded accordingly, besides still using the same 800% CPUs (or eight cores) of my regular CPU, which is the same usage the CPU-version has.

Any hint is greatly appreciated.

Body:
After playing a little bit, the following code also works. Interesting to note the declaration "global" on c_d variable. Without it, the system complained about ambiguity between the (global) CuArray c_d and the assumption of a different (unintended local) variable c_d.

using CUDA
using Random
N = 10000

a_d = CuArray{Float32}(undef, (N, N))
b_d = CuArray{Float32}(undef, (N, N))
c_d = CuArray{Float32}(undef, (N, N))

for i in 1:10
    randn!(a_d)
    randn!(b_d)

    global c_d = a_d * b_d
end

global a_d = nothing
global b_d = nothing
global c_d = nothing
GC.gc()

The outcome on a relatively modest GPU confirms the result:

(base) ciro@ciro-Inspiron-7460:~/projects/julia/cuda$ time julia cuda-gpu.jl

real    0m38,243s
user    0m36,810s
sys 0m1,413s


问:
Selenium Python After pressing the button,a new window opens,I can't press the keys there
I am new to python
https://prnt.sc/26nlk3q
I press the button on the site, then this window appears in which you need to click to confirm
I tried this

driver.switch_to.window(driver.window_handles[-1])

And This

alert = browser.switch_to.alert

alert.accept()

but its not working for me

I can show you how it looks in the browser, if necessary

This window has a separate html code, I do not understand how to access it

答:
I think the query is related to switching tabs. Try this:

driver.switch_to.window(driver.window_handles[1])

In driver.window_handles[] method, you are required to specify the index of the tab in [] [0] is the first tab, [1] is the second tab, and so on. I think this should clear the doubt.


问:
How to get winform fullpath?
I have a winform and its fullpath is C:\test.exe

How do I get the winform fullpath at run time? For example, the user may move the winform to other places. Thanks.

答: You can call Assembly.GetEntryAssembly ().CodeBase (or Location) from a Windows-Form application (but not from ASP.NET applications).</p>

Title: How to get winform fullpath?


问:
Typescript doesn't check keys in array object
I have an array that should content an explicit object. By some reason typescript doesn't show me errors if I break this object. I use column object to knex query.

```<code>type Test = {
    id: string;
    startDate: string;
    percentDebitCard: number,
}

const column = {
  id: 'bct.id',
  startDate: 'bct.startDate',
  percentDebitCard: 'bct.percentDebitCard',
};

const allCashBackByType:any=[{
    id: "bla",
    startDate: "bla",
    endDate: "bla",
    someKey:"bla",
    someKey1:"bla",
    someKey2:"bla",
    someKey3:"bla"
}]

const test:Test[]=allCashBackByType.map((item: typeof column):Test => ({
    id: item.id,
    startDate: item.startDate,
    percentDebitCard: item.percentDebitCard as number,
}));
</code>```

Why is this happening and how can it be fixed?

But if I remove method map that make iterations it shows errors

```<code>const test:Test[]=[{
    id: '11',
    startDate: "22",
    extraKey:"33"
}];
</code>```

But I need map.

答:
You can try this</p>
```<code>const test:Test[]=allCashBackByType.map((item: any): Test => ({
    id: item.id,
    startDate: item.startDate,
    extraKey: '2222'
}));
</code>```

Body:
I have an array that should content an explicit object. By some reason typescript doesn't show me errors if I break this object. I use column object to knex query.

type Test = {
    id: string;
    startDate: string;
    percentDebitCard: number,
}

const column = {
  id: 'bct.id',
  startDate: 'bct.startDate',
  percentDebitCard: 'bct.percentDebitCard',
};

const allCashBackByType:any=[{
    id: "bla",
    startDate: "bla",
    endDate: "bla",
    someKey:"bla",
    someKey1:"bla",
    someKey2:"bla",
    someKey3:"bla"
}]

const test:Test[]=allCashBackByType.map((item: typeof column):Test => ({
    id: item.id,
    startDate: item.startDate,
    percentDebitCard: item.percentDebitCard as number,
}));

Why is this happening and how can it be fixed?

But if I remove method map that make iterations it shows errors

const test:Test[]=[{
    id: '11',
    startDate: "22",
    extraKey:"33"
}];

But I need map.

Body:
You can try this

const test:Test[]=allCashBackByType.map((item: any): Test => ({
    id: item.id,
    startDate: item.startDate,
    extraKey: '2222'
}));


问:
How to display version update once user update the app from playstore
Sorry if this is a stupid question since I don't find any solution. So I know that I can get the version number and update-notifier when the update is available on the play store or app store using some flutter package. But I think that I cant show users what the update is about and there is no package like that exists. So I think I need to implement something like an alert dialog manually to show the updated information before I want to publish the update. So, how can I do it with flutter to show that alert dialog just once after the user update the app? Can shared preferences do that? If so how? And is there really a package or ways that I can show the updated information that I don't know of?</p>

答:
This should be possible with package_info_plus and shared_preferences. You can use package_info_plus to get the current version and store it with shared_preferences. Then on app launch, get the current version from package_info_plus and compare it to the stored version.

Here is an example:

import 'package:shared_preferences/shared_preferences.dart';
import 'package:package_info_plus/package_info_plus.dart';

bool shouldShowUpdateAlert() async {
  PackageInfo packageInfo = await PackageInfo.fromPlatform();
  final prefs = await SharedPreferences.getInstance();
  String version = packageInfo.version;
  final String? storedVersion = prefs.getString('appVersion');
  await prefs.setString('appVersion', version);
  return version != storedVersion;
}
```


问:
Changing 2D element of a list to 1D element
I wanted to change 2D element of a list to 1D in the following code.

```<code>from itertools import chain
a = ['one', 'two']
b = [[1, 2], [3, 3]]
c = [ [[x] * y for x, y in zip(a, row)] for row in b ]
c = list(chain.from_iterable(c))
print(c)
</code>```

The out put was

```<code>[['one'], ['two', 'two'], ['one', 'one', 'one'], ['two', 'two', 'two']]
</code>```

if

```<code>c = [ [x * y for x, y in zip(a, row)] for row in b ]
</code>```

the result would be

```<code>[['Amh', 'EngEng'], ['AmhAmhAmh', 'EngEngEng']]
</code>```

But I wanted the result to be as the following using list comprehension.

```<code>[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]
</code>```

答:
New answer (edited in after OP's edit):

Given

```<code>c = [ [[x] * y for x, y in zip(a, row)] for row in b ]
</code>```

You can simply iterate over the new sublist as you create it:

```<code>c = [ [i for x, y in zip(a, row) for i in [x]*y] for row in b]
</code>```

or use itertools.chain if that's what you prefer:

```<code>c = [ list(chain.from_iterable([x]*y for x, y in zip(a, row))) for row in b]
</code>```

Output:

```<code>[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]
</code>```

Old answer:

Given

```<code>lst = [['one'], ['two', 'two'], ['one', 'one', 'one'], ['two', 'two', 'two']]
</code>```

You could concatenate lists in a list comprehension using range:

```<code>out = [lst[i] + lst[i+1] for i in range(0, len(lst), 2)]
</code>```

or using zip:

```<code>out = [li1+li2 for li1, li2 in zip(lst[::2], lst[1::2])]
</code>```

Output:

```<code>[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]
</code>```

Body:
I wanted to change 2D element of a list to 1D in the following code.

from itertools import chain
a = ['one', 'two']
b = [[1, 2], [3, 3]]
c = [ [[x] * y for x, y in zip(a, row)] for row in b ]
c = list(chain.from_iterable(c))
print(c)

The out put was

[['one'], ['two', 'two'], ['one', 'one', 'one'], ['two', 'two', 'two']]

if

c = [ [x * y for x, y in zip(a, row)] for row in b ]

the result would be

[['Amh', 'EngEng'], ['AmhAmhAmh', 'EngEngEng']]

But I wanted the result to be as the following using list comprehension.

[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]

Body:
New answer (edited in after OP's edit):

Given

c = [ [[x] * y for x, y in zip(a, row)] for row in b ]

You can simply iterate over the new sublist as you create it:

c = [ [i for x, y in zip(a, row) for i in [x]*y] for row in b]

or use itertools.chain if that's what you prefer:

c = [ list(chain.from_iterable([x]*y for x, y in zip(a, row))) for row in b]

Output:

[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]

Old answer:

Given

lst = [['one'], ['two', 'two'], ['one', 'one', 'one'], ['two', 'two', 'two']]

You could concatenate lists in a list comprehension using range:

out = [lst[i] + lst[i+1] for i in range(0, len(lst), 2)]

or using zip:

out = [li1+li2 for li1, li2 in zip(lst[::2], lst[1::2])]

Output:

[['one', 'two', 'two'], ['one', 'one', 'one', 'two', 'two', 'two']]


答:
memset sets each byte of the destination buffer to the specified value.  On your system, an int is four bytes, each of which is 5 after the call to memset.  Thus, grid[0] has the value 0x05050505 (hexadecimal), which is 84215045 in decimal.

Some platforms provide alternative APIs to memset that write wider patterns to the destination buffer; for example, on OS X or iOS, you could use:

```<code>int pattern = 5;
memset_pattern4(grid, &pattern, sizeof grid);
</code>```

to get the behavior that you seem to expect.  What platform are you targeting?

In C++, you should just use std::fill_n:

```<code>std::fill_n(grid, 100, 5);
</code>```

Title: Why is memset() incorrectly initializing int?

Body:
memset sets each byte of the destination buffer to the specified value.  On your system, an int is four bytes, each of which is 5 after the call to memset.  Thus, grid[0] has the value 0x05050505 (hexadecimal), which is 84215045 in decimal.

Some platforms provide alternative APIs to memset that write wider patterns to the destination buffer; for example, on OS X or iOS, you could use:

int pattern = 5;
memset_pattern4(grid, &pattern, sizeof grid);

to get the behavior that you seem to expect.  What platform are you targeting?

In C++, you should just use std::fill_n:

std::fill_n(grid, 100, 5);


问:
User is loged/signed in but the screen does not change
I am working with Firebase authentication and lately was not able to do anything because of the following error. When I enter the user's credentials, it gets authenticated on the Firebase console, but my app's screen does not change. What's more, the following error appears in debug console.

2 I/System.out(26261): (HTTPLog)-Static: isSBSettingEnabled false
I/SurfaceControl(26261): nativeRelease nativeObject
s[-5476376676702711408] I/SurfaceControl(26261): nativeRelease
nativeObject e[-5476376676702711408] W/System  (26261): Ignoring
header X-Firebase-Locale because its value was null. 2
I/System.out(26261): (HTTPLog)-Static: isSBSettingEnabled false

```<code>void authUser(
      String email, String password, String conPassword, bool isLogin) async {
    UserCredential authResult;
    setState(() {
      isLoading = true;
    });
    FocusScope.of(context).unfocus();
    try {
      if (password != conPassword && isLogin == false) {
        showDialog(
          context: context,
          builder: (_) => const AlertDialog(
            title: Text('Passwords don\'t match'),
            content: Text('Please check if your passwords match'),
          ),
        );
      }

      if (isLogin == false) {
        authResult = await firebaseAuth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
      } else {
        authResult = await firebaseAuth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
      }

      setState(() {
        isLoading = false;
      });
    } catch (e) {
      rethrow;
    }
  }
</code>```

...

```<code>TextFormField(
                  key: const ValueKey('email'),
                  keyboardType: TextInputType.emailAddress,
                  decoration: const InputDecoration(
                    label: Text('Email adress'),
                  ),
                  onSaved: (newValue) {
                    email = newValue!;
                    FocusScope.of(context).requestFocus(_passwordNode);
                  },
                ),
                TextFormField(
                  key: const ValueKey('password'),
                  focusNode: _passwordNode,
                  obscureText: true,
                  onSaved: (newValue) {
                    password = newValue!;
                    FocusScope.of(context).requestFocus(_conPasswordNode);
                  },
                  decoration: const InputDecoration(
                    label: Text('Password'),
                  ),
                ),
                if (isLogin == false)
                  TextFormField(
                    key: const ValueKey('conPassword'),
                    focusNode: _conPasswordNode,
                    obscureText: true,
                    decoration: const InputDecoration(
                      label: Text('Confirm password'),
                    ),
                    onSaved: (newValue) {
                      conPassword = newValue!;
                    },
                  ),
                Expanded(
                  child: Container(),
                ),
                widget.isLoading == true
                    ? const Center(
                        child: CircularProgressIndicator(),
                      )
                    : ButtonBar(
                        alignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton(
                            onPressed: () {
                              setState(() {
                                isLogin = !isLogin;
                              });
                            },
                            child: Text(isLogin == true ? 'SignUp' : 'Login'),
                          ),
                          ElevatedButton(
                            onPressed: _trySubmit,
                            child: const Text('Done'),
                          ),
                        ],
                      ),

   ...
    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: Firebase.initializeApp(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              }
              return MultiProvider(
                providers: [
                  ChangeNotifierProvider(
                    create: (ctx) => RecipeProvider(),
                  ),

  ],
            child: MaterialApp ...
             home: StreamBuilder<User?>(
                  stream: FirebaseAuth.instance.authStateChanges(),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return const CircularProgressIndicator();
                    }
                    if (snapshot.hasData) {
                      return AllRecipesScreen();
                    }
                    return AuthScreen();
                  }),
              routes: {
                AllRecipesScreen.routeName: (ctx) => AllRecipesScreen(),
                RecipeDetailScreen.routeName: (ctx) => RecipeDetailScreen(),
                AddRecipeScreen.routeName: (ctx) => AddRecipeScreen(),
                AuthScreen.routeName: (ctx) => AuthScreen(),
              },
            ),
          );
        });
  }
}
</code>```

答: try changing the targetedSdk to 27, hope this helps.</p>

Body:
I am working with Firebase authentication and lately was not able to do anything because of the following error. When I enter the user's credentials, it gets authenticated on the Firebase console, but my app's screen does not change. What's more, the following error appears in debug console.

2 I/System.out(26261): (HTTPLog)-Static: isSBSettingEnabled false
I/SurfaceControl(26261): nativeRelease nativeObject
s[-5476376676702711408] I/SurfaceControl(26261): nativeRelease
nativeObject e[-5476376676702711408] W/System  (26261): Ignoring
header X-Firebase-Locale because its value was null. 2
I/System.out(26261): (HTTPLog)-Static: isSBSettingEnabled false

void authUser(
      String email, String password, String conPassword, bool isLogin) async {
    UserCredential authResult;
    setState(() {
      isLoading = true;
    });
    FocusScope.of(context).unfocus();
    try {
      if (password != conPassword && isLogin == false) {
        showDialog(
          context: context,
          builder: (_) => const AlertDialog(
            title: Text('Passwords don\'t match'),
            content: Text('Please check if your passwords match'),
          ),
        );
      }

      if (isLogin == false) {
        authResult = await firebaseAuth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
      } else {
        authResult = await firebaseAuth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
      }

      setState(() {
        isLoading = false;
      });
    } catch (e) {
      rethrow;
    }
  }

...

TextFormField(
                  key: const ValueKey('email'),
                  keyboardType: TextInputType.emailAddress,
                  decoration: const InputDecoration(
                    label: Text('Email adress'),
                  ),
                  onSaved: (newValue) {
                    email = newValue!;
                    FocusScope.of(context).requestFocus(_passwordNode);
                  },
                ),
                TextFormField(
                  key: const ValueKey('password'),
                  focusNode: _passwordNode,
                  obscureText: true,
                  onSaved: (newValue) {
                    password = newValue!;
                    FocusScope.of(context).requestFocus(_conPasswordNode);
                  },
                  decoration: const InputDecoration(
                    label: Text('Password'),
                  ),
                ),
                if (isLogin == false)
                  TextFormField(
                    key: const ValueKey('conPassword'),
                    focusNode: _conPasswordNode,
                    obscureText: true,
                    decoration: const InputDecoration(
                      label: Text('Confirm password'),
                    ),
                    onSaved: (newValue) {
                      conPassword = newValue!;
                    },
                  ),
                Expanded(
                  child: Container(),
                ),
                widget.isLoading == true
                    ? const Center(
                        child: CircularProgressIndicator(),
                      )
                    : ButtonBar(
                        alignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton(
                            onPressed: () {
                              setState(() {
                                isLogin = !isLogin;
                              });
                            },
                            child: Text(isLogin == true ? 'SignUp' : 'Login'),
                          ),
                          ElevatedButton(
                            onPressed: _trySubmit,
                            child: const Text('Done'),
                          ),
                        ],
                      ),

   ...
    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: Firebase.initializeApp(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              }
              return MultiProvider(
                providers: [
                  ChangeNotifierProvider(
                    create: (ctx) => RecipeProvider(),
                  ),

  ],
            child: MaterialApp ...
             home: StreamBuilder<User?>(
                  stream: FirebaseAuth.instance.authStateChanges(),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return const CircularProgressIndicator();
                    }
                    if (snapshot.hasData) {
                      return AllRecipesScreen();
                    }
                    return AuthScreen();
                  }),
              routes: {
                AllRecipesScreen.routeName: (ctx) => AllRecipesScreen(),
                RecipeDetailScreen.routeName: (ctx) => RecipeDetailScreen(),
                AddRecipeScreen.routeName: (ctx) => AddRecipeScreen(),
                AuthScreen.routeName: (ctx) => AuthScreen(),
              },
            ),
          );
        });
  }
}


问:
Subsetting a dataframe in R by retaining first occurrences of unique elements from all columns
df is a test dataframe which has 5 rows and 6 columns and it is a subset of a much larger dataframe (dimensions: 1000000 X 30).

```<code>df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
 category1 = c("a", "", "b", "a", ""),
 category2 = c("c", "", "", "d", "c"),
 category3 = c("", "", "e", "f", "f"),
 category4 = c("", "", "", "", ""),
 category5 = c("i", "", "i", "j", ""))
</code>```

df looks like this

For each column from category1 to category5 I need to retain only the first occurrences of all the unique elements. e.g. For category1, the unique elements are a and b and their first occurrences are in rows 1 and 3 respectively. So rows 1 and 3 should be retained, and so on. The output should look something like this

答:
Using lapply and duplicated you could first replace duplicates per column by "", then filter for rows containing at least one non "" string:

df[-1] <- lapply(df[-1], function(x) {
    x[duplicated(x)] <- ""
    x
})
df <- df[rowSums(!df[-1] == "") > 0, ]
df
#>   Hits category1 category2 category3 category4 category5
#> 1 Hit1         a         c                             i
#> 3 Hit3         b                   e
#> 4 Hit4                   d         f                   j
```

Body:
df is a test dataframe which has 5 rows and 6 columns and it is a subset of a much larger dataframe (dimensions: 1000000 X 30).

df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
 category1 = c("a", "", "b", "a", ""),
 category2 = c("c", "", "", "d", "c"),
 category3 = c("", "", "e", "f", "f"),
 category4 = c("", "", "", "", ""),
 category5 = c("i", "", "i", "j", ""))

df looks like this

For each column from category1 to category5 I need to retain only the first occurrences of all the unique elements. e.g. For category1, the unique elements are a and b and their first occurrences are in rows 1 and 3 respectively. So rows 1 and 3 should be retained, and so on. The output should look something like this


问:
Shell how to make some of the script arguments mandatory
I want to run a script which accepts 3 command line options -o|q|i. I want to make the q and o but not i so run command has to look like:

script.sh -q <some-text> -o <some-other-text>

The below code makes none of them mandatory. How can I achieve this?

```<code> for arg in "$@"
    do
        case $arg in
            -q) req="$2"
            shift  shift ;;
            -o) out="$2"
            shift  shift ;;
            -i|) ind="$2"
            shift  shift ;;
        esac
    done
</code>```

答:
I made this work by checking that the variables req and out have some value after the for loop with the below code:

```<code>  if [[ -z $out  ||  -z $req ]]
  then
    echo "ERROR: -q  and -o are mandatory arguments. See usage: \n";
    exit 1;
  fi
</code>```

Body:
I want to run a script which accepts 3 command line options -o|q|i. I want to make the q and o but not i so run command has to look like:

script.sh -q <some-text> -o <some-other-text>

The below code makes none of them mandatory. How can I achieve this?

 for arg in "$@"
    do
        case $arg in
            -q) req="$2"
            shift  shift ;;
            -o) out="$2"
            shift  shift ;;
            -i|) ind="$2"
            shift  shift ;;
        esac
    done

Body:
I made this work by checking that the variables req and out have some value after the for loop with the below code:

  if [[ -z $out  ||  -z $req ]]
  then
    echo "ERROR: -q  and -o are mandatory arguments. See usage: \n";
    exit 1;
  fi


问:
pyqtgraph: fixing the number of strings displayed on the x-axis when using TimeAxisItem and tickStrings
I am making a scrolling graph which will plot real-time sensor data, with time on the x axis.  I am a bit confused by the behavior of tickStrings.

My code is based on the example below (from here). As the number of points plotted increases, the number of x axis strings varies - sometimes it increases and sometimes it decreases . It stabilizes once the deque is full length and the 'scrolling' begins.

Is it possible to keep the spacing between tick strings the same as the number of plotted points increases? I guess that it might be possible use an approach where blank tick strings are replaced as new data is added, but don't know how to do that.

Edit: An example of what I wish to achieve is here.

```<code>import sys
import numpy as np
import datetime
from PyQt5.QtCore import QTime, QTimer
from pyqtgraph.Qt import QtGui
import pyqtgraph as pg
from collections import deque
import time

class TimeAxisItem(pg.AxisItem):
    def __init__(self, *args, **kwargs):
        super(TimeAxisItem, self).__init__(*args, **kwargs)

    def tickStrings(self, values, scale, spacing):
        return [int2dt(value).strftime("%H:%M:%S") for value in values]

def int2dt(ts):
    return(datetime.datetime.fromtimestamp(ts))

class MyApplication(QtGui.QApplication):
    def __init__(self, *args, **kwargs):
        super(MyApplication, self).__init__(*args, **kwargs)
        self.t = QTime()
        self.t.start()

        maxlen = 100
        self.data_x = deque(maxlen=maxlen)
        self.data_y = deque(maxlen=maxlen)

        self.win = pg.GraphicsLayoutWidget()
        self.win.resize(1000,600)
        self.plot = self.win.addPlot(title='Scrolling real-time plot', axisItems={'bottom': TimeAxisItem(
            orientation='bottom')})

        self.curve = self.plot.plot()

        self.tmr = QTimer()
        self.tmr.timeout.connect(self.update)
        self.tmr.start(1000)

        self.y = 100
        self.win.show()

    def update(self):
        x = int(time.time())
        self.y = self.y + np.random.uniform(-1, 1)

        self.data_x.append(x)
        self.data_y.append(self.y)
        time.sleep(2)
        print(self.data_x)
        print(self.data_y)
        self.curve.setData(x=list(self.data_x), y=list(self.data_y))

def main():
    app = MyApplication(sys.argv)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

</code>```

答:
Since question got updated with more details, here is more specific answer to it. I kept previous answer to help someone in case of having fixed number of ticks displayed.

To address exactly what You want, You need to first set tick frequency to 1 per second. This can be done by setting self.setTickSpacing(levels=[(1, 0)]). In Your example You have update time one minute, in that case You want to use self.setTickSpacing(levels=[(60, 0)]).

Second part of the problem is rotation of ticks by -90 degrees. Rotation is not part of the AxisItem implementation. So we have to reimplement drawPicture method. Do the rotation and translation of the tick. Also to have 'enough' height, we must set self.fixedHeight = 150 to fit long tick string .

Constant spacing between ticks is achieved by setting fixed range of axis X. To achieve scrolling effect, we have to hide first ticks without any data attached to it. This is done with ticks = [(1.0, ticks[0][1][self.hide_ticks:])] line.

It's important to note, that my solution fits You specific situation. Otherwise one must play with fixedHeight and rotation part of drawPicture method. Also maxlen for Your queue must be lowered to like 10, so that ticks won't overlap.

Here is full code:

```<code>import datetime
import sys
import time
from collections import deque

import numpy as np
import pyqtgraph as pg
from PyQt5.QtCore import QTime, QTimer
from pyqtgraph import debug as debug
from pyqtgraph.Qt import QtGui

class TimeAxisItem(pg.AxisItem):
    hide_ticks = 0

    def __init__(self, *args, **kwargs):
        super(TimeAxisItem, self).__init__(*args, **kwargs)
        # Paint tick every 1 second
        self.setTickSpacing(levels=[(1, 0)])
        # Paint tick every 1 minute
        # self.setTickSpacing(levels=[(60, 0)])
        # Set fixed tick height
        self.fixedHeight = 150

    def tickStrings(self, values, scale, spacing):
        return [int2dt(value).strftime("%Y-%m-%d %H:%M:%S") for value in values]

    def drawPicture(self, p, axisSpec, tickSpecs, textSpecs):

        profiler = debug.Profiler()

        p.setRenderHint(p.RenderHint.Antialiasing, False)
        p.setRenderHint(p.RenderHint.TextAntialiasing, True)

        ## draw long line along axis
        pen, p1, p2 = axisSpec
        p.setPen(pen)
        p.drawLine(p1, p2)
        # p.translate(0.5,0)  ## resolves some damn pixel ambiguity

        ## draw ticks
        for pen, p1, p2 in tickSpecs:
            p.setPen(pen)
            p.drawLine(p1, p2)
        profiler('draw ticks')

        # Draw all text
        if self.style['tickFont'] is not None:
            p.setFont(self.style['tickFont'])
        p.setPen(self.textPen())
        bounding = self.boundingRect().toAlignedRect()
        p.setClipRect(bounding)
        for rect, flags, text in textSpecs:
            p.save()  # save the painter state
            p.translate(rect.center())  # move coordinate system to center of text rect
            p.rotate(-90)  # rotate text
            p.translate(-rect.center())  # revert coordinate system
            p.translate(-65, 0)  # Move rotated tick down by 65 pixels
            p.drawText(rect, int(flags), text)
            p.restore()  # restore the painter state

        profiler('draw text')

    def tickValues(self, minVal, maxVal, size):
        if minVal == 0:
            return []
        else:
            ticks = super().tickValues(minVal, maxVal, size)
            ticks = [(1.0, ticks[0][1][self.hide_ticks:])]
            return ticks

def int2dt(ts):
    return (datetime.datetime.fromtimestamp(ts))

class MyApplication(QtGui.QApplication):
    def __init__(self, *args, **kwargs):
        super(MyApplication, self).__init__(*args, **kwargs)
        self.t = QTime()
        self.t.start()

        maxlen = 10
        self.data_x = deque(maxlen=maxlen)
        self.data_y = deque(maxlen=maxlen)
        self.win = pg.GraphicsLayoutWidget()
        self.win.resize(1000, 600)
        self.axis_x = TimeAxisItem(orientation='bottom')
        self.plot = self.win.addPlot(title='Scrolling real-time plot', axisItems={'bottom': self.axis_x})
        self.curve = self.plot.plot()

        self.tmr = QTimer()
        self.tmr.timeout.connect(self.update)
        self.tmr.start(1000)

        self.y = 100
        self.win.show()

    def update(self):
        x = int(time.time())
        self.y = self.y + np.random.uniform(-1, 1)

        self.data_x.append(x)
        self.data_y.append(self.y)
        time.sleep(1)

        # Set fixed range
        self.plot.setXRange(self.data_x[0] - self.data_x.maxlen + len(self.data_x),
                            self.data_x[0] + len(self.data_x) - 1, padding=0)
        # Hide ticks without data attached to it, to achieve scrolling effect
        self.axis_x.hide_ticks = self.data_x.maxlen - len(self.data_x)
        self.curve.setData(x=list(self.data_x), y=list(self.data_y))

def main():
    app = MyApplication(sys.argv)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

Body:
I am making a scrolling graph which will plot real-time sensor data, with time on the x axis.  I am a bit confused by the behavior of tickStrings.

My code is based on the example below (from here). As the number of points plotted increases, the number of x axis strings varies - sometimes it increases and sometimes it decreases . It stabilizes once the deque is full length and the 'scrolling' begins.

Is it possible to keep the spacing between tick strings the same as the number of plotted points increases? I guess that it might be possible use an approach where blank tick strings are replaced as new data is added, but don't know how to do that.

Edit: An example of what I wish to achieve is here.

import sys
import numpy as np
import datetime
from PyQt5.QtCore import QTime, QTimer
from pyqtgraph.Qt import QtGui
import pyqtgraph as pg
from collections import deque
import time

class TimeAxisItem(pg.AxisItem):
    def __init__(self, *args, **kwargs):
        super(TimeAxisItem, self).__init__(*args, **kwargs)

    def tickStrings(self, values, scale, spacing):
        return [int2dt(value).strftime("%H:%M:%S") for value in values]

def int2dt(ts):
    return(datetime.datetime.fromtimestamp(ts))

class MyApplication(QtGui.QApplication):
    def __init__(self, *args, **kwargs):
        super(MyApplication, self).__init__(*args, **kwargs)
        self.t = QTime()
        self.t.start()

        maxlen = 100
        self.data_x = deque(maxlen=maxlen)
        self.data_y = deque(maxlen=maxlen)

        self.win = pg.GraphicsLayoutWidget()
        self.win.resize(1000,600)
        self.plot = self.win.addPlot(title='Scrolling real-time plot', axisItems={'bottom': TimeAxisItem(
            orientation='bottom')})

        self.curve = self.plot.plot()

        self.tmr = QTimer()
        self.tmr.timeout.connect(self.update)
        self.tmr.start(1000)

        self.y = 100
        self.win.show()

    def update(self):
        x = int(time.time())
        self.y = self.y + np.random.uniform(-1, 1)

        self.data_x.append(x)
        self.data_y.append(self.y)
        time.sleep(2)
        print(self.data_x)
        print(self.data_y)
        self.curve.setData(x=list(self.data_x), y=list(self.data_y))

def main():
    app = MyApplication(sys.argv)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Body:
Since question got updated with more details, here is more specific answer to it. I kept previous answer to help someone in case of having fixed number of ticks displayed.

To address exactly what You want, You need to first set tick frequency to 1 per second. This can be done by setting self.setTickSpacing(levels=[(1, 0)]). In Your example You have update time one minute, in that case You want to use self.setTickSpacing(levels=[(60, 0)]).

Second part of the problem is rotation of ticks by -90 degrees. Rotation is not part of the AxisItem implementation. So we have to reimplement drawPicture method. Do the rotation and translation of the tick. Also to have 'enough' height, we must set self.fixedHeight = 150 to fit long tick string .

Constant spacing between ticks is achieved by setting fixed range of axis X. To achieve scrolling effect, we have to hide first ticks without any data attached to it. This is done with ticks = [(1.0, ticks[0][1][self.hide_ticks:])] line.

It's important to note, that my solution fits You specific situation. Otherwise one must play with fixedHeight and rotation part of drawPicture method. Also maxlen for Your queue must be lowered to like 10, so that ticks won't overlap.

Here is full code:

import datetime
import sys
import time
from collections import deque

import numpy as np
import pyqtgraph as pg
from PyQt5.QtCore import QTime, QTimer
from pyqtgraph import debug as debug
from pyqtgraph.Qt import QtGui

class TimeAxisItem(pg.AxisItem):
    hide_ticks = 0

    def __init__(self, *args, **kwargs):
        super(TimeAxisItem, self).__init__(*args, **kwargs)
        # Paint tick every 1 second
        self.setTickSpacing(levels=[(1, 0)])
        # Paint tick every 1 minute
        # self.setTickSpacing(levels=[(60, 0)])
        # Set fixed tick height
        self.fixedHeight = 150

    def tickStrings(self, values, scale, spacing):
        return [int2dt(value).strftime("%Y-%m-%d %H:%M:%S") for value in values]

    def drawPicture(self, p, axisSpec, tickSpecs, textSpecs):

        profiler = debug.Profiler()

        p.setRenderHint(p.RenderHint.Antialiasing, False)
        p.setRenderHint(p.RenderHint.TextAntialiasing, True)

        ## draw long line along axis
        pen, p1, p2 = axisSpec
        p.setPen(pen)
        p.drawLine(p1, p2)
        # p.translate(0.5,0)  ## resolves some damn pixel ambiguity

        ## draw ticks
        for pen, p1, p2 in tickSpecs:
            p.setPen(pen)
            p.drawLine(p1, p2)
        profiler('draw ticks')

        # Draw all text
        if self.style['tickFont'] is not None:
            p.setFont(self.style['tickFont'])
        p.setPen(self.textPen())
        bounding = self.boundingRect().toAlignedRect()
        p.setClipRect(bounding)
        for rect, flags, text in textSpecs:
            p.save()  # save the painter state
            p.translate(rect.center())  # move coordinate system to center of text rect
            p.rotate(-90)  # rotate text
            p.translate(-rect.center())  # revert coordinate system
            p.translate(-65, 0)  # Move rotated tick down by 65 pixels
            p.drawText(rect, int(flags), text)
            p.restore()  # restore the painter state

        profiler('draw text')

    def tickValues(self, minVal, maxVal, size):
        if minVal == 0:
            return []
        else:
            ticks = super().tickValues(minVal, maxVal, size)
            ticks = [(1.0, ticks[0][1][self.hide_ticks:])]
            return ticks

def int2dt(ts):
    return (datetime.datetime.fromtimestamp(ts))

class MyApplication(QtGui.QApplication):
    def __init__(self, *args, **kwargs):
        super(MyApplication, self).__init__(*args, **kwargs)
        self.t = QTime()
        self.t.start()

        maxlen = 10
        self.data_x = deque(maxlen=maxlen)
        self.data_y = deque(maxlen=maxlen)
        self.win = pg.GraphicsLayoutWidget()
        self.win.resize(1000, 600)
        self.axis_x = TimeAxisItem(orientation='bottom')
        self.plot = self.win.addPlot(title='Scrolling real-time plot', axisItems={'bottom': self.axis_x})
        self.curve = self.plot.plot()

        self.tmr = QTimer()
        self.tmr.timeout.connect(self.update)
        self.tmr.start(1000)

        self.y = 100
        self.win.show()

    def update(self):
        x = int(time.time())
        self.y = self.y + np.random.uniform(-1, 1)

        self.data_x.append(x)
        self.data_y.append(self.y)
        time.sleep(1)

        # Set fixed range
        self.plot.setXRange(self.data_x[0] - self.data_x.maxlen + len(self.data_x),
                            self.data_x[0] + len(self.data_x) - 1, padding=0)
        # Hide ticks without data attached to it, to achieve scrolling effect
        self.axis_x.hide_ticks = self.data_x.maxlen - len(self.data_x)
        self.curve.setData(x=list(self.data_x), y=list(self.data_y))

def main():
    app = MyApplication(sys.argv)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()