问:
indexing table rows js/jquery
I've been tryin to index my table rows but unsuccessfully. The best I could do was come up with the code the could maybe reindex every row in the table everytime i add new table row, but it doesnt work. I think something is wrong with syntax, but I'm not sure what. JS part:

```<code>$("#pridet").click(function(){
  $("table tbody tr").first().clone().prependTo("table tbody");
  var x = document.getElementsByTagName("tr");
  document.getElementsByName("tabelis").innerHTML = x.rowIndex;
});
</code>```

I realise something is fatally wrong with the second part (like directing where to write what index maybe?)

code on html file:

```<code><button id = "pridet">pridet</button>
  <table id="myTable" class="table table-inverse">
    <thead id = "headings" class = "thead-default">
      <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
      </tr>
    </thead>
    <tfoot class = "thead-default">
      <tr>
        <td>Vidurkis</td>
        <td></td>
        <td></td>
        <td></td>
        <td>10000</td>
        <td>17.3</td>
        <td></td>
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <td class = "tabelis">1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>bla</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
          <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p>
          <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr>
        <td class = "tabelis">2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>bla</td>
        <td>blum</td>
        <td>
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
      </tr>
      <tr>
        <td class = "tabelis">3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>bla</td>
        <td>blum</td>
        <td>
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
      </tr>
    </tbody>
  </table>
  <script src="script.js" charset="utf-8"></script>
  <script>
    function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("myTable").deleteRow(i);
  };
  </script>
</code>```

I could probably count the total number of rows with something like this

```<code>$("#counter").text( $("table tbody tr").length );
</code>```

and use the value to insert numbers into table cells somehow

EDIT: didnt mention this before, but table rows have to eb added at the top of the table (below thead)

答:
$("#pridet").click(function(){
  var new_row = $("table tbody tr").first().clone();
  $('table tbody').append(new_row);
  $('table tr:last').find('td:first').html($('table tbody tr').length);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id = "pridet">pridet</button>
  <table id="myTable" class="table table-inverse" border='1'>
    <thead id = "headings" class = "thead-default">
      <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
      </tr>
    </thead>
    <tfoot class = "thead-default">
      <tr>
        <td>Vidurkis</td>
        <td></td>
        <td></td>
        <td></td>
        <td>10000</td>
        <td>17.3</td>
        <td></td>
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <td class = "tabelis">1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>bla</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
          <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p>
          <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr>
        <td class = "tabelis">2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>bla</td>
        <td>blum</td>
        <td>
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
      </tr>
      <tr>
        <td class = "tabelis">3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>bla</td>
        <td>blum</td>
        <td>
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
      </tr>
    </tbody>
  </table></code>```

Title: indexing table rows js/jquery

Body:
I've been tryin to index my table rows but unsuccessfully. The best I could do was come up with the code the could maybe reindex every row in the table everytime i add new table row, but it doesnt work. I think something is wrong with syntax, but I'm not sure what. JS part:

$("#pridet").click(function(){
  $("table tbody tr").first().clone().prependTo("table tbody");
  var x = document.getElementsByTagName("tr");
  document.getElementsByName("tabelis").innerHTML = x.rowIndex;
});

I realise something is fatally wrong with the second part (like directing where to write what index maybe?)

code on html file:

<button id = "pridet">pridet</button>

        Tabelio Nr.
        Vardas
        Pavardė
        Pareigos
        Bazinė alga, €
        Valandinis atlyginimas, €
        Veiksmai

        Vidurkis

        10000
        17.3

        1
        Mark
        Otto
        @mdo
        bla
        <input type="button" value="Delete" onclick="deleteRow(this)">

        2
        Jacob
        Thornton
        @fat
        bla
        blum

        3
        Larry
        the Bird
        @twitter
        bla
        blum

I could probably count the total number of rows with something like this

$("#counter").text( $("table tbody tr").length );

and use the value to insert numbers into table cells somehow

EDIT: didnt mention this before, but table rows have to eb added at the top of the table (below thead)

Body:
$("#pridet").click(function(){
  var new_row = $("table tbody tr").first().clone();
  $('table tbody').append(new_row);
  $('table tr:last').find('td:first').html($('table tbody tr').length);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id = "pridet">pridet</button>
  <table id="myTable" class="table table-inverse" border='1'>
    <thead id = "headings" class = "thead-default">
      <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
      </tr>
    </thead>
    <tfoot class = "thead-default">
      <tr>
        <td>Vidurkis</td>
        <td></td>
        <td></td>
        <td></td>
        <td>10000</td>
        <td>17.3</td>
        <td></td>
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <td class = "tabelis">1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>bla</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
          <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p>
          <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr>
        <td class = "tabelis">2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>bla</td>
        <td>blum</td>
        <td>
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
      </tr>
      <tr>
        <td class = "tabelis">3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>bla</td>
        <td>blum</td>
        <td>
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-edit"></span></p> -->
          <!-- <p class = "btn" style = "width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class = "fa fa-trash"></span></p> -->
        </td>
      </tr>
    </tbody>
  </table>


来源: stackexchange

问:
SQL returning aggregated results from one table as a column in a query
Say I have the following setup

```<code>---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------
</code>```

Some Mock Data

```<code>Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3
</code>```

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

```<code>Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null
</code>```

Is this possible just using SQL?

答:
```<code>Select Title,
       (SELECT GROUP_CONCAT(Comment) FROM Comments
         WHERE
         Comments.postid=posts.posts) as comments
FROM posts
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Say I have the following setup

---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------

Some Mock Data

Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null

Is this possible just using SQL?


问:
Explanation for event_text[-SCREEN_SIZE[1]/font_height:]?
This code is from the book "Beginning Game Development with Python and Pygame", the following script displays the events that are generated by the mouse and the keyboard on the screen:

```<code>import pygame
from pygame.locals import *
from sys import exit

pygame.init()
SCREEN_SIZE = (800, 600)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

font = pygame.font.SysFont("arial", 16)
font_height = font.get_linesize()
event_text = []

while True:

    event = pygame.event.wait()
    event_text.append(str(event))
    event_text = event_text[-SCREEN_SIZE[1]/font_height:]
</code>```

I have a problem with this line:

```<code>event_text = event_text[-SCREEN_SIZE[1]/font_height:]
</code>```

Could someone explain it?
Thanks in advance :)

答:
event_text is a list. It supports not only subscripting (ie "mylist[4]" to get the fifth element) but also slicing (getting a subpart - or "slice" - of the list) with the list\[start:stop:step\] syntax

In this example, the start value is computed as -SCREEN_SIZE[1]/font_height. SCREEN_SIZE[1] is the height of the screen (600 in this case), font_height is, well, the height of the font used - if we assume a font height of say 20,  -SCREEN_SIZE[1] / 20 => -600 / 20 => -30, so we well get event_text[-30:], which is actually "the last 30 elements in  event_text".

ContentLicense: CC BY-SA 3.0

Body:
This code is from the book "Beginning Game Development with Python and Pygame", the following script displays the events that are generated by the mouse and the keyboard on the screen:

import pygame
from pygame.locals import *
from sys import exit

pygame.init()
SCREEN_SIZE = (800, 600)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

font = pygame.font.SysFont("arial", 16)
font_height = font.get_linesize()
event_text = []

while True:

    event = pygame.event.wait()
    event_text.append(str(event))
    event_text = event_text[-SCREEN_SIZE[1]/font_height:]

I have a problem with this line:

event_text = event_text[-SCREEN_SIZE[1]/font_height:]

Could someone explain it?
Thanks in advance :)


问:
Setting border-radius of input buttom
i try to set border-radius: 14px to the textarea. it shows (missing attribute name).

```<code><input id="txtDateRange" type="text" name="daterange" value="" style="width:80% "; "border-radius: 14px";  class="PrintHide" />
</code>```

How i can do it in good way?
I have searched but could not find what i need.

thanks

答:
your syntax is not right.</p>

```<code><input id="txtDateRange" type="text" name="daterange" value="" style="width:80%;border-radius: 14px;"  class="PrintHide" />
</code>```

Title: Setting border-radius of input buttom

