问:
Video streaming through socket and playing from client
I have two simple programmes, server and client, both at localhost. What I want to do is to streaming the video from the server to the client through socket and the client can play it by using filediscriptor of the socket. First I try to send some message and the client can receive it. After that I send a few bytes of the video from the server'sd card to the client. The client can receive those bytes but cannot play it. Anyone know how to solve the problem?

Here is my server and client code snippets:

Server:

```<code>        //Receive request from client.
     Socket client=serversocket.accept();
     System.out.println("accept");

     //Receive client message.
     BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
     String str=in.readLine();
     System.out.println("read:"+str);

     //Send message to client.
     //PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
     //out.println("server message");
     FileInputStream fis=new FileInputStream("/sdcard/toystory3.3gp");
     byte buffer[]=new byte[2000];
     fis.read(buffer,0,20);
     DataOutputStream out=new DataOutputStream(client.getOutputStream());
     out.write(buffer,0,20);
     in.close();
     out.close();
     client.close();
     System.out.println("close");
</code>```

Client:

```<code> Socket socket=new Socket("127.0.0.1",4444);
 String message="Initial"+"\r\n";
 //Send message to server.
 PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
 out.println(message);

 //Receive message from server.
 BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
 String msg=br.readLine();
 //ParcelFileDescriptor pfd=ParcelFileDescriptor.fromSocket(socket);
 //MediaPlayer m=new MediaPlayer();
 //m.setDataSource(pfd.getFileDescriptor());
 //m.prepare();
 //m.start();

 if(msg!=null)
 {
  System.out.println("Data received.");
  System.out.println(msg);
 }
 else
 {
  System.out.println("Data not received.");
 }
 out.close();
 br.close();
 socket.close();
</code>```

答:
I tried to port ffmpeg to android to solve the problem of video and streaming formats for android. But I found out that building ffmpeg for android with all the network stuff is pretty hard.

RTSP has a lot of configuration for streaming, I managed to get something like you want with the MediaPlayer and stuff, you should try to get to know the formats that you are streaming from (vlc in that case) a little better.

Also, take a lot at darwin streaming server its easy to configure, I was able to stream to an android device using it.

Body:
I have two simple programmes, server and client, both at localhost. What I want to do is to streaming the video from the server to the client through socket and the client can play it by using filediscriptor of the socket. First I try to send some message and the client can receive it. After that I send a few bytes of the video from the server'sd card to the client. The client can receive those bytes but cannot play it. Anyone know how to solve the problem?

Here is my server and client code snippets:

Server:

        //Receive request from client.
     Socket client=serversocket.accept();
     System.out.println("accept");

     //Receive client message.
     BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
     String str=in.readLine();
     System.out.println("read:"+str);

     //Send message to client.
     //PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
     //out.println("server message");
     FileInputStream fis=new FileInputStream("/sdcard/toystory3.3gp");
     byte buffer[]=new byte[2000];
     fis.read(buffer,0,20);
     DataOutputStream out=new DataOutputStream(client.getOutputStream());
     out.write(buffer,0,20);
     in.close();
     out.close();
     client.close();
     System.out.println("close");

Client:

 Socket socket=new Socket("127.0.0.1",4444);
 String message="Initial"+"\r\n";
 //Send message to server.
 PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
 out.println(message);

 //Receive message from server.
 BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
 String msg=br.readLine();
 //ParcelFileDescriptor pfd=ParcelFileDescriptor.fromSocket(socket);
 //MediaPlayer m=new MediaPlayer();
 //m.setDataSource(pfd.getFileDescriptor());
 //m.prepare();
 //m.start();

 if(msg!=null)
 {
  System.out.println("Data received.");
  System.out.println(msg);
 }
 else
 {
  System.out.println("Data not received.");
 }
 out.close();
 br.close();
 socket.close();


来源: stackexchange

问:
SQL Server: Select Max for each sub group in result set
I am new to SQL Server. I have a table that contains user names, addresses and the update dates.

The following query gives me all required details from that table but my problem is that the table can contain multiple records for the same user / ID in case they changed their address more than once.

How can I only get the address from the latest update for each user / ID?  I tried with DISTINCT, TOP1 etc. but couldn't figure out a way to make this work.

My query:

```<code>SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC
</code>```

答:
Go with ROW_NUMBER

```<code>SELECT * FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY  u.ID ORDER BY u.updateDate DESC ) AS SNO
    , u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
    FROM dbo.Users u
)A
WHERE A.SNO=1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to SQL Server. I have a table that contains user names, addresses and the update dates.

The following query gives me all required details from that table but my problem is that the table can contain multiple records for the same user / ID in case they changed their address more than once.

How can I only get the address from the latest update for each user / ID?  I tried with DISTINCT, TOP1 etc. but couldn't figure out a way to make this work.

My query:

SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC

Body:
Go with ROW_NUMBER

SELECT * FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY  u.ID ORDER BY u.updateDate DESC ) AS SNO
    , u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
    FROM dbo.Users u
)A
WHERE A.SNO=1


问:
Counter not working when use if check
When I click on my button I am trying to check the label-category has been created

($('#label-' + category_name).length === 0) {

For some reason if i use  ($('#label-' + category_name).length === 0) { it is stopping the counter.

Question: How can I make sure that can get the counter to work when have this if ($('#label-' + category_name).length === 0) {

I use codeigniter frame work also if that helps

Example how should perform here

```<code><script type="text/javascript">
var counter = 0;

$(document).on('click', '.category_title', function(e){

    e.preventDefault();

    var category_name = $(this).attr('data-name');
    var category_id = $(this).attr('data-id');

    if ($('#label-' + category_name).length === 0) {

        switch(counter) {
            case 0:
                element = 'label-default';
                break;
            case 1:
                element = 'label-primary';
                break;
            case 2:
                element = 'label-success';
                break;
            case 3:
                element = 'label-info';
                break;
            case 4:
                element = 'label-warning';
                break;
        }

        counter = (counter + 1) % 5;

        html = '';
        html += '<li id="label-'+category_name+'">';
        html += '<span class="label ' + element + '">';
        html += category_name;
        html += '</span>';
        html += '</li>';

        $('.categories ul').append(html);

    }

    $('.categories-panel').html("");
});
</script>
</code>```

Full code

```<code><?php if ($categories) {?>
    <div class="panel panel-default">
        <div class="panel-body">
            <?php
            foreach (array_chunk($categories, 4) as $category) {
            ?>
                <div class="row">
                    <?php
                    foreach ($category as $category) {
                    ?>
                        <div class="col-sm-4">
                            <div class="media">
                                <div class="media-left">
                                    <a href="#"></a>
                                </div>
                                <div class="media-body">
                                    <h4 class="media-heading" style="cursor: pointer;">
                                        <span
                                            class="category_title"
                                            id="category_title"
                                            data-name="<?php echo $category['name'];?>"
                                            data-id="<?php echo $category['category_id'];?>"
                                        >
                                            <?php echo $category['name'];?>
                                        </span>
                                    </h4>
                                    <?php
                                    echo $category['description'];
                                    ?>
                                </div>
                            </div>
                        </div>
                    <?php
                    }
                    ?>
                </div>
            <?php
            }
            ?>
        </div>
    </div>
<?php
}
?>

<script type="text/javascript">
var counter = 0;

$(document).on('click', '.category_title', function(e){

    e.preventDefault();

    var category_name = $(this).attr('data-name');
    var category_id = $(this).attr('data-id');

    if ($('#label-' + category_name).length === 0) {

        switch(counter) {
            case 0:
                element = 'label-default';
                break;
            case 1:
                element = 'label-primary';
                break;
            case 2:
                element = 'label-success';
                break;
            case 3:
                element = 'label-info';
                break;
            case 4:
                element = 'label-warning';
                break;
        }

        counter = (counter + 1) % 5;

        html = '';
        html += '<li id="label-'+category_name+'">';
        html += '<span class="label ' + element + '">';
        html += category_name;
        html += '</span>';
        html += '</li>';

        $('.categories ul').append(html);

    }

    $('.categories-panel').html("");
});
</script>
</code>```

ask.php

```<code><div class="container">
    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        </div>
    </div>

    <?php
    echo form_open(
        'questions/ask/submit',
        array(
            'id' => 'post-form'
        )
    );
    ?>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <input
                    type="text"
                    name="ask_title"
                    id="ask_title"
                    placeholder="Question Title"
                    class="form-control"
                />
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <textarea
                    name="ask_message"
                    id="ask_message"
                    class="form-control"
                    rows="15"
                    placeholder="Your message..."
                ></textarea>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="categories">
                <ul class="list-inline"></ul>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <input
                    type="text"
                    name="category_name"
                    id="category_name"
                    class="form-control"
                    placeholder="Choose category"
                />
                <div class="categories-panel"></div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <input
                    type="submit"
                    name="submit_button"
                    id="submit_button"
                    class="btn btn-default"
                />
            </div>
        </div>
    </div>

    <?php echo form_close();?>
</div>

<script type="text/javascript">
    $( document ).ready(function() {
        $("#category_name").on('keyup', function(e){
            $.ajax({
                url: '<?php echo base_url('questions/ask/getcategories');?>',
                type: "post",
                data: {
                    category_name: $('#category_name').val()
                },
                dataType: 'json',
                success: function(json){
                    $('.categories-panel').html(json);
                }
            });
        });
    });