Body:
i try to set border-radius: 14px to the textarea. it shows (missing attribute name).

<input id="txtDateRange" type="text" name="daterange" value="" style="width:80% "; "border-radius: 14px";  class="PrintHide" />

How i can do it in good way?
I have searched but could not find what i need.

thanks

Body:
your syntax is not right.

<input id="txtDateRange" type="text" name="daterange" value="" style="width:80%;border-radius: 14px;"  class="PrintHide" />


问:
Powershell - parsing through JSON to create CSV
I am extracting a JSON from Facebook, this is what it looks like:

```<code>pressions_by_paid_non_paid_unique/day
{
  "data": [
    {
      "name": "page_impressions_by_paid_non_paid_unique",
  "period": "day",
  "values": [
    {
      "value": {
        "total": 549215,
        "unpaid": 549215,
        "paid": 0
      },
      "end_time": "2017-06-02T07:00:00+0000"
    },
</code>```

What I would like is to create a CSV that would either looks like this:

total,unpaid,paid,endtime

  549215,549215,0,2017-06-02T07:00:00+0000

or

value,num,end_time

total,549215,2017-06-02T07:00:00+0000

unpaid,549215,2017-06-02T07:00:00+0000

paid,0,2017-06-02T07:00:00+0000

What I came up with is:

```<code>$file = "D:\BI_LP\001-Solutions_Sources\script\Powershell\curl\facebook21.json"
Get-Content $file -Raw |
ConvertFrom-Json |
Select -Expand data |
Select -Expand values | % {
$end_time = $_.end_time
$value = $_.value
$_.value | select @{n='end_time';e={$end_time}}, @{n='value';e={$value}}
}
</code>```

Which gives me:

```<code>end_time                 value

--------                 -----

2017-05-21T07:00:00+0000 @{total=608837; unpaid=608837; paid=0}

2017-05-22T07:00:00+0000 @{total=682090; unpaid=682090; paid=0}

2017-05-23T07:00:00+0000 @{total=885274; unpaid=885274; paid=0}

2017-05-24T07:00:00+0000 @{total=810845; unpaid=810845; paid=0}

2017-05-25T07:00:00+0000 @{total=755453; unpaid=755453; paid=0}

2017-05-26T07:00:00+0000 @{total=629096; unpaid=629096; paid=0}
</code>```

Does anyone have any suggestions?

答:
I think you are almost there. You could try creating the output object a bit like this in the foreach loop:

```<code>[pscustomobject]@{
  total    = $_.value.total
  unpaid   = $_.value.unpaid
  paid     = $_.value.paid
  end_time = $_.end_time
}
</code>```

Body:
I am extracting a JSON from Facebook, this is what it looks like:

pressions_by_paid_non_paid_unique/day
{
  "data": [
    {
      "name": "page_impressions_by_paid_non_paid_unique",
  "period": "day",
  "values": [
    {
      "value": {
        "total": 549215,
        "unpaid": 549215,
        "paid": 0
      },
      "end_time": "2017-06-02T07:00:00+0000"
    },

What I would like is to create a CSV that would either looks like this:

total,unpaid,paid,endtime

  549215,549215,0,2017-06-02T07:00:00+0000

or

value,num,end_time

total,549215,2017-06-02T07:00:00+0000

unpaid,549215,2017-06-02T07:00:00+0000

paid,0,2017-06-02T07:00:00+0000

What I came up with is:

$file = "D:\BI_LP\001-Solutions_Sources\script\Powershell\curl\facebook21.json"
Get-Content $file -Raw |
ConvertFrom-Json |
Select -Expand data |
Select -Expand values | % {
$end_time = $_.end_time
$value = $_.value
$_.value | select @{n='end_time';e={$end_time}}, @{n='value';e={$value}}
}

Which gives me:

end_time                 value

--------                 -----

2017-05-21T07:00:00+0000 @{total=608837; unpaid=608837; paid=0}

2017-05-22T07:00:00+0000 @{total=682090; unpaid=682090; paid=0}

2017-05-23T07:00:00+0000 @{total=885274; unpaid=885274; paid=0}

2017-05-24T07:00:00+0000 @{total=810845; unpaid=810845; paid=0}

2017-05-25T07:00:00+0000 @{total=755453; unpaid=755453; paid=0}

2017-05-26T07:00:00+0000 @{total=629096; unpaid=629096; paid=0}

Does anyone have any suggestions?

Body:
I think you are almost there. You could try creating the output object a bit like this in the foreach loop:

[pscustomobject]@{
  total    = $_.value.total
  unpaid   = $_.value.unpaid
  paid     = $_.value.paid
  end_time = $_.end_time
}


问:
PHP LongBlob Upload/Download not working with pictures
I have to store lots of documents in my database and i manage to make it work with PDF.
When i try to upload JPG or GIF for example, the content didn't show when i re-download it from the download function below.

Download function :

```<code>    public function downloadFile($id) {
    if($id!=null){
    $sql = "SELECT * FROM document WHERE id = ?";
    $stmt = $this->db->prepare($sql);
    $stmt->bindValue(1, $id);
    $stmt->execute();
    foreach ($stmt as $row) {
      header("Content-length:".$row['taillefichier']);
      header("Content-type:" . $row['typefichier']);
      header("Content-Disposition: attachment; filename=".$row['nomfichier']);
      echo $row['fichier'];
    }
  }
</code>```

答:
So i find the answer to my own question and i'll post the updated function here

```<code>    public function downloadFile($id) {
    if($id!=null){
    $sql = "SELECT * FROM document WHERE id = ?";
    $stmt = $this->db->prepare($sql);
    $stmt->bindValue(1, $id);
    $stmt->execute();
    foreach ($stmt as $row) {
      header("Content-length:".$row['taillefichier']);
      header("Content-type:".$row['typefichier']);
      header("Content-Disposition: attachment; filename=".$row['nomfichier']);
      header("Content-type:".$row['typefichier']);
      ob_clean();
      flush();
      echo $row['fichier'];
    }
  }
}
</code>```

See more here : https://stackoverflow.com/a/31318718/7295677

Body:
I have to store lots of documents in my database and i manage to make it work with PDF.
When i try to upload JPG or GIF for example, the content didn't show when i re-download it from the download function below.

Download function :

    public function downloadFile($id) {
    if($id!=null){
    $sql = "SELECT * FROM document WHERE id = ?";
    $stmt = $this->db->prepare($sql);
    $stmt->bindValue(1, $id);
    $stmt->execute();
    foreach ($stmt as $row) {
      header("Content-length:".$row['taillefichier']);
      header("Content-type:" . $row['typefichier']);
      header("Content-Disposition: attachment; filename=".$row['nomfichier']);
      echo $row['fichier'];
    }
  }

Body:
So i find the answer to my own question and i'll post the updated function here

    public function downloadFile($id) {
    if($id!=null){
    $sql = "SELECT * FROM document WHERE id = ?";
    $stmt = $this->db->prepare($sql);
    $stmt->bindValue(1, $id);
    $stmt->execute();
    foreach ($stmt as $row) {
      header("Content-length:".$row['taillefichier']);
      header("Content-type:".$row['typefichier']);
      header("Content-Disposition: attachment; filename=".$row['nomfichier']);
      header("Content-type:".$row['typefichier']);
      ob_clean();
      flush();
      echo $row['fichier'];
    }
  }
}

See more here : https://stackoverflow.com/a/31318718/7295677


问:
Trigger 'resize' event on component?
I'm writing a component decorator that is able to detect when a DOM element's size is altered (by css, javascript, window resize etc).

It already works perfectly, I'm now trying to make its API easy to use, so, what's easier than this?

```<code>class Foobar extends React.Component {
  render() {
    return <div onResize={() => console.log('resized!')}>Foobar</div>;
  }
}
ReactDOM.render(resizeAware(Foobar), app);
</code>```

The problem I'm facing, is that the onResize event is not being triggered when I trigger it...

These are two attempts to trigger the event:

```<code>// method 1
onResize() {
  const resizeEvent = document.createEvent('HTMLEvents');
  resizeEvent.initEvent('resize', true, true);
  console.log('triggering resize...');
  findDOMNode(this.componentNode).dispatchEvent(resizeEvent);
}

// method 2
onResize() {
    console.log('triggering resize...');
    findDOMNode(this.componentNode).dispatchEvent(new Event('resize'));
}
</code>```

If I listen for the event with:

```<code>findDOMNode(this).addEventListener('resize', () => console.log('resized'));
</code>```

Everything works. So it seems like the event I'm dispatching is received by the real DOM element and not by the virtual DOM.

The question now is, why the onResize callback is not called?

If there's not a solution, how would you make my decorator API available?

NB: I don't want a way to detect the resize of the component, I just need to dispatch an event to React and make it accessible with onResize

答: Another NPM lib to listen to resize event of a div. Check the demo</p>

ContentLicense: CC BY-SA 4.0

Title: Trigger 'resize' event on component?

Body:
I'm writing a component decorator that is able to detect when a DOM element's size is altered (by css, javascript, window resize etc).

It already works perfectly, I'm now trying to make its API easy to use, so, what's easier than this?

class Foobar extends React.Component {
  render() {
    return
 console.log('resized!')}>Foobar
;
  }
}
ReactDOM.render(resizeAware(Foobar), app);

The problem I'm facing, is that the onResize event is not being triggered when I trigger it...

These are two attempts to trigger the event:

// method 1
onResize() {
  const resizeEvent = document.createEvent('HTMLEvents');
  resizeEvent.initEvent('resize', true, true);
  console.log('triggering resize...');
  findDOMNode(this.componentNode).dispatchEvent(resizeEvent);
}

// method 2
onResize() {
    console.log('triggering resize...');
    findDOMNode(this.componentNode).dispatchEvent(new Event('resize'));
}

If I listen for the event with:

findDOMNode(this).addEventListener('resize', () => console.log('resized'));

Everything works. So it seems like the event I'm dispatching is received by the real DOM element and not by the virtual DOM.

The question now is, why the onResize callback is not called?

If there's not a solution, how would you make my decorator API available?

NB: I don't want a way to detect the resize of the component, I just need to dispatch an event to React and make it accessible with onResize


问:
How to check for OpenGL version conformance?
I want to make sure that my application conforms to OpenGL 2.1.
How can I check this?

Because my computer supports GL4.4, even if I use, for example, glGenVertexArrays(), it will work successfully. But glGenVertexArrays() is only available with GL3+.

So, I want to verify that my app only uses GL2.1 functionality.
One way is to run it on my old PC that support only GL2.1, but I'm looking for an easier way.

答:
Try https://github.com/cginternals/glbinding. It's an OpenGL wrapper library which supports exactly what you ask for:

Feature-Centered Header Design

The OpenGL API is iteratively developed and released in versions,
  internally (for the API specification) named features. The latest
  feature/version of OpenGL is 4.5. The previous version are 1.0, 1.1,
  1.2, 1.3, 1.4, 1.5, 2.0, 2.1, 3.0, 3.1, 3.2, 3.3, 4.0, 4.1, 4.2, 4.3, and 4.4. OpenGL uses a deprecation model for removing outdated parts
  of its API which results in compatibility (with deprecated API) and
  core (without deprecated API) usage that is manifested in the targeted
  OpenGL context. On top of that, new API concepts are suggested as
  extensions (often vendor specific) that might be integrated into
  future versions. All this results in many possible specific
  manifestations of the OpenGL API you can use in your program.

One tough task is to adhere to one agreed set of functions in your own
  OpenGL program (e.g., OpenGL 3.2 Core if you want to develop for every
  Windows, macOS, and Linux released in the last 4 years). glbinding
  facilitates this by providing per-feature headers by means of
  well-defined/generated subsets of the OpenGL API.

All-Features OpenGL Headers

If you do not use per-feature headers the OpenGL program can look like
  this:

```<code>#include <glbinding/gl/gl.h>

// draw code
gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);
gl::glUniform1i(u_numcubes, m_numcubes);
gl::glDrawElementsInstanced(gl::GL_TRIANGLES, 18, gl::GL_UNSIGNED_BYTE, 0, m_numcubes * m_numcubes);
</code>```

Single-Feature OpenGL Headers

When developing your code on Windows with latest drivers installed,
  the code above is likely to compile and run. But if you want to port
  it to systems with less mature driver support (e.g., macOS or Linux
  using open source drivers), you may wonder if glDrawElementsInstanced
  is available. In this case, just switch to per-feature headers of
  glbinding and choose the OpenGL 3.2 Core headers (as you know that at
  least this version is available on all target platforms):

```<code>#include <glbinding/gl32core/gl.h>

// draw code
gl32core::glClear(gl32core::GL_COLOR_BUFFER_BIT | gl32core::GL_DEPTH_BUFFER_BIT);
gl32core::glUniform1i(u_numcubes, m_numcubes);
gl32core::glDrawElementsInstanced(gl32core::GL_TRIANGLES, 18, gl32core::GL_UNSIGNED_BYTE, 0, m_numcubes * m_numcubes);
</code>```

If the code compiles than you can be sure it is OpenGL 3.2 Core
  compliant. Using functions that are not yet available or relying on
  deprecated functionality is prevented.

Body:
Try https://github.com/cginternals/glbinding. It's an OpenGL wrapper library which supports exactly what you ask for:

Feature-Centered Header Design

The OpenGL API is iteratively developed and released in versions,
  internally (for the API specification) named features. The latest
  feature/version of OpenGL is 4.5. The previous version are 1.0, 1.1,
  1.2, 1.3, 1.4, 1.5, 2.0, 2.1, 3.0, 3.1, 3.2, 3.3, 4.0, 4.1, 4.2, 4.3, and 4.4. OpenGL uses a deprecation model for removing outdated parts
  of its API which results in compatibility (with deprecated API) and
  core (without deprecated API) usage that is manifested in the targeted
  OpenGL context. On top of that, new API concepts are suggested as
  extensions (often vendor specific) that might be integrated into
  future versions. All this results in many possible specific
  manifestations of the OpenGL API you can use in your program.

One tough task is to adhere to one agreed set of functions in your own
  OpenGL program (e.g., OpenGL 3.2 Core if you want to develop for every
  Windows, macOS, and Linux released in the last 4 years). glbinding
  facilitates this by providing per-feature headers by means of
  well-defined/generated subsets of the OpenGL API.

All-Features OpenGL Headers

If you do not use per-feature headers the OpenGL program can look like
  this:

#include <glbinding/gl/gl.h>

// draw code
gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);
gl::glUniform1i(u_numcubes, m_numcubes);
gl::glDrawElementsInstanced(gl::GL_TRIANGLES, 18, gl::GL_UNSIGNED_BYTE, 0, m_numcubes * m_numcubes);

Single-Feature OpenGL Headers

When developing your code on Windows with latest drivers installed,
  the code above is likely to compile and run. But if you want to port
  it to systems with less mature driver support (e.g., macOS or Linux
  using open source drivers), you may wonder if glDrawElementsInstanced
  is available. In this case, just switch to per-feature headers of
  glbinding and choose the OpenGL 3.2 Core headers (as you know that at
  least this version is available on all target platforms):

#include <glbinding/gl32core/gl.h>

// draw code
gl32core::glClear(gl32core::GL_COLOR_BUFFER_BIT | gl32core::GL_DEPTH_BUFFER_BIT);
gl32core::glUniform1i(u_numcubes, m_numcubes);
gl32core::glDrawElementsInstanced(gl32core::GL_TRIANGLES, 18, gl32core::GL_UNSIGNED_BYTE, 0, m_numcubes * m_numcubes);

If the code compiles than you can be sure it is OpenGL 3.2 Core
  compliant. Using functions that are not yet available or relying on
  deprecated functionality is prevented.


问:
Program Execution Sequence Differs. Bounces up and down the code (lines) : The code below is "Code-Sheet" / Worksheet_Change-event, Not a "Module"
Set the Break point on the first line, then step through (F8), It can be noted that the program does not follow a top-bottom sequence, instead,  Enters IF block, then leaves IF block,  Re-enter IF block after exiting it (After hitting the End Sub).  Could some one explain please ? </p>

```<code>Private Sub Worksheet_Change(ByVal Tgt As Range)
  If Not IsNumeric(Tgt.Value) Then
    MsgBox "Numbers Only"
    Tgt.ClearContents
    Tgt.Activate
  End If
End Sub
</code>```

答:
Simple. Your code is in the Change event, which gets triggered after each time any cell is changed. But the code itself makes a change so it triggers a call to itself.
To ensure the change the change event makes does not trigger the change event :-) , start the change event with:

```<code>Application.EnableEvents = False
</code>```

Make sure you add

```<code>Application.EnableEvents = True
</code>```

Just above the End Sub line.

Body:
Set the Break point on the first line, then step through (F8), It can be noted that the program does not follow a top-bottom sequence, instead,  Enters IF block, then leaves IF block,  Re-enter IF block after exiting it (After hitting the End Sub).  Could some one explain please ?

Private Sub Worksheet_Change(ByVal Tgt As Range)
  If Not IsNumeric(Tgt.Value) Then
    MsgBox "Numbers Only"
    Tgt.ClearContents
    Tgt.Activate
  End If
End Sub

Body:
Simple. Your code is in the Change event, which gets triggered after each time any cell is changed. But the code itself makes a change so it triggers a call to itself.
To ensure the change the change event makes does not trigger the change event :-) , start the change event with:

Application.EnableEvents = False

Make sure you add

Application.EnableEvents = True

Just above the End Sub line.


问:
View throws error due to asynchronous object loading

I have an Ionic 2 app where one component retrieves a client from a service and provides it as an input on it's child component.  The child component keeps throwing an error because when it's initialized, client is still undefined.

Parent

@Component({
  template: `
        <client-generic [client]="client"></client-generic>
  `,
})

export class TabComponent {
    client:any;
    client_id:any;
    token:any;
    current_user:any;
    constructor(private params: NavParams, private clientService: ClientService) {
        this.client_id = params.get("client_id")
        this.current_user = params.get("current_user")
        this.token = this.current_user.auth_token

        this.clientService.newGetClient(this.client_id, this.token).subscribe(client => {
        this.client = client;

      // Logs properly
      console.log(this.client);
    });
  }
}
```

<p><strong>Child</strong></p>

<pre class="lang-js prettyprint-override"><code>@Component({
  templateUrl: 'client-generic.html',
  selector: 'client-generic'
})

export class ClientGenericPage {
  @Input() client: any;

  constructor(
    public navCtrl: NavController, public navParams: NavParams,
    public modalController: ModalController, private clientService: ClientService) {

    // Logs undefined
    console.log("Client", this.client)
  }
}

ngOnInit() {
    // also logs undefined
    console.log(this.client);
}
</code>```

What can I do to ensure that client is defined in the child?

答:
Please try following changes in your parent component

```<code>@Component({
  template: `
        <client-generic [client]="client" *ngIf="!isLoading"></client-generic>
  `,
})

export class TabComponent {
    client:any;
    client_id:any;
    token:any;
    current_user:any;
    isLoading: boolean = true;
    constructor(private params: NavParams, private clientService: ClientService) {
        this.client_id = params.get("client_id")
        this.current_user = params.get("current_user")
        this.token = this.current_user.auth_token

        this.clientService.newGetClient(this.client_id, this.token).subscribe(client => {
        this.client = client;
        this.isLoading = false;
      // Logs properly
      console.log(this.client);
    });
  }
}
</code>```

You can read this 3 Ways to Pass Async Data to Angular 2+ Child Components to know more about the problem.

Body:
I have an Ionic 2 app where one component retrieves a client from a service and provides it as an input on it's child component.  The child component keeps throwing an error because when it's initialized, client is still undefined.

Parent

@Component({
  template: `
        <client-generic [client]="client"></client-generic>
  `,
})

export class TabComponent {
    client:any;
    client_id:any;
    token:any;
    current_user:any;
    constructor(private params: NavParams, private clientService: ClientService) {
        this.client_id = params.get("client_id")
        this.current_user = params.get("current_user")
        this.token = this.current_user.auth_token

        this.clientService.newGetClient(this.client_id, this.token).subscribe(client => {
        this.client = client;

      // Logs properly
      console.log(this.client);
    });
  }
}

Child

@Component({
  templateUrl: 'client-generic.html',
  selector: 'client-generic'
})

export class ClientGenericPage {
  @Input() client: any;

  constructor(
    public navCtrl: NavController, public navParams: NavParams,
    public modalController: ModalController, private clientService: ClientService) {

    // Logs undefined
    console.log("Client", this.client)
  }
}

ngOnInit() {
    // also logs undefined
    console.log(this.client);
}

What can I do to ensure that client is defined in the child?

Body:
Please try following changes in your parent component

@Component({
  template: `
        <client-generic [client]="client" *ngIf="!isLoading"></client-generic>
  `,
})

export class TabComponent {
    client:any;
    client_id:any;
    token:any;
    current_user:any;
    isLoading: boolean = true;
    constructor(private params: NavParams, private clientService: ClientService) {
        this.client_id = params.get("client_id")
        this.current_user = params.get("current_user")
        this.token = this.current_user.auth_token

        this.clientService.newGetClient(this.client_id, this.token).subscribe(client => {
        this.client = client;
        this.isLoading = false;
      // Logs properly
      console.log(this.client);
    });
  }
}

You can read this 3 Ways to Pass Async Data to Angular 2+ Child Components to know more about the problem.


问:
STM32 flashing through boot loader fails (UART1)
I have an STM32F103 that I'm re-flashing remotely using a different MCU through its UART port (using the boot loader). It works perfectly fine, I have multiple devices that have been successfully flashed with the right code. But occasionally there comes along a device that has stopped working because the STM32 code flashed is not the right one. The whole bin file is flashed using the other MCU, but the STM gets "bricked" (not exactly bricked, it's just has a wrong code). When I re-flash the device using my PC everything is working again. Why would the hex wrote into to the STM fail?