</script>
</code>```

答:
Unfortunately, your answer is not clear enough, but I guess the following code can help you. The first time I press the button, the if statement works, as there's no label with the given ID. The second time, it doesn't as there's already an element with the given ID.

I guess that your problem is the way you set the ID. I tried your code, and I found that the statement '
' is the issue.

If for example, the category_name is like that: This Is A String the label id it is going to be like this: ... that prevents the jQuery to match the element.

What I did in my case, was the replace the spaces with - and lowercase the string ( the lowercase it is not important ), and this way, the jQuery can now match the label ids.

Also keep in mind that if you use the string with special characters, you may also need to replace them as well.

(
  function($, window, undefined) {

    var counter = 0;
    var button = $( '.category_title' );

    if ( 0 < button.length ) {
      button.on(
        'click',
        function ( e ) {
          e.preventDefault();

          var me = $( this );
          var category_name = me.attr( 'data-name' );
          var category_id = me.attr( 'data-id' );
          var id = category_name.replace( /\s+/g, '-' ).toLowerCase();
          var label = $( '#label-' + id );
          var label_class = '';

          if ( 0 === label.length ) {
            switch ( counter ) {
              case 0:
                label_class = 'label-default';
                break;
              case 1:
                label_class = 'label-primary';
                break;
              case 2:
                label_class = 'label-success';
                break;
              case 3:
                label_class = 'label-info';
                break;
              case 4:
                label_class = 'label-warning';
                break;
            }
          }

          counter = (counter + 1) % 5;

          html = '';
          html += '
';
          html += '';
          html += '{text}';
          html += '';
          html += '
';

          html = html
                  .replace( /\{id\}/, id )
                  .replace( /\{class\}/, label_class )
                  .replace( /\{text\}/, category_name );

          $('.categories ul').append(html);

        }
      );
    }

  }
)(jQuery, this);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Click Me
<div class="categories">
  <ul></ul>
</div></code>```

Hope this is what you are looking for.

Note, I have also done a short refactoring to this code, in order to make it isolated from other code in your site.

Title: Counter not working when use if check

Body:
When I click on my button I am trying to check the label-category has been created