Brief:

*Using UART bootloader to flash STM32F103

*Occasionally this method fails, and so the STM stops working.

*Is there a method to check if the data written into the code space is valid?

*The STM is not bricked, it's just a wrong code inside the flash. When I read back the flash from the code space, this is smaller than the file that should have been flashed.

*I'm using the STM in system boot mode. [AN2606]

答: You can read the data written in STM32's flash using the boot-loader command just the way you write the data (bin file) to flash. This way, you can check if the data written (or new code) written into flash is same as the original binary file. Re-flashing is successful only if these two match, else you can re-attempt to flash the STM32.</p>


问:
Output two futures when they complete in Play 2.5
I'm humbly coming back to the community as I'm obviously in way too deep right now.

So I am trying to return two futures (in Play 2.5.2 in Scala) to screen as modules that appear onscreen when they complete. I've tried quite a few ways of trying to do this. Firstly to note that I have seemingly been able to successfully stream two Sources that have a reoccurring schedule:

```<code>  def streamAction = Action { request =>

    val source1: Source[String, NotUsed] = unfoldAsync(NotUsed) { _ ⇒
      sc.makeServiceCall("stream1").map(x ⇒ Some(NotUsed → x))
    }

    val source2: Source[String, NotUsed] = unfoldAsync(NotUsed) { _ ⇒
      sc.makeServiceCall("stream2").map(x ⇒ Some(NotUsed → x))
    }

    Ok.chunked(source1.merge(source2))
  }
</code>```

Where sc.makeServiceCall refers to:

```<code>   class ServiceClient @Inject() (ws: WSClient) {

     def makeServiceCall(serviceName: String): Future[String] = {
       ws.url(s"http://localhost:9000/mock/$serviceName").get().map(_.body)
     }

   }
</code>```

Which is calling:

```<code>   class Mock @Inject() (actorSystem: ActorSystem)(implicit exec: ExecutionContext) extends Controller {

     def mock(serviceName: String) = Action.async { request =>
       serviceName match {
         case "async1" => respond("asy1", 0.second)
         case "async2" => respond("asy2", 3.second)
         case "async3" => respond("asy3", 5.second)
         case "stream1" => schedule("first", 500.millisecond)
         case "stream2" => schedule("second", 2000.millisecond)
       }
     }

     private def schedule(data: String, delay: FiniteDuration): Future[Result] = {
       akka.pattern.after(delay, actorSystem.scheduler){Future.successful(Ok(data))}
     }

     private def respond(data: String, delay: FiniteDuration): Future[Result] = {
       val promise: Promise[Result] = Promise[Result]()
       actorSystem.scheduler.scheduleOnce(delay) { promise.success(Ok(data)) }
       promise.future
     }

   }
</code>```

So this works (as mentioned) outputting a stream like this:

firstfirstfirstsecondfirstfirstfirstfirstsecondfirstfirstfirstfirstsecond

But in trying to output two futures when they complete (just once each) I cannot. I tried this:

```<code> def outputAction = Action { request =>

   val source1: Source[String, NotUsed] = Source.fromFuture(sc.makeServiceCall("async1"))
   val source2: Source[String, NotUsed] = Source.fromFuture(sc.makeServiceCall("async2"))

   Ok.chunked(source1.merge(source2))
 }
</code>```

This just outputs all at once (when the 2nd future completes)

asys1asys2

What I am doing wrong?

答:
As said in the comments, this seems to be a cache problem on your client side:

I used the following code and called curl -N localhost:9000/stream

```<code>def streamAction = Action { request =>

  val source1: Source[String, NotUsed] = Source.single("async1")

  val source2: Source[String, NotUsed] = Source.single("async2").initialDelay(3.seconds)

  val merged: Source[String, NotUsed] = source1.merge(source2)

  Ok.chunked(merged)
}
</code>```

This returned async1 and 3 seconds later async2, as expected.

Body:
I'm humbly coming back to the community as I'm obviously in way too deep right now.

So I am trying to return two futures (in Play 2.5.2 in Scala) to screen as modules that appear onscreen when they complete. I've tried quite a few ways of trying to do this. Firstly to note that I have seemingly been able to successfully stream two Sources that have a reoccurring schedule:

  def streamAction = Action { request =>

    val source1: Source[String, NotUsed] = unfoldAsync(NotUsed) { _ ⇒
      sc.makeServiceCall("stream1").map(x ⇒ Some(NotUsed → x))
    }

    val source2: Source[String, NotUsed] = unfoldAsync(NotUsed) { _ ⇒
      sc.makeServiceCall("stream2").map(x ⇒ Some(NotUsed → x))
    }

    Ok.chunked(source1.merge(source2))
  }

Where sc.makeServiceCall refers to:

   class ServiceClient @Inject() (ws: WSClient) {

     def makeServiceCall(serviceName: String): Future[String] = {
       ws.url(s"http://localhost:9000/mock/$serviceName").get().map(_.body)
     }

   }

Which is calling:

   class Mock @Inject() (actorSystem: ActorSystem)(implicit exec: ExecutionContext) extends Controller {

     def mock(serviceName: String) = Action.async { request =>
       serviceName match {
         case "async1" => respond("asy1", 0.second)
         case "async2" => respond("asy2", 3.second)
         case "async3" => respond("asy3", 5.second)
         case "stream1" => schedule("first", 500.millisecond)
         case "stream2" => schedule("second", 2000.millisecond)
       }
     }

     private def schedule(data: String, delay: FiniteDuration): Future[Result] = {
       akka.pattern.after(delay, actorSystem.scheduler){Future.successful(Ok(data))}
     }

     private def respond(data: String, delay: FiniteDuration): Future[Result] = {
       val promise: Promise[Result] = Promise[Result]()
       actorSystem.scheduler.scheduleOnce(delay) { promise.success(Ok(data)) }
       promise.future
     }

   }

So this works (as mentioned) outputting a stream like this:

firstfirstfirstsecondfirstfirstfirstfirstsecondfirstfirstfirstfirstsecond

But in trying to output two futures when they complete (just once each) I cannot. I tried this:

 def outputAction = Action { request =>

   val source1: Source[String, NotUsed] = Source.fromFuture(sc.makeServiceCall("async1"))
   val source2: Source[String, NotUsed] = Source.fromFuture(sc.makeServiceCall("async2"))

   Ok.chunked(source1.merge(source2))
 }

This just outputs all at once (when the 2nd future completes)

asys1asys2

What I am doing wrong?

Body:
As said in the comments, this seems to be a cache problem on your client side:

I used the following code and called curl -N localhost:9000/stream

def streamAction = Action { request =>

  val source1: Source[String, NotUsed] = Source.single("async1")

  val source2: Source[String, NotUsed] = Source.single("async2").initialDelay(3.seconds)

  val merged: Source[String, NotUsed] = source1.merge(source2)

  Ok.chunked(merged)
}

This returned async1 and 3 seconds later async2, as expected.


问:
Dynamically add a new filter
Is it possible to add a new filter in the filter chain dynamically? I mean by checking a condition/configuration can we include or exclude a specific filter from the filter chain?</p>

答:
I think it is not possible in the regular web.xml file.

You can think about usage of ServletContainerInitializer. It is a way to programmatically declare you web application config.

It means that you can programmatically set servlets, filters and other things that you can define in the regular web.xml.

E.g. in this question is described how to declare servlets programmatically Map servlet programmatically instead of using web.xml or annotations

If you use Spring framework you can also think about using spring's callbacks to do this. Check this article out How to specify url-pattern for Servlet filters in WebApplicationInitializer?

Title: Dynamically add a new filter


问:
Are there alternative methods for saying 'next' in a pl/sql for loop?
So I've got a for loop that processes a list of IDs and has some fairly complex things to do. Without going into all the ugly details, basically this:

```
    DECLARE
      l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;

      ...snip...
    BEGIN

      -- get the list ids
      l_selected := APEX_UTIL.STRING_TO_TABLE(:P4_SELECT_LIST);
      -- process each in a nice loop
      FOR i IN 1..l_selected.count
      LOOP
        -- do some data checking stuff...

        -- here we will look for duplicate entries, so we can noop if duplicate is found
        BEGIN
          SELECT county_id INTO v_dup_check FROM org_county_accountable
          WHERE organization_id = :P4_ID AND county_id = v_county_id;
          -- NEXT;! NOOP;! but there is no next!
        EXCEPTION WHEN NO_DATA_FOUND THEN
          dbms_output.put_line('no dups found, proceeding');
        END;
        -- here we have code we only want to execute if there are no dupes already
        IF v_dup_check IS NULL THEN
          -- if not a duplicate record, proceed...

        ELSE
          -- reset duplicate check variable
          v_dup_check := NULL;
        END;
      END LOOP;
    END;
```

How I normally handle this is by selecting into a value, and then wrap the following code in an IF statement checking to make sure that duplicate check variable is NULL. But it's annoying. I just want to be able to say NEXT; or NOOP; or something. Especially since I already have to catch the NO_DATA_FOUND exception. I suppose I could write a letter to Oracle, but I'm curious how others handle this.

I could also wrap this in a function, too, but I was looking for something a little cleaner/simpler.

答:
Another way - turn the check into a local function:

```<code>DECLARE
  l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;

  ...snip...
  FUNCTION dup_exists
     ( p_org_id org_county_accountable.organization_id%TYPE
     , p_county_id org_county_accountable.county_id%TYPE
     ) RETURN BOOLEAN
  IS
    v_dup_check org_county_accountable.county_id%TYPE;
  BEGIN
    SELECT county_id INTO v_dup_check FROM org_county_accountable
    WHERE organization_id = p_org_id AND county_id = p_county_id;
    RETURN TRUE;
  EXCEPTION WHEN NO_DATA_FOUND THEN
    RETURN FALSE;
  END;
BEGIN

  -- get the list ids
  l_selected := APEX_UTIL.STRING_TO_TABLE(:P4_SELECT_LIST);
  -- process each in a nice loop
  FOR i IN 1..l_selected.count
  LOOP
    -- do some data checking stuff...

    -- here we have code we only want to execute if there are no dupes already
    IF NOT dup_exists (:P4_ID, v_county_id) THEN
      -- if not a duplicate record, proceed...

    END;
  END LOOP;
END;
</code>```