($('#label-' + category_name).length === 0) {

For some reason if i use  ($('#label-' + category_name).length === 0) { it is stopping the counter.

Question: How can I make sure that can get the counter to work when have this if ($('#label-' + category_name).length === 0) {

I use codeigniter frame work also if that helps

Example how should perform here

Full code

<?php if ($categories) {?>

            <?php
            foreach (array_chunk($categories, 4) as $category) {
            ?>

                    <?php
                    foreach ($category as $category) {
                    ?>

                                        <span
                                            class="category_title"
                                            id="category_title"
                                            data-name="<?php echo $category['name'];?>"
                                            data-id="<?php echo $category['category_id'];?>"
                                        >
                                            <?php echo $category['name'];?>

                                    <?php
                                    echo $category['description'];
                                    ?>

                    <?php
                    }
                    ?>

            <?php
            }
            ?>

<?php
}
?>

ask.php

    <?php
    echo form_open(
        'questions/ask/submit',
        array(
            'id' => 'post-form'
        )
    );
    ?>

                <input
                    type="text"
                    name="ask_title"
                    id="ask_title"
                    placeholder="Question Title"
                    class="form-control"
                />

                <textarea
                    name="ask_message"
                    id="ask_message"
                    class="form-control"
                    rows="15"
                    placeholder="Your message..."
                ></textarea>

                <input
                    type="text"
                    name="category_name"
                    id="category_name"
                    class="form-control"
                    placeholder="Choose category"
                />

                <input
                    type="submit"
                    name="submit_button"
                    id="submit_button"
                    class="btn btn-default"
                />

    <?php echo form_close();?>

Body:
Unfortunately, your answer is not clear enough, but I guess the following code can help you. The first time I press the button, the if statement works, as there's no label with the given ID. The second time, it doesn't as there's already an element with the given ID.

I guess that your problem is the way you set the ID. I tried your code, and I found that the statement '<li id="label-'+category_name+'">' is the issue.

If for example, the category_name is like that: This Is A String the label id it is going to be like this: <label class="label-This Is A String">...</label> that prevents the jQuery to match the element.

What I did in my case, was the replace the spaces with - and lowercase the string ( the lowercase it is not important ), and this way, the jQuery can now match the label ids.

Also keep in mind that if you use the string with special characters, you may also need to replace them as well.

(
  function($, window, undefined) {

    var counter = 0;
    var button = $( '.category_title' );

    if ( 0 < button.length ) {
      button.on(
        'click',
        function ( e ) {
          e.preventDefault();

          var me = $( this );
          var category_name = me.attr( 'data-name' );
          var category_id = me.attr( 'data-id' );
          var id = category_name.replace( /\s+/g, '-' ).toLowerCase();
          var label = $( '#label-' + id );
          var label_class = '';

          if ( 0 === label.length ) {
            switch ( counter ) {
              case 0:
                label_class = 'label-default';
                break;
              case 1:
                label_class = 'label-primary';
                break;
              case 2:
                label_class = 'label-success';
                break;
              case 3:
                label_class = 'label-info';
                break;
              case 4:
                label_class = 'label-warning';
                break;
            }
          }

          counter = (counter + 1) % 5;

          html = '';
          html += '<li id="label-{id}">';
          html += '<span class="label {class}">';
          html += '{text}';
          html += '</span>';
          html += '</li>';

          html = html
                  .replace( /\{id\}/, id )
                  .replace( /\{class\}/, label_class )
                  .replace( /\{text\}/, category_name );

          $('.categories ul').append(html);

        }
      );
    }

  }
)(jQuery, this);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="category_title" data-name="This Is A Test" data-id="this-is-the-id">Click Me</a>
<div class="categories">
  <ul></ul>
</div>

Hope this is what you are looking for.

Note, I have also done a short refactoring to this code, in order to make it isolated from other code in your site.


问:
knockout.js ul li databinding not proper
HTML

```<code><h4>People</h4>
<ul data-bind="foreach: people">
    <li>
        <span data-bind="text: name"> </span>
        <a href="#" data-bind="click: $parent.removePerson">Remove</a>
    </li>
</ul>
<button data-bind="click: addPerson">Add</button>
<input type="text" data-bind="value: cardtext" /><br /><br /><br />
</code>```

JS

```<code>function AppViewModel() {
    var self = this;
    self.cardtext=ko.observable();

   self.people = ko.observableArray([
       { name: 'Bert' },
       { name: 'Charles' },
       { name: 'Denise' }
   ]);

   self.addPerson = function() {
      self.people.push({ name: self.cardtext });
   };

   self.removePerson = function() {
      self.people.remove(this);
   }
}
ko.applyBindings(new AppViewModel());
</code>```

This is the result

The problem is that the textbox keep adding new elements but the previous newly added elements keep getting updated by the new elements.

3rd element was 3rd element

4th element was 4th element

when I added 5th element the 3rd and the 4th element get updated by 5th element.
why it is that? what I am doing wrong?. I have no idea.

答:
You just need to add () at the end of self.cardtext(). If you don't put the parenthesis, what it will do is it will push the observable object of cardtext to the array instead of its value. So when you modify cardtext from the textbox, it will also modify the previous object that was pushed.

function AppViewModel() {
  var self = this;
  self.cardtext=ko.observable();
  self.people = ko.observableArray([
    { name: 'Bert' },
    { name: 'Charles' },
    { name: 'Denise' }
  ]);

  self.addPerson = function() {
    self.people.push({ name: self.cardtext() });
  };

  self.removePerson = function() {
    self.people.remove(this);
  }
}
ko.applyBindings(new AppViewModel());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<h4>People</h4>
<ul data-bind="foreach: people">
  <li>
    <span data-bind="text: name"> </span>
    Remove
  </li>
</ul>
<button data-bind="click: addPerson">Add</button>
<input type="text" data-bind="value: cardtext" /><br /><br /><br /></code>```

Body:
HTML

People

        Remove

<button data-bind="click: addPerson">Add</button>
<input type="text" data-bind="value: cardtext" />

JS

function AppViewModel() {
    var self = this;
    self.cardtext=ko.observable();

   self.people = ko.observableArray([
       { name: 'Bert' },
       { name: 'Charles' },
       { name: 'Denise' }
   ]);

   self.addPerson = function() {
      self.people.push({ name: self.cardtext });
   };

   self.removePerson = function() {
      self.people.remove(this);
   }
}
ko.applyBindings(new AppViewModel());

This is the result

The problem is that the textbox keep adding new elements but the previous newly added elements keep getting updated by the new elements.

3rd element was 3rd element

4th element was 4th element

when I added 5th element the 3rd and the 4th element get updated by 5th element.
why it is that? what I am doing wrong?. I have no idea.

Body:
You just need to add () at the end of self.cardtext(). If you don't put the parenthesis, what it will do is it will push the observable object of cardtext to the array instead of its value. So when you modify cardtext from the textbox, it will also modify the previous object that was pushed.

function AppViewModel() {
  var self = this;
  self.cardtext=ko.observable();
  self.people = ko.observableArray([
    { name: 'Bert' },
    { name: 'Charles' },
    { name: 'Denise' }
  ]);

  self.addPerson = function() {
    self.people.push({ name: self.cardtext() });
  };

  self.removePerson = function() {
    self.people.remove(this);
  }
}
ko.applyBindings(new AppViewModel());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<h4>People</h4>
<ul data-bind="foreach: people">
  <li>
    <span data-bind="text: name"> </span>
    <a href="#" data-bind="click: $parent.removePerson">Remove</a>
  </li>
</ul>
<button data-bind="click: addPerson">Add</button>
<input type="text" data-bind="value: cardtext" /><br /><br /><br />


问:
How to print string by awk in special format?
it's that able to convert following string

```
3.840527449999989,6A3,06,67,07,DF,0D,63,81,AA
4.306243875,601,02,3E,80,00,00,00,00,00
```

to format string like below

```
3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00
```

Note that:

timestamps should postfix 0 if necessary

data bytes should remove , between them

答:
This might work for you (GNU sed):

```<code>sed ':a;/^[0-9.]\{17\},/!s/,/0,/;ta;s/,/ /3g' file
</code>```

If the first field is not length 17 insert a 0 until it is, then replace the third , onwards with a space.

N.B. pre-supposes that the first field is not longer than 17 and that this field is number of the type shown. Also that the record layout is as the example and field two does not contain a , i.e. is not a quoted field.

Body:
it's that able to convert following string

3.840527449999989,6A3,06,67,07,DF,0D,63,81,AA
4.306243875,601,02,3E,80,00,00,00,00,00

to format string like below

3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00

Note that:

timestamps should postfix 0 if necessary

data bytes should remove , between them

Body:
This might work for you (GNU sed):

sed ':a;/^[0-9.]\{17\},/!s/,/0,/;ta;s/,/ /3g' file

If the first field is not length 17 insert a 0 until it is, then replace the third , onwards with a space.

N.B. pre-supposes that the first field is not longer than 17 and that this field is number of the type shown. Also that the record layout is as the example and field two does not contain a , i.e. is not a quoted field.


问:
Phpmailer how allowed user to upload only pdf or docs in PHP
How can i restrict users to upload only PDF or DOCS format through contact form.

I tried but unable to get over this problem. Any help over this will help me a lot.

Here is my code.

```<code><?php
require('phpmailer/class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port     = 587;
$mail->Username = "";
$mail->Password = "";
$mail->Host     = "smtp.gmail.com";
$mail->Mailer   = "smtp";
$mail->From = $_POST["userEmail"];
$mail->FromName = $_POST['userName'];
//$mail->SetFrom($_POST["userEmail"]);
$mail->AddReplyTo($_POST["userEmail"], $_POST["userName"]);
$mail->AddAddress("");
$mail->Subject = "Career request by " . $_POST['userName'];
$mail->WordWrap   = 80;
// /$mail->MsgHTML($_POST["userName"]."\r\n"$_POST["userEmail"]);
$mail->MsgHTML("Applicant Name: ".$_POST['userName']."<br/><br/>Applicant Email: ".$_POST['userEmail']." <br/><br/>Applicant Mobile Number: ".$_POST['userPhone']."<br/><br/> Job Applied For : ".$_POST['jobApplied']);
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']);
}

$mail->IsHTML(true);

if(!$mail->Send()) {
    echo "<p class='error'>Problem in Sending Mail.</p>";
} else {
    echo "<p class='success'>Contact Mail Sent.</p>";
}
?>
</code>```

Thank you..

答:
You can check your uploaded file using so many ways for example:</p>

```<code>$file = explode('.', strtolower($_FILES['attachmentFile']['name']));
$extension = end($file);
$allowed_types = ["pdf", "docs"];

if (!in_array($extension, $allowed_types)) {
   echo "Allowed types are pdf and docs.";
} else {
   // send your email
}
</code>```

Body:
How can i restrict users to upload only PDF or DOCS format through contact form.

I tried but unable to get over this problem. Any help over this will help me a lot.

Here is my code.

<?php
require('phpmailer/class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port     = 587;
$mail->Username = "";
$mail->Password = "";
$mail->Host     = "smtp.gmail.com";
$mail->Mailer   = "smtp";
$mail->From = $_POST["userEmail"];
$mail->FromName = $_POST['userName'];
//$mail->SetFrom($_POST["userEmail"]);
$mail->AddReplyTo($_POST["userEmail"], $_POST["userName"]);
$mail->AddAddress("");
$mail->Subject = "Career request by " . $_POST['userName'];
$mail->WordWrap   = 80;
// /$mail->MsgHTML($_POST["userName"]."\r\n"$_POST["userEmail"]);
$mail->MsgHTML("Applicant Name: ".$_POST['userName']."

Applicant Email: ".$_POST['userEmail']."

Applicant Mobile Number: ".$_POST['userPhone']."

 Job Applied For : ".$_POST['jobApplied']);
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']);
}

$mail->IsHTML(true);

if(!$mail->Send()) {
    echo "
Problem in Sending Mail.
";
} else {
    echo "
Contact Mail Sent.
";
}
?>

Thank you..

Body:
You can check your uploaded file using so many ways for example:

$file = explode('.', strtolower($_FILES['attachmentFile']['name']));
$extension = end($file);
$allowed_types = ["pdf", "docs"];

if (!in_array($extension, $allowed_types)) {
   echo "Allowed types are pdf and docs.";
} else {
   // send your email
}


问:
Android ADB stop application command like "force-stop" for non rooted device
I'm trying to stop application on Android 2.3.7 device. But in this version of Android I can't use "force-stop" command. Do you know any other ways to close application on non rooted device?</p>

答:
To kill from the application, you can do:</p>

```<code>android.os.Process.killProcess(android.os.Process.myPid());
</code>```

Body:
To kill from the application, you can do:

android.os.Process.killProcess(android.os.Process.myPid());


问:
Trying to display live table which is editable using ajax and php
I have four different files

```<code>index.php
select.php
insert.php
edit.php
delete.php
</code>```

In my backend I have created a database named 'ecc'

Database 'ecc' has atable named 'task'

The table task has following fields

id, name, category, cost

Datatype for id set to int and index as primary also id field is on auto increment

My Issue:My code is only displaying 'Live Table Data'.

It would be grate if someone rewrite it or suggest some changes.

index.php

```<code><html>
      <head>
           <title>Live Table Data Edit</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      </head>
      <body>
           <div class="container">
                <br />
                <br />
                <br />
                <div class="table-responsive">
                     <h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
                     <div id="live_data"></div>
                </div>
           </div>
      </body>
 </html>
 <script>

 $(document).ready(function(){
      function fetch_data()
      {
           $.ajax({
                url:"select.php",
                method:"POST",
                success:function(data){
                     $('#live_data').html(data);
                }
           });
      }

 fetch_data();
      $(document).on('click', '#btn_add', function(){

           var name = $('#name').text();
           var category = $('#category').text();
           var cost = $('#cost').text();

           if(name == '')
           {
                alert("Enter Service Name");
                return false;
           }

           if(category == '')
           {
                alert("Enter Category of Service");
                return false;
           }

           if(cost == '')
           {
                alert("Enter cost");
                return false;
           }
           $.ajax({
                url:"insert.php",
                method:"POST",
                data:{name:name, category:category, cost:cost},
                dataType:"text",
                success:function(data)
                {
                     alert(data);
                     fetch_data();
                }
           })
      });
      function edit_data(id, text, column_name)
      {
           $.ajax({
                url:"edit.php",
                method:"POST",
                data:{id:id, text:text, column_name:column_name},
                dataType:"text",
                success:function(data){
                     alert(data);
                }
           });
      }
      $(document).on('blur', '.name', function(){
           var id = $(this).data("id1");
           var name = $(this).text();
           edit_data(id, name, "name");
      });
      $(document).on('blur', '.category', function(){
           var id = $(this).data("id2");
           var category = $(this).text();
           edit_data(id,category, "category");

      $(document).on('blur', '.cost', function(){
           var id = $(this).data("id3");
           var category = $(this).text();
           edit_data(id,cost, "cost");
      });

      $(document).on('click', '.btn_delete', function(){
           var id=$(this).data("id4");
           if(confirm("Are you sure you want to delete this?"))
           {
                $.ajax({
                     url:"delete.php",
                     method:"POST",
                     data:{id:id},
                     dataType:"text",
                     success:function(data){
                          alert(data);
                          fetch_data();
                     }
                });
           }
      });
 });
 </script>
</code>```

select.php

```<code><?php
 $connect = mysqli_connect("localhost", "root", "", "ecc");
 $output = '';
 $sql = "SELECT * FROM task ORDER BY id DESC";
 $result = mysqli_query($connect, $sql);
 $output .= '
      <div class="table-responsive">
           <table class="table table-bordered">
                <tr>
                     <th width="10%">Id</th>
                     <th width="40%">First Name</th>
                     <th width="40%">Last Name</th>
                     <th width="10%">Delete</th>
                </tr>';
 if(mysqli_num_rows($result) > 0)
 {
      while($row = mysqli_fetch_array($result))
      {
           $output .= '
                <tr>
                     <td>'.$row["id"].'</td>
                     <td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
                     <td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
                     <td class="cost" data-id3="'.$row["id"].'" contenteditable>'.$row["cost"].'</td>
                     <td><button type="button" name="delete_btn" data-id4="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
                </tr>
           ';
      }
      $output .= '
           <tr>
                <td></td>
                <td id="name" contenteditable></td>
                <td id="category" contenteditable></td>
                <td id="cost" contenteditable></td>
                <td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
           </tr>
      ';
 }
 else
 {
      $output .= '<tr>
                          <td colspan="4">Data not Found</td>
                     </tr>';
 }
 $output .= '</table>
      </div>';
 echo $output;
 ?>
</code>```

insert.php

```<code><?php
 $connect = mysqli_connect("localhost", "root", "", "test_db");
 $sql = "INSERT INTO tbl_sample(name, category, cost) VALUES('".$_POST["name"]."', '".$_POST["category"]."', '".$_POST["cost"]."')";
 if(mysqli_query($connect, $sql))
 {
      echo 'Data Inserted';
 }
 ?>
</code>```

edit.php

```<code><?php
 $connect = mysqli_connect("localhost", "root", "", "ecc");
 $id = $_POST["id"];
 $text = $_POST["text"];
 $column_name = $_POST["column_name"];
 $sql = "UPDATE task SET ".$column_name."='".$text."' WHERE id='".$id."'";
 if(mysqli_query($connect, $sql))
 {
      echo 'Data Updated';
 }
 ?>
</code>```

delete.php

```<code><?php
 $connect = mysqli_connect("localhost", "root", "", "ecc");
 $sql = "DELETE FROM task WHERE id = '".$_POST["id"]."'";
 if(mysqli_query($connect, $sql))
 {
      echo 'Data Deleted';
 }
 ?>
</code>```

答:
you can use data tables for this, no need of all this

https://editor.datatables.net/examples/inline-editing/simple

check this, data tables provide libraries for this

Body:
I have four different files

index.php
select.php
insert.php
edit.php
delete.php

In my backend I have created a database named 'ecc'

Database 'ecc' has atable named 'task'

The table task has following fields

id, name, category, cost

Datatype for id set to int and index as primary also id field is on auto increment

My Issue:My code is only displaying 'Live Table Data'.

It would be grate if someone rewrite it or suggest some changes.

index.php

           <title>Live Table Data Edit</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

Live Table Add Edit Delete using Ajax Jquery in PHP Mysql

select.php

<?php
 $connect = mysqli_connect("localhost", "root", "", "ecc");
 $output = '';
 $sql = "SELECT * FROM task ORDER BY id DESC";
 $result = mysqli_query($connect, $sql);
 $output .= '

                     Id
                     First Name
                     Last Name
                     Delete

';
 if(mysqli_num_rows($result) > 0)
 {
      while($row = mysqli_fetch_array($result))
      {
           $output .= '

                     '.$row["id"].'
                     '.$row["name"].'
                     '.$row["category"].'
                     '.$row["cost"].'
                     <button type="button" name="delete_btn" data-id4="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button>

           ';
      }
      $output .= '

                <button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button>

      ';
 }
 else
 {
      $output .= '

                          Data not Found

';
 }
 $output .= '

';
 echo $output;
 ?>

insert.php

<?php
 $connect = mysqli_connect("localhost", "root", "", "test_db");
 $sql = "INSERT INTO tbl_sample(name, category, cost) VALUES('".$_POST["name"]."', '".$_POST["category"]."', '".$_POST["cost"]."')";
 if(mysqli_query($connect, $sql))
 {
      echo 'Data Inserted';
 }
 ?>

edit.php

<?php
 $connect = mysqli_connect("localhost", "root", "", "ecc");
 $id = $_POST["id"];
 $text = $_POST["text"];
 $column_name = $_POST["column_name"];
 $sql = "UPDATE task SET ".$column_name."='".$text."' WHERE id='".$id."'";
 if(mysqli_query($connect, $sql))
 {
      echo 'Data Updated';
 }
 ?>

delete.php

<?php
 $connect = mysqli_connect("localhost", "root", "", "ecc");
 $sql = "DELETE FROM task WHERE id = '".$_POST["id"]."'";
 if(mysqli_query($connect, $sql))
 {
      echo 'Data Deleted';
 }
 ?>


问:
How to create table using angular from inside request callback function
I'm trying to create a table using angular. The problem is that I need to create that table based on JSON response from my http request (at which point I call the responseHandler function below:

```<code>function call(){
    $.ajax({
        url: url
        , type: "GET"
        , success: function (response, status, xhr) {

            responseHandler(response);
        }
        , error: function (xhr, status, error) {}
    });
}

 function responseHandler(response) {
    var data = angular.fromJson(response);
    var user = angular.fromJson(data['users']);
    userdata = user['data'];// this is correctly assigning the data I
                                // need to the variable userdata
    var tApp = angular.module('tApp', []);
    tApp.controller('tCtrl', ['$scope', function ($scope) {

        $scope.userdata = userdata;
        $("#usertable").css("visibility", "visible");
    }]);
 }
</code>```

Here is my html:

```<code><div ng-app="tApp" ng-controller="tCtrl" class="tab-content clearfix" id='tCtrl'>
<table id='usertable' border="1">
                        <tr ng-repeat="x in userdata">
                            <td>{{x.name}}</td>
                            <td>{{x.id}}</td>
                            <td>{{x.picture.data.url}}</td>
                        </tr>
                    </table>
</div>
</code>```

I keep getting the angular.js:14516 Error: [$controller:ctrlreg] error.
So it seems my controller is not being recognize by angular. Any ideas?

Thank you!

答:
If you are using angular, you should completely stop using JQuery, the asynchronous ajax call will mess up your application really hard because of angular's digest loop.

It's also a best practice to split the data-fetching into a different service, as it sometimes gets messy really fast and pollutes the controllers with a lot of code without application logic.

And because you don't use JQuery, you don't need to place ID in elements.

HTML:

```<code><div ng-app="tApp" ng-controller="tCtrl" class="tab-content clearfix">
  <table border="1" ng-show="userdata.length > 0">
    <tr ng-repeat="x in userdata">
      <td>{{x.name}}</td>
      <td>{{x.id}}</td>
      <td>{{x.picture.data.url}}</td>
    </tr>
  </table>
</div>
</code>```

Javascript

```<code>var tApp = angular.module('tApp', []);

tApp.factory('dataFetchingService', ['$http', function ($http) {
  return {
    getUserData: function() {
      $http.get('/someUrl/to/userData')
        .then(
          response => response.data,
          error => console.error(error)
        );
    }
  };
}]);

tApp.controller('tCtrl', ['$scope', 'dataFetchingService', function ($scope, dataFetchingService) {
    $scope.userdata = [];

    dataFetchingService.getUserData().then(userData => {
      $scope.userdata = userData;
    });
}]);
</code>```

Body:
I'm trying to create a table using angular. The problem is that I need to create that table based on JSON response from my http request (at which point I call the responseHandler function below:

function call(){
    $.ajax({
        url: url
        , type: "GET"
        , success: function (response, status, xhr) {

            responseHandler(response);
        }
        , error: function (xhr, status, error) {}
    });
}

 function responseHandler(response) {
    var data = angular.fromJson(response);
    var user = angular.fromJson(data['users']);
    userdata = user['data'];// this is correctly assigning the data I
                                // need to the variable userdata
    var tApp = angular.module('tApp', []);
    tApp.controller('tCtrl', ['$scope', function ($scope) {

        $scope.userdata = userdata;
        $("#usertable").css("visibility", "visible");
    }]);
 }

Here is my html:

                            {{x.name}}
                            {{x.id}}
                            {{x.picture.data.url}}

I keep getting the angular.js:14516 Error: [$controller:ctrlreg] error.
So it seems my controller is not being recognize by angular. Any ideas?

Thank you!

Body:
If you are using angular, you should completely stop using JQuery, the asynchronous ajax call will mess up your application really hard because of angular's digest loop.

It's also a best practice to split the data-fetching into a different service, as it sometimes gets messy really fast and pollutes the controllers with a lot of code without application logic.

And because you don't use JQuery, you don't need to place ID in elements.

HTML:

<div ng-app="tApp" ng-controller="tCtrl" class="tab-content clearfix">
  <table border="1" ng-show="userdata.length > 0">
    <tr ng-repeat="x in userdata">
      <td>{{x.name}}</td>
      <td>{{x.id}}</td>
      <td>{{x.picture.data.url}}</td>
    </tr>
  </table>
</div>

Javascript

var tApp = angular.module('tApp', []);

tApp.factory('dataFetchingService', ['$http', function ($http) {
  return {
    getUserData: function() {
      $http.get('/someUrl/to/userData')
        .then(
          response => response.data,
          error => console.error(error)
        );
    }
  };
}]);

tApp.controller('tCtrl', ['$scope', 'dataFetchingService', function ($scope, dataFetchingService) {
    $scope.userdata = [];

    dataFetchingService.getUserData().then(userData => {
      $scope.userdata = userData;
    });
}]);


问:
Provide an image for WhatsApp link sharing
How can we include an image in our website to display in WhatsApp when we share a link like this?

答:
2020 standards

It takes a few steps to get the perfect preview for WhatsApp, Twitter, Facebook and bookmark icons for pc's and mobile devices. If you like reading go to Open Graph (ogp.me) - but make sure to read steps 1 - 6 in this answer to get the best WhatsApp preview.

Results of many tech audits by different companies show having Open Graph tags won’t help you get a better SEO ranking, they are only for social media. schema.org's data structures will help you with SEO.

These Open Graph <meta> tags go inside the  tag.

Please note: @jaimish11 mentioned some apps or websites use cache or even store the website preview in their database. This means when you're testing your link in WhatsApp or Facebook for example, you'll most likely not see any difference right away. Using another link (another page) will do the trick. But as soon as you use that link once, this "please note" section starts all over again.

Step 1: title

Maximum of 65 characters

```<code><title>your keyword rich title of the website and/or webpage</title>
</code>```

Step 2: description

Maximum of 155 characters

```<code><meta name="description" content="description of your website/webpage, make sure you use keywords!" />
</code>```

Step 3: og:title

Maximum 35 characters

```<code><meta property="og:title" content="short title of your website/webpage" />
</code>```

Step 4: og:url

Full link to the current webpage address

```<code><meta property="og:url" content="https://www.example.com/webpage/" />
</code>```

Step 5: og:description

Maximum 65 characters

```<code><meta property="og:description" content="description of your website/webpage" />
</code>```

Step 6: og:image

Image(JPG or PNG) with a size less than 300KB and minimum dimensions of 300 x 200 *. This image should be served via a HTTPS connection with a valid non-self-signed certificate.**

```<code><meta property="og:image" content="//cdn.example.com/uploads/images/webpage_300x200.png" />
</code>```

* @RichDeBourke mentioned this to me, but apparently WhatsApp has increased its maximum image size (dimensions as well as file size). I did some tests: it does not work consistently every time on every device. I tested 2.x Mb images and even that seemed to work 9/10 times. <300KB is the safest approach, but you should be fine using larger images as of 18-02-2020. I would recommend keeping the file size below 2MB, though. And definitely throw your image through TinyPNG or any other image compression algorithm if you haven't already.

** @Indraraj mentioned the image may not show up if your site runs on https with a self-signed certificate.

If you completed the steps above, you can now see your preview in WhatsApp! However, be aware of the "please note" section above.

Step 7: og:type

In order for your object to be represented within the graph, you need to specify its type. Here's a list of the global types available: http://ogp.me/#types. You can also specify your own types.

```<code><meta property="og:type" content="article" />
</code>```

Step 8: og:locale

The locale of the resource. You can also use og:locale:alternate if you have other language translations available.

If you don't specify og:locale, it defaults to en_US.

```<code><meta property="og:locale" content="en_GB" />
<meta property="og:locale:alternate" content="fr_FR" />
<meta property="og:locale:alternate" content="es_ES" />
</code>```

Step 9: Twitter

For the best Twitter support read this.

Step 10: Facebook

For the best Facebook support read this.

Step 11: favicon

For the best favicon support for all browsers and devices read this.

Bonus step 12: video/audio

It's also possible to share audio/video. Facebook and Twitter for example share videos very well. Read ogp.me. And of course WhatsApp has this option as well: when you share an Instagram or Youtube link, the WhatsApp preview comes with the in-app video player.

Super bonus step 13: products, persons, movies etc.

This kind of information really depends on the provider (Facebook, Google). I don't know when, but WhatsApp and Twitter could enable support for products. This way, the persons you share the link with, might see the price, average review score in the shared link "widget". That would be nice. This already exists for business accounts who have their Catalog up-to-date in their WhatsApp Business app, but this is totally different than link sharing.

Body:
2020 standards

It takes a few steps to get the perfect preview for WhatsApp, Twitter, Facebook and bookmark icons for pc's and mobile devices. If you like reading go to Open Graph (ogp.me) - but make sure to read steps 1 - 6 in this answer to get the best WhatsApp preview.

Results of many tech audits by different companies show having Open Graph tags won’t help you get a better SEO ranking, they are only for social media. schema.org's data structures will help you with SEO.

These Open Graph <meta> tags go inside the <head> tag.

Please note: @jaimish11 mentioned some apps or websites use cache or even store the website preview in their database. This means when you're testing your link in WhatsApp or Facebook for example, you'll most likely not see any difference right away. Using another link (another page) will do the trick. But as soon as you use that link once, this "please note" section starts all over again.

Step 1: title

Maximum of 65 characters

<title>your keyword rich title of the website and/or webpage</title>

Step 2: description

Maximum of 155 characters

<meta name="description" content="description of your website/webpage, make sure you use keywords!" />

Step 3: og:title

Maximum 35 characters

<meta property="og:title" content="short title of your website/webpage" />

Step 4: og:url

Full link to the current webpage address

<meta property="og:url" content="https://www.example.com/webpage/" />

Step 5: og:description

Maximum 65 characters

<meta property="og:description" content="description of your website/webpage" />

Step 6: og:image

Image(JPG or PNG) with a size less than 300KB and minimum dimensions of 300 x 200 *. This image should be served via a HTTPS connection with a valid non-self-signed certificate.**

<meta property="og:image" content="//cdn.example.com/uploads/images/webpage_300x200.png" />

* @RichDeBourke mentioned this to me, but apparently WhatsApp has increased its maximum image size (dimensions as well as file size). I did some tests: it does not work consistently every time on every device. I tested 2.x Mb images and even that seemed to work 9/10 times. <300KB is the safest approach, but you should be fine using larger images as of 18-02-2020. I would recommend keeping the file size below 2MB, though. And definitely throw your image through TinyPNG or any other image compression algorithm if you haven't already.

** @Indraraj mentioned the image may not show up if your site runs on https with a self-signed certificate.

If you completed the steps above, you can now see your preview in WhatsApp! However, be aware of the "please note" section above.

Step 7: og:type

In order for your object to be represented within the graph, you need to specify its type. Here's a list of the global types available: http://ogp.me/#types. You can also specify your own types.

<meta property="og:type" content="article" />

Step 8: og:locale

The locale of the resource. You can also use og:locale:alternate if you have other language translations available.

If you don't specify og:locale, it defaults to en_US.

<meta property="og:locale" content="en_GB" />
<meta property="og:locale:alternate" content="fr_FR" />
<meta property="og:locale:alternate" content="es_ES" />

Step 9: Twitter

For the best Twitter support read this.

Step 10: Facebook

For the best Facebook support read this.

Step 11: favicon

For the best favicon support for all browsers and devices read this.

Bonus step 12: video/audio

It's also possible to share audio/video. Facebook and Twitter for example share videos very well. Read ogp.me. And of course WhatsApp has this option as well: when you share an Instagram or Youtube link, the WhatsApp preview comes with the in-app video player.

Super bonus step 13: products, persons, movies etc.

This kind of information really depends on the provider (Facebook, Google). I don't know when, but WhatsApp and Twitter could enable support for products. This way, the persons you share the link with, might see the price, average review score in the shared link "widget". That would be nice. This already exists for business accounts who have their Catalog up-to-date in their WhatsApp Business app, but this is totally different than link sharing.

ContentLicense: CC BY-SA 4.0


问:
Wikipedia special features list
I am searching for the complete Wikipedia Feature list. I know there are some feature functions in Wikipedia like Wikiquote:Quote_of_the_day.

Or is there a Media Wiki which describes the standard functions?

答:
I got the answer for my question. This is what i was searching for, maybe others would find it useful. This lists all the speical properties

https://en.wikipedia.org/wiki/Help:Special_page

Title: Wikipedia special features list


问:
link error with "undefined lua_xxxxx" when building lsnes
In my ubuntu 14.xx, I try to compile lsnes emulator to use the mario-ai script from aleju/mario-ai, and I've tried to google many solutions to solve the problem below:

Here is the output from the console:

make[3]: __all__.files' is up to date.
  make[3]: Leaving directory/home/pengsuyu/software/lsnes/sourcecode/src/platform/macosx'
  make[2]: Leaving directory /home/pengsuyu/software/lsnes/sourcecode/src/platform'
  g++ -o lsnescat all_common.files all_platform.files-pthread -lboost_iostreams -lboost_filesystem -lboost_system -lz  -lgcrypt -lgpg-error  -L/usr/lib/x86_64-linux-gnu -lcurl -rdynamic -ldlcat core/all.ldflags lua/all.ldflags fonts/all.ldflags library/all.ldflags interface/all.ldflags video/all.ldflags emulation/all.ldflags cmdhelp/all.ldflags platform/all.ldflags
  core/multitrack.o: In functionlua::state::get_string(int, std::string const&)':
  /home/pengsuyu/software/lsnes/sourcecode/src/core/../../include/library/lua-base.hpp:317: undefined reference to lua_tolstring'
  core/multitrack.o: In functionlua::state::get_bool(int, std::string const&)':
  /home/pengsuyu/software/lsnes/sourcecode/src/core/../../include/library/lua-base.hpp:334: undefined reference to lua_toboolean'
  core/multitrack.o: In functionlua::state::type(int)':
  .
  .
  /home/pengsuyu/software/lsnes/sourcecode/src/library/lua.cpp:536: undefined reference to lua_close'
  library/lua.o: In functionlua::state::pushcfunction(int ()(lua_State))':
  /home/pengsuyu/software/lsnes/sourcecode/src/library/../../include/library/lua-base.hpp:504: undefined reference to lua_pushcclosure'
  library/lua.o: In functionlua::state::getfield(int, char const*)':
  /home/pengsuyu/software/lsnes/sourcecode/src/library/../../include/library/lua-base.hpp:506: undefined reference to lua_getfield'
  library/lua.o: In functionlua::state::insert(int)':
  /home/pengsuyu/software/lsnes/sourcecode/src/library/../../include/library/lua-base.hpp:509: undefined reference to lua_insert'
  collect2: error: ld returned 1 exit status
  make[1]: *** [lsnes] Error 1
  make[1]: Leaving directory/home/pengsuyu/software/lsnes/sourcecode/src'
  make: *** [src/all_files] Error 2

==================================

At the beginning, I think, the linker cannot find my lua library. So I tried to compile my main.cpp with test.lua.

main.cpp:

```<code>#include <stdio.h>
#include <iostream>

//extern "C"
//{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
//} // liblua5.1-c++.a
lua_State * L;
int main ()
{
     L = lua_open();
     luaL_openlibs(L);
     luaL_dofile(L, "d:\\test.lua");
     return 0;
}
</code>```

test.lua:

```<code>print("Hello World");
</code>```

I write a MakeFile to generate the executable file "main":

```<code>main:main.o
    gcc -o $@ $< -llua5.1 -lstdc++
main.o:
    gcc -c main.cpp
clean:
    -rm *.o
</code>```

It works when I add the compile option "-llua5.1" and "-lstdc++" otherwise it throws the same error as I compiled lsnes

I am not familiar with gcc and Makefile. Please help me to solve this problem.

答:
I've solved my question

The way to solve this problem is just to change one line in the file named "options.build".

```<code>1. find the line "LUA=lua" in options.build

2. change this line to "LUA=lua5.1"
</code>```

because the needed library is 5.1, so if you want to build it successfully, you must use the "lua5.1" library however the default configuration is "lua" not "lua5.1"

Body:
In my ubuntu 14.xx, I try to compile lsnes emulator to use the mario-ai script from aleju/mario-ai, and I've tried to google many solutions to solve the problem below:

Here is the output from the console:

make[3]: __all__.files' is up to date.
  make[3]: Leaving directory/home/pengsuyu/software/lsnes/sourcecode/src/platform/macosx'
  make[2]: Leaving directory /home/pengsuyu/software/lsnes/sourcecode/src/platform'
  g++ -o lsnescat all_common.files all_platform.files-pthread -lboost_iostreams -lboost_filesystem -lboost_system -lz  -lgcrypt -lgpg-error  -L/usr/lib/x86_64-linux-gnu -lcurl -rdynamic -ldlcat core/all.ldflags lua/all.ldflags fonts/all.ldflags library/all.ldflags interface/all.ldflags video/all.ldflags emulation/all.ldflags cmdhelp/all.ldflags platform/all.ldflags
  core/multitrack.o: In functionlua::state::get_string(int, std::string const&)':
  /home/pengsuyu/software/lsnes/sourcecode/src/core/../../include/library/lua-base.hpp:317: undefined reference to lua_tolstring'
  core/multitrack.o: In functionlua::state::get_bool(int, std::string const&)':
  /home/pengsuyu/software/lsnes/sourcecode/src/core/../../include/library/lua-base.hpp:334: undefined reference to lua_toboolean'
  core/multitrack.o: In functionlua::state::type(int)':
  .
  .
  /home/pengsuyu/software/lsnes/sourcecode/src/library/lua.cpp:536: undefined reference to lua_close'
  library/lua.o: In functionlua::state::pushcfunction(int ()(lua_State))':
  /home/pengsuyu/software/lsnes/sourcecode/src/library/../../include/library/lua-base.hpp:504: undefined reference to lua_pushcclosure'
  library/lua.o: In functionlua::state::getfield(int, char const*)':
  /home/pengsuyu/software/lsnes/sourcecode/src/library/../../include/library/lua-base.hpp:506: undefined reference to lua_getfield'
  library/lua.o: In functionlua::state::insert(int)':
  /home/pengsuyu/software/lsnes/sourcecode/src/library/../../include/library/lua-base.hpp:509: undefined reference to lua_insert'
  collect2: error: ld returned 1 exit status
  make[1]: *** [lsnes] Error 1
  make[1]: Leaving directory/home/pengsuyu/software/lsnes/sourcecode/src'
  make: *** [src/all_files] Error 2

==================================

At the beginning, I think, the linker cannot find my lua library. So I tried to compile my main.cpp with test.lua.

main.cpp:

#include <stdio.h>
#include <iostream>

//extern "C"
//{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
//} // liblua5.1-c++.a
lua_State * L;
int main ()
{
     L = lua_open();
     luaL_openlibs(L);
     luaL_dofile(L, "d:\\test.lua");
     return 0;
}

test.lua:

print("Hello World");

I write a MakeFile to generate the executable file "main":

main:main.o
    gcc -o $@ $< -llua5.1 -lstdc++
main.o:
    gcc -c main.cpp
clean:
    -rm *.o

It works when I add the compile option "-llua5.1" and "-lstdc++" otherwise it throws the same error as I compiled lsnes

I am not familiar with gcc and Makefile. Please help me to solve this problem.

Body:
I've solved my question

The way to solve this problem is just to change one line in the file named "options.build".

1. find the line "LUA=lua" in options.build

2. change this line to "LUA=lua5.1"

because the needed library is 5.1, so if you want to build it successfully, you must use the "lua5.1" library however the default configuration is "lua" not "lua5.1"


问:
Laravel 5.4 migrate key is too long error
when I run migrate command with laravel 5.4 I get an error "specific key was too long", I searched and found many people also face this error. The common is add Schema::defaultStringLength(191); in AppServiceProvider.php. But the doc https://laravel-news.com/laravel-5-4-key-too-long-error says it is for those mysql version older than 5.7.7. But my version is 5.7.14(mysql  Ver 14.14 Distrib 5.7.14, for Win64 (x86_64)), and I already set mysql default charset to utf8mb4(show variables like "%char%"):

So I think I do not need to change anything but I still get the problem. It makes me confused. Who can help me? Thanks.

答: I think you should make sure you have set innodb_large_prefix to On. According to documentation it should be default in Mysql >= 5.7.7 but maybe you use non-standard settings.


问:
understanding some concepts in java generics
So I came across this code while studying linkedlists. The code here uses generics and I am having problem understanding some of the things here.

```<code>public static class Node<E>
{
     E element;
     Node <E> next;
    public Node(E e,Node <E> n)
    {
        element=e;
        next=n;System.out.println(next);
    }
    public E getelement() {return element;}
    public Node<E> getnext(){ return next;}
    public void setnext(Node <E> n)
    {
        next=n;
    }
}
</code>```

So what does class Node <E> mean?
I think E element; means  element is of type E. Am I right?
Node <E> next; what does this mean?

答:
The <E> by the class name declares that E as a generic type parameter - this means any instance of Node will be of some type, and this type will be decided by the code that instantiates it.  new Node<String>() will create a node of type String, new Node<Integer>() creates a node of type Integer, and so on.

Where E is used in the class then reflects whatever type a particular instance has chosen, so if a have a node of type String, I know that element will be a String, and next will be a reference to another node containing a String.

The beauty of generics is that using this type parameter means I don't need to write a copy of this class for each type I want to use, while also being sure that all of the references will be of the type I expect - I won't get next returning an Integer when I'm expecting a String.

The link JB Nizet provides is a very good one - generics are quite a large and subtle topic, and if you wnat to learn about generics that tutorial will help you a lot.

Body:
So I came across this code while studying linkedlists. The code here uses generics and I am having problem understanding some of the things here.

public static class Node<E>
{
     E element;
     Node <E> next;
    public Node(E e,Node <E> n)
    {
        element=e;
        next=n;System.out.println(next);
    }
    public E getelement() {return element;}
    public Node<E> getnext(){ return next;}
    public void setnext(Node <E> n)
    {
        next=n;
    }
}

So what does class Node <E> mean?
I think E element; means  element is of type E. Am I right?
Node <E> next; what does this mean?


答:
You need to (1) Group your user ID; (2) sort descending your updateDate and (3) DISTINCT your user ID as below:

```<code>SELECT
    DISTINCT u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID
ORDER BY u.updateDate DESC
</code>```

Title: SQL Server: Select Max for each sub group in result set

Body:
I am new to SQL Server. I have a table that contains user names, addresses and the update dates.

The following query gives me all required details from that table but my problem is that the table can contain multiple records for the same user / ID in case they changed their address more than once.

How can I only get the address from the latest update for each user / ID?  I tried with DISTINCT, TOP1 etc. but couldn't figure out a way to make this work.

My query:

SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC

Body:
You need to (1) Group your user ID; (2) sort descending your updateDate and (3) DISTINCT your user ID as below:

SELECT
    DISTINCT u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID
ORDER BY u.updateDate DESC


问:
Run a command in a shell and keep running the command when you close the session
I am using Putty to connect to a remote server. What I want to know is if there is any way to write my commands and allow them to keep running after I close the session with Putty. The reason for this is that I do not want to keep the computer ON all the time. Is there any way to do this?.

Update with the solution

For my question as it is presented the best solution is use one of the commands provided such as nohup, because you do not have to install any additional software. But if you are in the same problem use screen, install it and use it. It is amazing.

I have selected the answer of Norman Ramsey as favourite because propose several solutions using commands and screen. But please check the other answers specially the one of PEZ, then you get an insight of what screen is able todo.

答: nohup, disown, and screen are all good but screen is the best because unlike the other two, screen allows you to disconnect from the remote server, keep everything running, and then reconnect later to see what is happening.  With nohup and disown you can't resume interacting.

OwnerDisplayName: Eduardo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eduardo

OwnerDisplayName: Norman Ramsey


问:
Debugging not working in ASP.NET Core, or in VS2017 at all
I am working on a project, and I have two servers, a login server, and a secondary server which serves the application.

The secondary server is ASP.NET Core, but the first one is just ASP.NET MVC, because I couldn't get Identity to work with tokens for Angular 2, in ASP.NET Core. In Visual Studio 2015, breakpoints worked for ASP.NET MVC, but not for ASP.NET Core.

I moved to Visual Studio 2017 in the hope it would fix things. No breakpoints are hit at all, although my A2 project works, the methods are being called.

The debugger says that there's no debug information for the code.  I've gone in to project settings and told it to generate the full pdb (at the bottom of build settings, under 'advanced'), I've turned off 'just my code' and turned on .NET code breaks. These are all the suggestions I can find online. My breakpoints are still not being hit.

答:
OK, it seems I got a web.config file from somewhere, like this:

```<code>   <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>
</code>```

I don't know how it got here, but if I comment it out, debugging works...

Body:
OK, it seems I got a web.config file from somewhere, like this:

   <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>

I don't know how it got here, but if I comment it out, debugging works...


问:
applescript does not run from terminal
why doesn't my applescript run from terminal  I can run it successfully from the editor

I run command

```<code>/usr/bin/osascript -e my_script.scpt
</code>```

I get error

0:12: syntax error: A unknown token can’t go after this identifier. (-2740)

my script

```<code>set volume 2
set x to 0
open location "spotify:user:wunspe:playlist:meininki"
tell application "Spotify"
    set the sound volume to 0
    play
    repeat 10 times
        if sound volume is less than 70 then
            set sound volume to (sound volume + 10)
            set x to (x + 9)
            set volume output volume x without output muted --100%

            delay 3
        end if
    end repeat

end tell
</code>```

答:
To run a compiled script (file) you have to omit the -e flag and pass the full path to the script

```<code>/usr/bin/osascript /Users/myUser/path/to/my_script.scpt
</code>```

Title: applescript does not run from terminal

Body:
why doesn't my applescript run from terminal  I can run it successfully from the editor

I run command

/usr/bin/osascript -e my_script.scpt

I get error

0:12: syntax error: A unknown token can’t go after this identifier. (-2740)

my script

set volume 2
set x to 0
open location "spotify:user:wunspe:playlist:meininki"
tell application "Spotify"
    set the sound volume to 0
    play
    repeat 10 times
        if sound volume is less than 70 then
            set sound volume to (sound volume + 10)
            set x to (x + 9)
            set volume output volume x without output muted --100%

            delay 3
        end if
    end repeat

end tell

Body:
To run a compiled script (file) you have to omit the -e flag and pass the full path to the script

/usr/bin/osascript /Users/myUser/path/to/my_script.scpt


问:
How can i convert linux "date +%s" output to a more readable format in bash script
Here is the script:

```<code>
#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

</code>
```

so i want to convert $startTime into a UTC format

答:
What format are you looking for? Simply executing date with -u Will give you a readable output format of UTC time, ie:</p>

```<code># date -u
Tue Nov 30 15:35:12 UTC 2010
</code>```

Body:
Here is the script:

#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

so i want to convert $startTime into a UTC format

Body:
What format are you looking for? Simply executing date with -u Will give you a readable output format of UTC time, ie:

# date -u
Tue Nov 30 15:35:12 UTC 2010


问:
Get the first date and time from within a group
Many of the questions we get asked are related to how much time passes between two events (e.g. - patient was admitted, some assessment occurred). Some events take place multiple times. How can I find the first date and time that an event occurred per patient visit?

In the model is a table called Clinical Queries. In that table is a column called Activity Date Time. There is a calculated column called Date and another called Time that are based off of the Activity Date Time. These are related to a Date dimension table and a Time dimension table.

I've managed to build a query that gives me the earliest date, and it gives me the earliest time. However, it returns the earliest time regardless of the date. For example, if a patient has two assessments performed, one on 1/1/2017 at 23:59 and another on 1/2/2017 at 00:01, the query returns 1/1/2017 at 00:01.

```<code>WITH
MEMBER [Measures].[FirstInterventionDate] AS (
    NonEmpty(existing{[Date].[Fiscal].[Date].MEMBERS}, {[Measures].[Clinical Queries Interventions Performed]}).Item(0).Name
)

MEMBER [Measures].[FirstInterventionTime] AS (
    NonEmpty(existing{[Time].[Time].[Time].MEMBERS}, {[Measures].[Clinical Queries Interventions Performed]}).Item(0).Name
)

SELECT {[Measures].[Clinical Queries Interventions Performed], [Measures].[FirstInterventionDate], [Measures].[FirstInterventionTime]} on 0,
    NON EMPTY([Clinical Queries].[Account Number].Children) ON 1
FROM (
SELECT { [Clinical Queries].[InterventionID].&[3000195],
    [Clinical Queries].[InterventionID].&[3000186],
    [Clinical Queries].[InterventionID].&[3000184],
    [Clinical Queries].[InterventionID].&[3000182],
    [Clinical Queries].[InterventionID].&[3000184] } ON 0
FROM (
SELECT { [Clinical Queries].[Account Number].&[ACCT992],
    [Clinical Queries].[Account Number].&[ACCT064] } ON 0
FROM [Model]
))
</code>```

What do I need to change to make it return the earliest date and time for that earliest date. For the example above it would be 1/1/2017 at 23:59.

答:
Try the following code:

```<code>select
    {[Clinical Queries].[Account Number].&[ACCT992],
     [Clinical Queries].[Account Number].&[ACCT064]} *
    {[Measures].[Clinical Queries Interventions Performed]} on 0,
    Generate(
        {[Clinical Queries].[InterventionID].&[3000195],
         [Clinical Queries].[InterventionID].&[3000186],
         [Clinical Queries].[InterventionID].&[3000184],
         [Clinical Queries].[InterventionID].&[3000182],
         [Clinical Queries].[InterventionID].&[3000184]},
        Head(
            NonEmpty(
                [Clinical Queries].[InterventionID].CurrentMember *
                [Date].[Fiscal].[Date].Members *
                [Time].[Time].[Time].Members,
                [Measures].[Clinical Queries Interventions Performed]
            ),
            1
        )
    ) on 1
from [Model]
</code>```

You may be not very happy about performance, so I strongly recommend you to move the logic on DWH level: add a measure field like 201703301020 (3/30/2017 10:20) with Min aggregation, you may parse the value using MDX calculated measure combined with left() right() functions.

Body:
Many of the questions we get asked are related to how much time passes between two events (e.g. - patient was admitted, some assessment occurred). Some events take place multiple times. How can I find the first date and time that an event occurred per patient visit?

In the model is a table called Clinical Queries. In that table is a column called Activity Date Time. There is a calculated column called Date and another called Time that are based off of the Activity Date Time. These are related to a Date dimension table and a Time dimension table.

I've managed to build a query that gives me the earliest date, and it gives me the earliest time. However, it returns the earliest time regardless of the date. For example, if a patient has two assessments performed, one on 1/1/2017 at 23:59 and another on 1/2/2017 at 00:01, the query returns 1/1/2017 at 00:01.

WITH
MEMBER [Measures].[FirstInterventionDate] AS (
    NonEmpty(existing{[Date].[Fiscal].[Date].MEMBERS}, {[Measures].[Clinical Queries Interventions Performed]}).Item(0).Name
)

MEMBER [Measures].[FirstInterventionTime] AS (
    NonEmpty(existing{[Time].[Time].[Time].MEMBERS}, {[Measures].[Clinical Queries Interventions Performed]}).Item(0).Name
)

SELECT {[Measures].[Clinical Queries Interventions Performed], [Measures].[FirstInterventionDate], [Measures].[FirstInterventionTime]} on 0,
    NON EMPTY([Clinical Queries].[Account Number].Children) ON 1
FROM (
SELECT { [Clinical Queries].[InterventionID].&[3000195],
    [Clinical Queries].[InterventionID].&[3000186],
    [Clinical Queries].[InterventionID].&[3000184],
    [Clinical Queries].[InterventionID].&[3000182],
    [Clinical Queries].[InterventionID].&[3000184] } ON 0
FROM (
SELECT { [Clinical Queries].[Account Number].&[ACCT992],
    [Clinical Queries].[Account Number].&[ACCT064] } ON 0
FROM [Model]
))

What do I need to change to make it return the earliest date and time for that earliest date. For the example above it would be 1/1/2017 at 23:59.

Body:
Try the following code:

select
    {[Clinical Queries].[Account Number].&[ACCT992],
     [Clinical Queries].[Account Number].&[ACCT064]} *
    {[Measures].[Clinical Queries Interventions Performed]} on 0,
    Generate(
        {[Clinical Queries].[InterventionID].&[3000195],
         [Clinical Queries].[InterventionID].&[3000186],
         [Clinical Queries].[InterventionID].&[3000184],
         [Clinical Queries].[InterventionID].&[3000182],
         [Clinical Queries].[InterventionID].&[3000184]},
        Head(
            NonEmpty(
                [Clinical Queries].[InterventionID].CurrentMember *
                [Date].[Fiscal].[Date].Members *
                [Time].[Time].[Time].Members,
                [Measures].[Clinical Queries Interventions Performed]
            ),
            1
        )
    ) on 1
from [Model]

You may be not very happy about performance, so I strongly recommend you to move the logic on DWH level: add a measure field like 201703301020 (3/30/2017 10:20) with Min aggregation, you may parse the value using MDX calculated measure combined with left() right() functions.


问:
Asking multiple permissions one at a time
The code just shows dialog box for the first permission and not for the other two permissions.How can I handle multiple requests in a much easier way other than this , in which the app prompts for each permission one at a time .

The code for requesting permission is as follows :

```<code>package com.example.hp.requesting_permissions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)     {
             if  (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,  Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
             }

         } else {
             Toast.makeText(MainActivity.this, "Denied",   Toast.LENGTH_SHORT).show();
         }

         if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION) !=   PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new   String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",   Toast.LENGTH_SHORT).show();
        }

        if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,      Manifest.permission.INTERNET)) {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",  Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]     permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)     {
                        Toast.makeText(MainActivity.this, "Granted", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
            case 2: {
                 if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,      Manifest.permission.ACCESS_COARSE_LOCATION) ==      PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Granted",      Toast.LENGTH_SHORT).show();
                    }
                }
            }
             break;
            case 3: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }
}
</code>```

答:
Here it ask all permissions

```<code>public class RequestUserPermission {

private Activity activity;

// Storage Permissions
private static final int REQUEST_PERMISSION = 1;
private static String[] PERMISSIONS = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
};

public RequestUserPermission(Activity activity) {
    this.activity = activity;
}

public  boolean verifyStoragePermissions() {
    // Check if we have write permission
    int permissionWrite = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int permissionRead = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

    if ((permissionWrite != PackageManager.PERMISSION_GRANTED) ||
            (permissionRead != PackageManager.PERMISSION_GRANTED)) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS,
                REQUEST_PERMISSION
        );
        return false;
    }else{
        return true;
    }
}

public void providePermission(){
    verifyStoragePermissions();
}

public void forceFullOpenPermission(){
    if(!verifyStoragePermissions()){
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        activity.startActivityForResult(intent, REQUEST_PERMISSION);
    }
}
}
</code>```

Body:
The code just shows dialog box for the first permission and not for the other two permissions.How can I handle multiple requests in a much easier way other than this , in which the app prompts for each permission one at a time .

The code for requesting permission is as follows :

package com.example.hp.requesting_permissions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)     {
             if  (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,  Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
             }

         } else {
             Toast.makeText(MainActivity.this, "Denied",   Toast.LENGTH_SHORT).show();
         }

         if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION) !=   PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new   String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",   Toast.LENGTH_SHORT).show();
        }

        if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,      Manifest.permission.INTERNET)) {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",  Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]     permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)     {
                        Toast.makeText(MainActivity.this, "Granted", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
            case 2: {
                 if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,      Manifest.permission.ACCESS_COARSE_LOCATION) ==      PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Granted",      Toast.LENGTH_SHORT).show();
                    }
                }
            }
             break;
            case 3: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }
}

Body:
Here it ask all permissions

public class RequestUserPermission {

private Activity activity;

// Storage Permissions
private static final int REQUEST_PERMISSION = 1;
private static String[] PERMISSIONS = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
};

public RequestUserPermission(Activity activity) {
    this.activity = activity;
}

public  boolean verifyStoragePermissions() {
    // Check if we have write permission
    int permissionWrite = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int permissionRead = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

    if ((permissionWrite != PackageManager.PERMISSION_GRANTED) ||
            (permissionRead != PackageManager.PERMISSION_GRANTED)) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS,
                REQUEST_PERMISSION
        );
        return false;
    }else{
        return true;
    }
}

public void providePermission(){
    verifyStoragePermissions();
}

public void forceFullOpenPermission(){
    if(!verifyStoragePermissions()){
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        activity.startActivityForResult(intent, REQUEST_PERMISSION);
    }
}
}


问:
add comma after thousand amount in javascript
I am using slide input with following javascript,

```<code><script type="text/javascript">
    jQuery(document).ready(function(e){
        var val1 = 0;
        var val2 = 0;
        $("#ex1").slider();
        $("#ex1").on("slide", function(slideEvt1) {
            //$("#ex1SliderVal").text((Number(slideEvt1.value) * 2.90) + (Number(val2) * 0.30));
            val1 = Number(slideEvt1.value);

            $("#ex1SliderVal").text((Number(val1) * 0.0290) + (Number(val2) * 0.30));

            $("#ex2SliderVal").text((Number(val1) * 0.0199) + (Number(val2) * 0.15));

            $("#ex3SliderVal").text((Number(val1) * 0.0225) + (Number(val2) * 0.10));

            $("#showex1").text(Number(val1));
            //console.log(val1)
        });
});
</script>