Of course, the local function could be re-written to use the count method if you prefer:

```<code>  FUNCTION dup_exists
     ( p_org_id org_county_accountable.organization_id%TYPE
     , p_county_id org_county_accountable.county_id%TYPE
     ) RETURN BOOLEAN
  IS
    l_count INTEGER;
  BEGIN
     SELECT COUNT(*) INTO l_count
       FROM org_county_accountable
      WHERE organization_id = p_org_id AND county_id = p_county_id;
     RETURN (l_count > 0);
  END;
</code>```

OwnerDisplayName: Billy Gray

Body:
So I've got a for loop that processes a list of IDs and has some fairly complex things to do. Without going into all the ugly details, basically this:

    DECLARE
      l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;

      ...snip...
    BEGIN

      -- get the list ids
      l_selected := APEX_UTIL.STRING_TO_TABLE(:P4_SELECT_LIST);
      -- process each in a nice loop
      FOR i IN 1..l_selected.count
      LOOP
        -- do some data checking stuff...

        -- here we will look for duplicate entries, so we can noop if duplicate is found
        BEGIN
          SELECT county_id INTO v_dup_check FROM org_county_accountable
          WHERE organization_id = :P4_ID AND county_id = v_county_id;
          -- NEXT;! NOOP;! but there is no next!
        EXCEPTION WHEN NO_DATA_FOUND THEN
          dbms_output.put_line('no dups found, proceeding');
        END;
        -- here we have code we only want to execute if there are no dupes already
        IF v_dup_check IS NULL THEN
          -- if not a duplicate record, proceed...

        ELSE
          -- reset duplicate check variable
          v_dup_check := NULL;
        END;
      END LOOP;
    END;

How I normally handle this is by selecting into a value, and then wrap the following code in an IF statement checking to make sure that duplicate check variable is NULL. But it's annoying. I just want to be able to say NEXT; or NOOP; or something. Especially since I already have to catch the NO_DATA_FOUND exception. I suppose I could write a letter to Oracle, but I'm curious how others handle this.

I could also wrap this in a function, too, but I was looking for something a little cleaner/simpler.

Body:
Another way - turn the check into a local function:

DECLARE
  l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;

  ...snip...
  FUNCTION dup_exists
     ( p_org_id org_county_accountable.organization_id%TYPE
     , p_county_id org_county_accountable.county_id%TYPE
     ) RETURN BOOLEAN
  IS
    v_dup_check org_county_accountable.county_id%TYPE;
  BEGIN
    SELECT county_id INTO v_dup_check FROM org_county_accountable
    WHERE organization_id = p_org_id AND county_id = p_county_id;
    RETURN TRUE;
  EXCEPTION WHEN NO_DATA_FOUND THEN
    RETURN FALSE;
  END;
BEGIN

  -- get the list ids
  l_selected := APEX_UTIL.STRING_TO_TABLE(:P4_SELECT_LIST);
  -- process each in a nice loop
  FOR i IN 1..l_selected.count
  LOOP
    -- do some data checking stuff...

    -- here we have code we only want to execute if there are no dupes already
    IF NOT dup_exists (:P4_ID, v_county_id) THEN
      -- if not a duplicate record, proceed...

    END;
  END LOOP;
END;

Of course, the local function could be re-written to use the count method if you prefer:

  FUNCTION dup_exists
     ( p_org_id org_county_accountable.organization_id%TYPE
     , p_county_id org_county_accountable.county_id%TYPE
     ) RETURN BOOLEAN
  IS
    l_count INTEGER;
  BEGIN
     SELECT COUNT(*) INTO l_count
       FROM org_county_accountable
      WHERE organization_id = p_org_id AND county_id = p_county_id;
     RETURN (l_count > 0);
  END;

OwnerDisplayName: Tony Andrews

LastEditorDisplayName: Tony Andrews


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
I'm not sure why you need a loop if there is a break statement at the end of the loop. Arent you just iterating once, no matter the situation?

Anyway, you'll usually find two differing opinions concerning this on SO, one being that break statements shouldn't be used at all, and one being that it depends on the situation.

I tend to fall in with the latter group, but the way that your loop works uses superfluous break statements. I'd much rather structure such a loop like this:

```<code>bool valid = true;

for(... ; .... && valid == true ; ....)
{
     if (!condition1)
        valid = false;

     if (!condition2)
        valid = false;

     if (!condition3)
        valid = false;

}
</code>```

This allows a loop exit that I think is more elegant.

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
I'm not sure why you need a loop if there is a break statement at the end of the loop. Arent you just iterating once, no matter the situation?

Anyway, you'll usually find two differing opinions concerning this on SO, one being that break statements shouldn't be used at all, and one being that it depends on the situation.

I tend to fall in with the latter group, but the way that your loop works uses superfluous break statements. I'd much rather structure such a loop like this:

bool valid = true;

for(... ; .... && valid == true ; ....)
{
     if (!condition1)
        valid = false;

     if (!condition2)
        valid = false;

     if (!condition3)
        valid = false;

}

This allows a loop exit that I think is more elegant.


问:
Should I always use virtualenvs in Django?
I'm a beginner, and I'm learning Django for web development. So I want to know for my little test, should in always have a virtualenv or can I continue to learn without installing it? I've asked because in youtube Django videos, some instructors are installing it, and others aren't.</p>

答:
From the hitchhiker's guide to python

A Virtual Environment is a tool to keep the dependencies required by
  different projects in separate places, by creating virtual Python
  environments for them. It solves the “Project X depends on version 1.x
  but, Project Y needs 4.x” dilemma, and keeps your global site-packages
  directory clean and manageable.

Meaning if you install all your packages in your local environment, it could collide when you work on multiple projects. Hence having a virtualenv for each project is considered a fail safe.


问:
How can I create a master m3u8 playlist for my encrypted sub-playlists (created with ffmpeg)?
If I create three outputs with the following ffmpeg command for an encrypted HLS stream, how I am able to create a master.m3u8 variant playlist (with correct BANDWIDTH)?

```<code>./ffmpeg -re -i Test_1080p.mp4 \
     -c:a aac -b:a 128k -c:v libx264 -s 1920x1080 -g 48 -keyint_min 48  -sc_threshold 0 -bf 3 -b_strategy 2 -b:v 7800k -maxrate 8600k -bufsize 7800k -f hls -hls_time 6 -hls_list_size 0 -hls_key_info_file enc.keyinfo ./1080p/index.m3u8 \
     -c:a aac -b:a 128k -c:v libx264 -s 1280x720 -g 48 -keyint_min 48 -sc_threshold 0 -bf 3 -b_strategy 2 -b:v 4500k -maxrate 5000k -bufsize 4500k -f hls -hls_time 6 -hls_list_size 0 -hls_key_info_file enc.keyinfo ./720p/index.m3u8 \
    -c:a aac -b:a 64k -c:v libx264 -s 640x360 -g 48 -keyint_min 48 -sc_threshold 0 -bf 3 -b_strategy 2 -b:v 730k -maxrate 800k -bufsize 730k -f hls -hls_time 6 -hls_list_size 0 -hls_key_info_file enc.keyinfo ./360p/index.m3u8
</code>```

Here is some example I found, but I think the BANDWIDTH-Value is not correct for my output files. How do I calculate the correct bandwidth?

```<code>#EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=150000,RESOLUTION=640x360
http://example.com/360p/index.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=240000,RESOLUTION=1280x720
http://example.com/720p/index.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=640000,RESOLUTION=1920x1080
http://example.com/1080p/index.m3u8
</code>```

The variantplaylistcreator-tool from Apple will not work in this case because I need .plist files, ffmpeg does not generate these files.

I think ffmpeg is not able to create a master.m3u8 playlist for the generated output files..

答:
Update January 2018

You can now create master playlists directly with FFmpeg using master_pl_name and var_stream_map. See the documentation.

FFmpeg doesn't create the master playlist but you can do it manually like in the example.

The BANDWIDTH attribute represents the peak bitrate of the variant. For multiplexed streams like yours the value is the peak audio bitrate + peak video bitrate + mux overhead (including any encryption padding). If you have separate video/audio you must take into account the highest-bitrate combination of renditions.

The muxing overhead is shown when the ffmpeg command ends but only if you have a single output. Once you choose the encoding parameters you can run some tests and make an educated guess based on the results.

One thing to keep in mind is that the measured value must be within 10% of the declared bandwidth for VOD and respectively within 25% for 1 hour of live content based on the Apple guidelines.

Body:
If I create three outputs with the following ffmpeg command for an encrypted HLS stream, how I am able to create a master.m3u8 variant playlist (with correct BANDWIDTH)?

./ffmpeg -re -i Test_1080p.mp4 \
     -c:a aac -b:a 128k -c:v libx264 -s 1920x1080 -g 48 -keyint_min 48  -sc_threshold 0 -bf 3 -b_strategy 2 -b:v 7800k -maxrate 8600k -bufsize 7800k -f hls -hls_time 6 -hls_list_size 0 -hls_key_info_file enc.keyinfo ./1080p/index.m3u8 \
     -c:a aac -b:a 128k -c:v libx264 -s 1280x720 -g 48 -keyint_min 48 -sc_threshold 0 -bf 3 -b_strategy 2 -b:v 4500k -maxrate 5000k -bufsize 4500k -f hls -hls_time 6 -hls_list_size 0 -hls_key_info_file enc.keyinfo ./720p/index.m3u8 \
    -c:a aac -b:a 64k -c:v libx264 -s 640x360 -g 48 -keyint_min 48 -sc_threshold 0 -bf 3 -b_strategy 2 -b:v 730k -maxrate 800k -bufsize 730k -f hls -hls_time 6 -hls_list_size 0 -hls_key_info_file enc.keyinfo ./360p/index.m3u8

Here is some example I found, but I think the BANDWIDTH-Value is not correct for my output files. How do I calculate the correct bandwidth?

#EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=150000,RESOLUTION=640x360
http://example.com/360p/index.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=240000,RESOLUTION=1280x720
http://example.com/720p/index.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=640000,RESOLUTION=1920x1080
http://example.com/1080p/index.m3u8

The variantplaylistcreator-tool from Apple will not work in this case because I need .plist files, ffmpeg does not generate these files.

I think ffmpeg is not able to create a master.m3u8 playlist for the generated output files..


问:
Could FAIR scheduling mode make Spark Streaming jobs that read from different topics running in parallel?
I use Spark 2.1 and Kafka 0.9.

Under fair sharing, Spark assigns tasks between jobs in a “round robin” fashion, so that all jobs get a roughly equal share of cluster resources. This means that short jobs submitted while a long job is running can start receiving resources right away and still get good response times, without waiting for the long job to finish.

According to this if i have multiple jobs from multiple threads in case of spark streaming(one topic from each thread) is it possible that multiple topics can run simultaneously if i have enough cores in my cluster or would it just do a round robin across pools but run only one job at a time ?

Context:

I have two topics T1 and T2, both with one 1 partition. I have configured a pool with scheduleMode to be FAIR. I have 4 cores registered with spark. Now each topic has two actions(hence two jobs - totally 4 jobs across topics) Let's say J1 and J2 are jobs for T1 and J3 and J4 are jobs for topic T2. What spark is doing in FAIR mode is execute J1 J3 J2 J4, but at any time only one job is executing. Now as each topic has only one partition, only once core is being used and 3 are just free. This is something which i don't want.
Any way i can avoid this ?

答:
if i have multiple jobs from multiple threads...is it possible that multiple topics can run simultaneously

Yes. That's the purpose of FAIR scheduling mode.

As you may have noticed, I removed "Spark Streaming" from your question since it does not contribute in any way to how Spark schedules Spark jobs. It does not really matter whether you start your Spark jobs from a "regular" application or Spark Streaming one.

Quoting Scheduling Within an Application (highlighting mine):

Inside a given Spark application (SparkContext instance), multiple parallel jobs can run simultaneously if they were submitted from separate threads.

By default, Spark’s scheduler runs jobs in FIFO fashion. Each job is divided into "stages" (e.g. map and reduce phases), and the first job gets priority on all available resources while its stages have tasks to launch, then the second job gets priority, etc.

And then the quote you used to ask the question that should now get clearer.

it is also possible to configure fair sharing between jobs. Under fair sharing, Spark assigns tasks between jobs in a "round robin" fashion, so that all jobs get a roughly equal share of cluster resources.

So, speaking about Spark Streaming you'd have to configure FAIR scheduling mode and Spark Streaming's JobScheduler should submit Spark jobs per topic in parallel (haven't tested it out myself so it's more theory than practice).


问:
Setting up django parallel test in setting.py
Hello I know that it's possible to run tests in django in parallel via --parallel flag eg. python manage.py test --parallel 10. It really speeds up testing in project I'm working for, what is really nice. But Developers in company shares different hardware setups. So ideally I would like to put parallel argument in ./app_name/settings.py so every developer would use at least 4 threads in testing or number of cores provided by multiprocessing lib.

I know that I can make another script let's say run_test.py in which I make use of --parallel, but I would love to make parallel testing 'invisible'.

To sum up - my question is: Can I put number of parallel test runs in settings of django app?
And if answer is yes. There is second question - Would command line argument (X) manage.py --parallel X override settings from './app_name/settings'

Any help is much appreciated.

答:
There is no setting for this, but you can override the test command to set a different default value. In one of your installed apps, create a .management.commands submodule, and add a test.py file. In there you need to subclass the old test command:

```<code>from django.conf import settings
from django.core.management.commands.test import Command as TestCommand

class Command(TestCommand):
    def add_arguments(self, parser):
        super().add_arguments(parser)
        if hasattr(settings, 'TEST_PARALLEL_PROCESSES'):
            parser.set_defaults(parallel=settings.TEST_PARALLEL_PROCESSES)
</code>```

This adds a new default to the --parallel flag. Running python manage.py test --parallel=1 will still override the default.

Body:
There is no setting for this, but you can override the test command to set a different default value. In one of your installed apps, create a .management.commands submodule, and add a test.py file. In there you need to subclass the old test command:

from django.conf import settings
from django.core.management.commands.test import Command as TestCommand

class Command(TestCommand):
    def add_arguments(self, parser):
        super().add_arguments(parser)
        if hasattr(settings, 'TEST_PARALLEL_PROCESSES'):
            parser.set_defaults(parallel=settings.TEST_PARALLEL_PROCESSES)

This adds a new default to the --parallel flag. Running python manage.py test --parallel=1 will still override the default.


问:
IE version 8.07 Session Lost on Hyperlink click within authenticated session (asp.net)
After logging in (authorization) within my application a session is created and I am being redirected to correct location (SSL page).  However, after clicking on a hyperlink (non SSL page within same application) I am being logged out automatically (authenticated session lost).  I tested the same in FireFox 3.6 and the application is working as expected.

The above is only happening if i clear the chache from IE and log in.  However, if I login for second time after just closing the browser the above does not occur.

Thanks,

Lihnid

答: What do your URLs look like before login and after login?  This kinda thing happened to me before, and it turned out that my authn cookies were having trouble with a domain change from www.domain.com to domain.com or visa versa.</p>


问:
React access type prop via passed variable
I have a type with many properties, and I was wondering if it's possible to use one function to update any of the properties. So for example I have

```<code>export type RequestData = {
  Status: string,
  RequestDate: Moment,
  RequesterName: string,
  RequesterId: number,
  BudgetCategory: string,
  BudgetSubcategory: string,
  BudgetTeamCode: string
}
</code>```

I can update BudgetSubcategory with this