<div class="col-xs-12">
                <input id="ex1" type="text" data-slider-min="0000" data-slider-max="8000" data-slider-step="1" data-slider-value="0"/>
                <span><span style="margin-left: 30px; font-size:14px;"id="showex1">0</span></span>
            </div>
</code>```

This is working properly. Only thing I want to add a comma after thousands.
like 2,000 80,000 170,000

Please help me add this.
Thank you+

答:
in this way you can use @RokoC.Buljan usefull link for your code:

```<code><script type="text/javascript">
jQuery(document).ready(function(e){
    var val1 = 0;
    var val2 = 0;
    $("#ex1").slider();
    $("#ex1").on("slide", function(slideEvt1) {
        //$("#ex1SliderVal").text((Number(slideEvt1.value) * 2.90) + (Number(val2) * 0.30));
        val1 = Number(slideEvt1.value);

        $("#ex1SliderVal").text(((Number(val1) * 0.0290) + (Number(val2) * 0.30)).toLocaleString(););

        $("#ex2SliderVal").text(((Number(val1) * 0.0199) + (Number(val2) * 0.15)).toLocaleString(););

        $("#ex3SliderVal").text(((Number(val1) * 0.0225) + (Number(val2) * 0.10)).toLocaleString(););

        $("#showex1").text((Number(val1)).toLocaleString(););
        //console.log(val1)
    });
});
</script>
</code>```

here i used .toLocaleString(); function that has been mentioned in that link.

Body:
I am using slide input with following javascript,

                <input id="ex1" type="text" data-slider-min="0000" data-slider-max="8000" data-slider-step="1" data-slider-value="0"/>
                0

This is working properly. Only thing I want to add a comma after thousands.
like 2,000 80,000 170,000

Please help me add this.
Thank you+

Body:
in this way you can use @RokoC.Buljan usefull link for your code:

<script type="text/javascript">
jQuery(document).ready(function(e){
    var val1 = 0;
    var val2 = 0;
    $("#ex1").slider();
    $("#ex1").on("slide", function(slideEvt1) {
        //$("#ex1SliderVal").text((Number(slideEvt1.value) * 2.90) + (Number(val2) * 0.30));
        val1 = Number(slideEvt1.value);

        $("#ex1SliderVal").text(((Number(val1) * 0.0290) + (Number(val2) * 0.30)).toLocaleString(););

        $("#ex2SliderVal").text(((Number(val1) * 0.0199) + (Number(val2) * 0.15)).toLocaleString(););

        $("#ex3SliderVal").text(((Number(val1) * 0.0225) + (Number(val2) * 0.10)).toLocaleString(););

        $("#showex1").text((Number(val1)).toLocaleString(););
        //console.log(val1)
    });
});
</script>

here i used .toLocaleString(); function that has been mentioned in that link.


问:
Changing statement separator in Intellij Idea or Datagrip like in Squirrel
is it possible to change statement separator in Intellij Idea database tool?

To be exact, in squirrel, you can change statement separator, so you don't need to use symbol ; but you can change it to different symbols like @!? etc.

Example

```<code>select * from users;
</code>```

I would need

```<code>select * from users@
</code>```

Thanks

答: It is currently not possible, please follow/vote for this request DBE-2968</p>

Body:
is it possible to change statement separator in Intellij Idea database tool?

To be exact, in squirrel, you can change statement separator, so you don't need to use symbol ; but you can change it to different symbols like @!? etc.

Example

select * from users;

I would need

select * from users@

Thanks


问:
SQL Server: Select Max for each sub group in result set
I am new to SQL Server. I have a table that contains user names, addresses and the update dates.

The following query gives me all required details from that table but my problem is that the table can contain multiple records for the same user / ID in case they changed their address more than once.

How can I only get the address from the latest update for each user / ID?  I tried with DISTINCT, TOP1 etc. but couldn't figure out a way to make this work.

My query:

```<code>SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC
</code>```

答:
rextester demo</p>

```<code>select * from (
select rn = row_number() over (partition by id order by updateDate desc), *
from Users
) x
where rn = 1
</code>```

Body:
rextester demo

select * from (
select rn = row_number() over (partition by id order by updateDate desc), *
from Users
) x
where rn = 1