```<code>interface ConnectedState {
  requestData: Store.RequestData
}

interface ConnectedDispatch {
  updateRequestData: (requestData: Store.RequestData) => void
}

function mapStateToProps(state: Store.All): ConnectedState {
  return {
    requestData: getRequestData(state),
  }
}

function mapDispatchToProps(dispatch: Redux.Dispatch<Store.All>): ConnectedDispatch {
return {
  updateRequestData: (requestData: Store.RequestData) => dispatch(updateRequestData(requestData))
 };
}

class MainContainer extends React.Component<OwnProps & ConnectedState & ConnectedDispatch, {}> {
  constructor(props, context) {
    super(props, context);
  }

  updateBudgetSubcategory = (subcategory: string) => {
    this.props.updateRequestData({...this.props.requestData, BudgetSubcategory: subcategory });
   }
}
</code>```

I want to be able to update any of these props one at a time, without having to create a separate function for each of them. Is it possible to pass a property name along with the value to do something like

```<code>updateRequestDataProperty = (propertyToUpdate: string, value: string) => {
  this.props.updateRequestData({...this.props.requestData, propertyToUpdate: value });
}
</code>```

答:
you want to use computed properties:</p>

```<code>updateRequestDataProperty = (propertyToUpdate, value) => {
  this.props.updateRequestData({
    ...this.props.requestData,
    [propertyToUpdate]: value  // field name: value of `propertyToUpdate`
  });
};
</code>```

Body:
I have a type with many properties, and I was wondering if it's possible to use one function to update any of the properties. So for example I have

export type RequestData = {
  Status: string,
  RequestDate: Moment,
  RequesterName: string,
  RequesterId: number,
  BudgetCategory: string,
  BudgetSubcategory: string,
  BudgetTeamCode: string
}

I can update BudgetSubcategory with this

interface ConnectedState {
  requestData: Store.RequestData
}

interface ConnectedDispatch {
  updateRequestData: (requestData: Store.RequestData) => void
}

function mapStateToProps(state: Store.All): ConnectedState {
  return {
    requestData: getRequestData(state),
  }
}

function mapDispatchToProps(dispatch: Redux.Dispatch<Store.All>): ConnectedDispatch {
return {
  updateRequestData: (requestData: Store.RequestData) => dispatch(updateRequestData(requestData))
 };
}

class MainContainer extends React.Component<OwnProps & ConnectedState & ConnectedDispatch, {}> {
  constructor(props, context) {
    super(props, context);
  }

  updateBudgetSubcategory = (subcategory: string) => {
    this.props.updateRequestData({...this.props.requestData, BudgetSubcategory: subcategory });
   }
}

I want to be able to update any of these props one at a time, without having to create a separate function for each of them. Is it possible to pass a property name along with the value to do something like

updateRequestDataProperty = (propertyToUpdate: string, value: string) => {
  this.props.updateRequestData({...this.props.requestData, propertyToUpdate: value });
}

Body:
you want to use computed properties:

updateRequestDataProperty = (propertyToUpdate, value) => {
  this.props.updateRequestData({
    ...this.props.requestData,
    [propertyToUpdate]: value  // field name: value of `propertyToUpdate`
  });
};


问:
Can I pass a method to apply_async or map in python multiprocessing?
How can I get the following to work? The main point is that I want to run a method (and not a function) asynchronously.

```<code>from multiprocessing import Pool

class Async:
    def __init__(self, pool):
        self.pool = pool
        self.run()

    def run(self):
        p.apply_async(self.f, (10, ))

    def f(self, x):
        print x*x

if __name__ == '__main__':
    p = Pool(5)
    a = Async(p)
    p.close()
    p.join()
</code>```

This prints nothing.

答:
The problem appears to be due to the fact that multiprocessing needs to pickle self.f while bound methods are not picklable.  There is a discussion on how to solve the problem here.

The apply_async apparently creates an exception which is put inside the future returned. That's why nothing is printed. If a get is executed on the future, then the exception is raised.

Body:
How can I get the following to work? The main point is that I want to run a method (and not a function) asynchronously.

from multiprocessing import Pool

class Async:
    def __init__(self, pool):
        self.pool = pool
        self.run()

    def run(self):
        p.apply_async(self.f, (10, ))

    def f(self, x):
        print x*x

if __name__ == '__main__':
    p = Pool(5)
    a = Async(p)
    p.close()
    p.join()

This prints nothing.


问:
How to find elapsed time interval
```<code>void Wait(Single wait_time)
{
    Single start_time;
    Single end_time;
    Single ellapsed_time;

    ellapsed_time = 0;
    start_time = DateTime.Now.Second;
    while (ellapsed_time<=wait_time)
    {
        end_time = DateTime.Now.Second;
        ellapsed_time = end_time - start_time;
    }
}
</code>```

The code above is in C# and it works according to my colleague. The goal is to tell the machine to wait for a certain time, then continue after that. For example, when Wait(5) is triggered, the machine won't continue until elapsed time is greater than 5.  I'm trying to do the same thing in C++/CLI. Here is my code :

```<code>void Wait(Single wait_time)
{
    Single start_time;
    Single end_time;
    Single ellapsed_time;

    ellapsed_time = 0;
    start_time = DateTime::Now;

    while (ellapsed_time <= wait_time) {
        end_time = DateTime::Now;
        ellapsed_time = end_time - start_time;

    }

}
</code>```

I get this error:

no suitable conversion function from System::DateTime to float exists

I tried TimeSpan as well, but it didn't work. Is there a better way to do this?

答:
C#

```<code>System.Threading.Thread.Sleep(5000);
</code>```

C++

```<code> #include <chrono>
 #include <thread>

 int main() {
 using namespace std::this_thread;
 using namespace std::chrono;
 sleep_until(system_clock::now() + seconds(5));
 }
</code>```

The above code will make your application sleep for 5 seconds.

Or i have seen people use

```<code> Thread::Sleep(100);
</code>```

In terms of CLI .

Title: How to find elapsed time interval

Body:
void Wait(Single wait_time)
{
    Single start_time;
    Single end_time;
    Single ellapsed_time;

    ellapsed_time = 0;
    start_time = DateTime.Now.Second;
    while (ellapsed_time<=wait_time)
    {
        end_time = DateTime.Now.Second;
        ellapsed_time = end_time - start_time;
    }
}

The code above is in C# and it works according to my colleague. The goal is to tell the machine to wait for a certain time, then continue after that. For example, when Wait(5) is triggered, the machine won't continue until elapsed time is greater than 5.  I'm trying to do the same thing in C++/CLI. Here is my code :

void Wait(Single wait_time)
{
    Single start_time;
    Single end_time;
    Single ellapsed_time;

    ellapsed_time = 0;
    start_time = DateTime::Now;

    while (ellapsed_time <= wait_time) {
        end_time = DateTime::Now;
        ellapsed_time = end_time - start_time;

    }

}

I get this error:

no suitable conversion function from System::DateTime to float exists

I tried TimeSpan as well, but it didn't work. Is there a better way to do this?

Body:
C#

System.Threading.Thread.Sleep(5000);

C++

 #include <chrono>
 #include <thread>

 int main() {
 using namespace std::this_thread;
 using namespace std::chrono;
 sleep_until(system_clock::now() + seconds(5));
 }

The above code will make your application sleep for 5 seconds.

Or i have seen people use

 Thread::Sleep(100);

In terms of CLI .


问:
onchange="" doesn't work in select tag
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

```<code><select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>
<style type="text/css">
    #a , #b , #c , #d , #f , #g , #h , #j , #k , #e , #i {
        display: none;
    }
</style>
</code>```

JS:

```<code>$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});
</code>```

And after run the code the css code which I  want don't launch.
What's the problem here ?

答:
Try using the .change() event :

HTML

```<code><select name="study-phase" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>
</code>```

JS

```<code> $(function(){
   $('#study-phase').change(function(){
     if ($("#study-phase").val() == "pri") {
        $("#a").css('display','block');
     }
   });

 });
</code>```

Title: onchange="" doesn't work in select tag

Body:
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

<select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>

JS:

$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});

And after run the code the css code which I  want don't launch.
What's the problem here ?

Body:
Try using the .change() event :

HTML

<select name="study-phase" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>

JS

 $(function(){
   $('#study-phase').change(function(){
     if ($("#study-phase").val() == "pri") {
        $("#a").css('display','block');
     }
   });

 });