问:
Arrow key and mouse navigation for AJAX Live search
I am using the below code for autocomplete feature in webpage. The problem is that I am not able to navigate through the suggestion using mouse pointer. But if up/down key is pressed once after the list item refreshed mouse pointer navigation is working fine.

Could you please suggest the code change to make the mouse pointer and keyboard navigation work like the navigation in html select option?

How can I improve the scrolling of suggestion list using up/down key?

HTML:

```<code><div class="field-wrap">

<input type="text" id="college"  placeholder="College Name" required autocomplete="off"/>
<ul id="college_list"></ul>

</div>
</code>```

CSS:

```<code>.field-wrap ul {
    width: 93%;
    margin-top: 1px;
    border: 1px solid #3498DB;
    position: absolute;
    z-index: 9;
    background: #0F0F0F;
    list-style: none;
    max-height: 100px;
    overflow-y:auto;
}

.field-wrap ul li {
    padding: 2px;
    border: solid grey;
    border-width: 0 0 2px 0;
}

#college_list {
    display: none;
}

.selected {
    background: #2980B9;
}
</code>```

Javascript:

```<code>// livesearch : this function will be executed every time we change the text
function livesearch() {
    var min_length = 1; // min caracters to display the autocomplete
    var keyword = $.trim($('#college').val());
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'livesearch.php',
            type: 'POST',
            data: {keyword:keyword},
            success:function(data){
                $('#college_list').show();
                $('#college_list').html(data);
            }
        });

    } else {
        $('#college_list').hide();
    }
}

// set_item : this function will be executed when we select an item
function set_item(item) {

    // change input value
    $('#college').val(item);

    // after selecting an item, update list item and hide proposition list
    var min_length = 1; // min caracters to display the autocomplete
    var keyword = $('#college').val();
        if (keyword.length >= min_length) {
            $.ajax({
                url: 'livesearch.php',
                type: 'POST',
                data: {keyword:keyword},
                success:function(data){
                    $('#college_list').hide();
                    $('#college_list').html(data);
                }
            });
        }

}

// Display or hide list based on focus in search box

$('#college').focus(function() {

    livesearch();

    $(document).bind('focusin.college click.college',function(e) {
        if ($(e.target).closest('#college, #college').length) return;
        $(document).unbind('#college');
        $('#college_list').fadeOut('medium');
    });

});

// Disable default behaviour of form submit when enter is pressed for livesearch text box

$('#college').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13 ) { e.preventDefault(); }
});

// Livesearch list or navigate and select a list item based on keyup events

$('#college').keyup(function(e)
{

    var $listItems = $('.field-wrap li');
    var key = e.keyCode,
        $selected = $listItems.filter('.selected'),
        $current;

// Search text pattern in database if key pressed is not up/down/enter

    if ( key != 40 && key != 38 && key != 13 ) livesearch();

    $listItems.removeClass('selected');

// navigate or select list item based on up/down/enter key pressed if list is visible

    if($('#college_list').is(':visible')) {

        var menu = $('#college_list');
        var height = $selected.outerHeight(); //Height of <li>
        var top = menu.scrollTop(); //Current top of scroll window
        var menuHeight = menu[0].scrollHeight; //Full height of <ul>

        if ( key == 40 ) // Down key
        {
            if ( ! $selected.length || $selected.is(':last-child') ) {
                $current = $listItems.eq(0);
                menu.scrollTop(0);
            }
            else {
                $current = $selected.next();
                menu.scrollTop(top + height);
            }

            $current.addClass('selected');
        }

        if ( key == 38 ) // Up key
        {
            if ( ! $selected.length || $selected.is(':first-child') ) {
                $current = $listItems.last();
                menu.scrollTop(menuHeight + height);
            }
            else {
                $current = $selected.prev();
                menu.scrollTop(top - height);
            }
            $current.addClass('selected');
        }

        if ( key == 13 ) // Enter key
        {
        $current = $selected;

        // If selected text in list is not blank change the text in search box else hide list and retain entered text in search box

            if($current.addClass('selected').text()!='') {
                set_item( $current.addClass('selected').text() );
            }
            else {
                $('#college_list').fadeOut('medium');
            }
        }

    }

        $('#college_list li').mousemove(function() {
            $('.field-wrap li').removeClass('selected');
            $(this).addClass('selected');
        });
});
</code>```

Livesearch.php:

```<code><?php
// PDO connect *********
function connect() {
    return new PDO('mysql:host=localhost;dbname=expertreaders', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}

$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM colleges WHERE college_name LIKE (:keyword) ORDER BY college_name ASC";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
    // put in bold the written text
    $college_name = preg_replace('/' . preg_quote($_POST['keyword'], "/") . '/i', "<b><font color=green>\$0</font></b>", $rs['college_name']);
    // add new option
    echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['college_name']).'\')">'.$college_name.'</li>';
}

?>
</code>```

Thanks in advance.

答:
The mouse navigation working after the key press because you defined the mousemove event handler inside the keyup event. And for dynamically created html contents like this use always $(document).bind or $(document).on like functions as event handler.
There are duplicate event handlers in your code. Is it necessory?
Eg:

```<code>$('#college').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13 ) { e.preventDefault(); }
});

// Livesearch list or navigate and select a list item based on keyup events

$('#college').keyup(function(e)
{

    var $listItems = $('.field-wrap li');
    var key = e.keyCode,
        $selected = $listItems.filter('.selected'),
        $current;
</code>```

Use a single handler and apply conditions.
like

```<code>if(e.keyCode == 13 ) { //do some stuff
}
else {
//Do something else
}
</code>```

Try my answer. Pardon me if you get anything wrong

Body:
I am using the below code for autocomplete feature in webpage. The problem is that I am not able to navigate through the suggestion using mouse pointer. But if up/down key is pressed once after the list item refreshed mouse pointer navigation is working fine.

Could you please suggest the code change to make the mouse pointer and keyboard navigation work like the navigation in html select option?

How can I improve the scrolling of suggestion list using up/down key?

HTML:

<input type="text" id="college"  placeholder="College Name" required autocomplete="off"/>

CSS:

.field-wrap ul {
    width: 93%;
    margin-top: 1px;
    border: 1px solid #3498DB;
    position: absolute;
    z-index: 9;
    background: #0F0F0F;
    list-style: none;
    max-height: 100px;
    overflow-y:auto;
}

.field-wrap ul li {
    padding: 2px;
    border: solid grey;
    border-width: 0 0 2px 0;
}

#college_list {
    display: none;
}

.selected {
    background: #2980B9;
}

Javascript:

// livesearch : this function will be executed every time we change the text
function livesearch() {
    var min_length = 1; // min caracters to display the autocomplete
    var keyword = $.trim($('#college').val());
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'livesearch.php',
            type: 'POST',
            data: {keyword:keyword},
            success:function(data){
                $('#college_list').show();
                $('#college_list').html(data);
            }
        });

    } else {
        $('#college_list').hide();
    }
}

// set_item : this function will be executed when we select an item
function set_item(item) {

    // change input value
    $('#college').val(item);

    // after selecting an item, update list item and hide proposition list
    var min_length = 1; // min caracters to display the autocomplete
    var keyword = $('#college').val();
        if (keyword.length >= min_length) {
            $.ajax({
                url: 'livesearch.php',
                type: 'POST',
                data: {keyword:keyword},
                success:function(data){
                    $('#college_list').hide();
                    $('#college_list').html(data);
                }
            });
        }

}

// Display or hide list based on focus in search box

$('#college').focus(function() {

    livesearch();

    $(document).bind('focusin.college click.college',function(e) {
        if ($(e.target).closest('#college, #college').length) return;
        $(document).unbind('#college');
        $('#college_list').fadeOut('medium');
    });

});

// Disable default behaviour of form submit when enter is pressed for livesearch text box

$('#college').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13 ) { e.preventDefault(); }
});

// Livesearch list or navigate and select a list item based on keyup events

$('#college').keyup(function(e)
{

    var $listItems = $('.field-wrap li');
    var key = e.keyCode,
        $selected = $listItems.filter('.selected'),
        $current;

// Search text pattern in database if key pressed is not up/down/enter

    if ( key != 40 && key != 38 && key != 13 ) livesearch();

    $listItems.removeClass('selected');

// navigate or select list item based on up/down/enter key pressed if list is visible

    if($('#college_list').is(':visible')) {

        var menu = $('#college_list');
        var height = $selected.outerHeight(); //Height of

        var top = menu.scrollTop(); //Current top of scroll window
        var menuHeight = menu[0].scrollHeight; //Full height of

        if ( key == 40 ) // Down key
        {
            if ( ! $selected.length || $selected.is(':last-child') ) {
                $current = $listItems.eq(0);
                menu.scrollTop(0);
            }
            else {
                $current = $selected.next();
                menu.scrollTop(top + height);
            }

            $current.addClass('selected');
        }

        if ( key == 38 ) // Up key
        {
            if ( ! $selected.length || $selected.is(':first-child') ) {
                $current = $listItems.last();
                menu.scrollTop(menuHeight + height);
            }
            else {
                $current = $selected.prev();
                menu.scrollTop(top - height);
            }
            $current.addClass('selected');
        }

        if ( key == 13 ) // Enter key
        {
        $current = $selected;

        // If selected text in list is not blank change the text in search box else hide list and retain entered text in search box

            if($current.addClass('selected').text()!='') {
                set_item( $current.addClass('selected').text() );
            }
            else {
                $('#college_list').fadeOut('medium');
            }
        }

    }

        $('#college_list li').mousemove(function() {
            $('.field-wrap li').removeClass('selected');
            $(this).addClass('selected');
        });
});

Livesearch.php:

<?php
// PDO connect *********
function connect() {
    return new PDO('mysql:host=localhost;dbname=expertreaders', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}

$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM colleges WHERE college_name LIKE (:keyword) ORDER BY college_name ASC";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
    // put in bold the written text
    $college_name = preg_replace('/' . preg_quote($_POST['keyword'], "/") . '/i', "\$0", $rs['college_name']);
    // add new option
    echo '
'.$college_name.'
';
}

?>

Thanks in advance.

Body:
The mouse navigation working after the key press because you defined the mousemove event handler inside the keyup event. And for dynamically created html contents like this use always $(document).bind or $(document).on like functions as event handler.
There are duplicate event handlers in your code. Is it necessory?
Eg:

$('#college').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13 ) { e.preventDefault(); }
});

// Livesearch list or navigate and select a list item based on keyup events

$('#college').keyup(function(e)
{

    var $listItems = $('.field-wrap li');
    var key = e.keyCode,
        $selected = $listItems.filter('.selected'),
        $current;

Use a single handler and apply conditions.
like

if(e.keyCode == 13 ) { //do some stuff
}
else {
//Do something else
}

Try my answer. Pardon me if you get anything wrong


来源: stackexchange

问:
org.apache.hadoop.hbase.snapshot.CorruptedSnapshotException: Couldn't read snapshot info from:file:/tmp/hbase-cloudera/hbase
Hi I am trying to Export Hbase table snapshot to my local hdfs so that i can run mapreduce on that .

I have taken the snapshot of the Hbase table using below command

```<code>snapshot 'FundamentalAnalytic','FundamentalAnalyticSnapshot'
</code>```

Also when i ran list_snapshots command i can see my snapshot also .

I have exported my Hbase table snapshot to my local HDFS directory using below command and copied successfully .

```<code>hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot FundamentalAnalyticSnapshot -copy-to /tmp -mappers 16
</code>```

Finally i have to run map reduce on the snapshot so below is my driver code to configure that job .

```<code>TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // input table
                scan, // Scan instance to control CF and attribute selection
                DefaultMapper.class, // mapper class
                NullWritable.class, // mapper output key
                Text.class, // mapper output value
                job,
                true,
                new Path("/home/cloudera/archive/data/default/FundamentalAnalytic/bc95715f67e52547e86b5b096a1f1cb5/cf/d29205a44623434eba2d100a94d8ebfb_SeqId_4_"));
</code>```

This is where i get error .
I dont know which path i have to give as last arg in initTableSnapshotMapperJob method.

When i run this code i get below error .

```<code>org.apache.hadoop.hbase.snapshot.CorruptedSnapshotException: Couldn't read snapshot info from:file:/tmp/hbase-cloudera/hbase/.hbase-snapshot/FundamentalAnalyticSnapshot/.snapshotinfo
    at org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils.readSnapshotInfo(SnapshotDescriptionUtils.java:294)
    at org.apache.hadoop.hbase.snapshot.RestoreSnapshotHelper.copySnapshotForScanner(RestoreSnapshotHelper.java:818)
    at org.apache.hadoop.hbase.mapreduce.TableSnapshotInputFormatImpl.setInput(TableSnapshotInputFormatImpl.java:355)
    at org.apache.hadoop.hbase.mapreduce.TableSnapshotInputFormat.setInput(TableSnapshotInputFormat.java:204)
    at org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil.initTableSnapshotMapperJob(TableMapReduceUtil.java:335)
    at com.thomsonretuers.hbase.HBaseToFileDriver.run(HBaseToFileDriver.java:128)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at com.thomsonretuers.hbase.HBaseToFileDriver.main(HBaseToFileDriver.java:75)
Caused by: java.io.FileNotFoundException: File file:/tmp/hbase-cloudera/hbase/.hbase-snapshot/FundamentalAnalyticSnapshot/.snapshotinfo does not exist
</code>```

One quick Question about Snapshot.

I want to take snapshot and run full table scan ,in that case scan
on snapshot will impact the region server performance?

答:
I solved it after using correct path

Create snapshot

```<code>snapshot 'FundamentalAnalytic','FundamentalAnalyticSnapshot'
</code>```

Export Snapshot to local hdfs

```<code>hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot FundamentalAnalyticSnapshot -copy-to /tmp -mappers 16
</code>```

Driver Job Configuration to rum mapreduce on Hbase snapshot

```<code>    String snapshotName="FundamentalAnalyticSnapshot";
    Path restoreDir = new Path("hdfs://quickstart.cloudera:8020/tmp");
    String  hbaseRootDir =  "hdfs://quickstart.cloudera:8020/hbase";

TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // Snapshot name
                    scan, // Scan instance to control CF and attribute selection
                    DefaultMapper.class, // mapper class
                    NullWritable.class, // mapper output key
                    Text.class, // mapper output value
                    job,
                    true,
                    restoreDir);
</code>```

Also running mapreduce on Hbase snapshot will skip scan on Hbase table and also there will be no impact on region server.

ContentLicense: CC BY-SA 3.0

Body:
Hi I am trying to Export Hbase table snapshot to my local hdfs so that i can run mapreduce on that .

I have taken the snapshot of the Hbase table using below command

snapshot 'FundamentalAnalytic','FundamentalAnalyticSnapshot'

Also when i ran list_snapshots command i can see my snapshot also .

I have exported my Hbase table snapshot to my local HDFS directory using below command and copied successfully .

hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot FundamentalAnalyticSnapshot -copy-to /tmp -mappers 16

Finally i have to run map reduce on the snapshot so below is my driver code to configure that job .

TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // input table
                scan, // Scan instance to control CF and attribute selection
                DefaultMapper.class, // mapper class
                NullWritable.class, // mapper output key
                Text.class, // mapper output value
                job,
                true,
                new Path("/home/cloudera/archive/data/default/FundamentalAnalytic/bc95715f67e52547e86b5b096a1f1cb5/cf/d29205a44623434eba2d100a94d8ebfb_SeqId_4_"));

This is where i get error .
I dont know which path i have to give as last arg in initTableSnapshotMapperJob method.

When i run this code i get below error .

org.apache.hadoop.hbase.snapshot.CorruptedSnapshotException: Couldn't read snapshot info from:file:/tmp/hbase-cloudera/hbase/.hbase-snapshot/FundamentalAnalyticSnapshot/.snapshotinfo
    at org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils.readSnapshotInfo(SnapshotDescriptionUtils.java:294)
    at org.apache.hadoop.hbase.snapshot.RestoreSnapshotHelper.copySnapshotForScanner(RestoreSnapshotHelper.java:818)
    at org.apache.hadoop.hbase.mapreduce.TableSnapshotInputFormatImpl.setInput(TableSnapshotInputFormatImpl.java:355)
    at org.apache.hadoop.hbase.mapreduce.TableSnapshotInputFormat.setInput(TableSnapshotInputFormat.java:204)
    at org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil.initTableSnapshotMapperJob(TableMapReduceUtil.java:335)
    at com.thomsonretuers.hbase.HBaseToFileDriver.run(HBaseToFileDriver.java:128)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at com.thomsonretuers.hbase.HBaseToFileDriver.main(HBaseToFileDriver.java:75)
Caused by: java.io.FileNotFoundException: File file:/tmp/hbase-cloudera/hbase/.hbase-snapshot/FundamentalAnalyticSnapshot/.snapshotinfo does not exist

One quick Question about Snapshot.

I want to take snapshot and run full table scan ,in that case scan
on snapshot will impact the region server performance?

Body:
I solved it after using correct path

Create snapshot

snapshot 'FundamentalAnalytic','FundamentalAnalyticSnapshot'

Export Snapshot to local hdfs

hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot FundamentalAnalyticSnapshot -copy-to /tmp -mappers 16

Driver Job Configuration to rum mapreduce on Hbase snapshot

    String snapshotName="FundamentalAnalyticSnapshot";
    Path restoreDir = new Path("hdfs://quickstart.cloudera:8020/tmp");
    String  hbaseRootDir =  "hdfs://quickstart.cloudera:8020/hbase";

TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // Snapshot name
                    scan, // Scan instance to control CF and attribute selection
                    DefaultMapper.class, // mapper class
                    NullWritable.class, // mapper output key
                    Text.class, // mapper output value
                    job,
                    true,
                    restoreDir);

Also running mapreduce on Hbase snapshot will skip scan on Hbase table and also there will be no impact on region server.


问:
Socket.io with NGINX and https2
I have node.js app which is served by NGINX. I can't connect socket.io and keep getting 404 for POST requests to establishing a connection.

It's working locally, so it must be an NGINX problem.

```<code>  # HTTP - redirect all requests to HTTPS:
  server {
     listen 80;
     listen [::]:80;
     return 301 https://$host$request_uri;
  }
  # HTTPS - proxy requests on to local Node.js app:
  server {
     listen 443 ssl http2;
     server_name example.com;
     ssl on;
     ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
     ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
     ssl_session_timeout 5m;
     ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
     ssl_prefer_server_ciphers on;
     ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
     location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-Proto https;
        proxy_pass http://127.0.0.1:8080;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
     }
}
</code>```

Thanks for any help.

答:
Since Websockets are using the Upgrade header introduced in HTTP 1.1, you'll need to specifically use this protocol in your route and set the Connection header to upgrade.

You'll also need to specify a proxy_pass directive with a unique name.

Your config would be something like that:

```<code>upstream sockets {
  server localhost:8080;
}

# HTTP - redirect all requests to HTTPS:
server {
  listen 80;
  listen [::]:80;
  return 301 https://$host$request_uri;
}

# HTTPS - proxy requests on to local Node.js app:
server {
     listen 443 ssl http2;
     server_name example.com;
     ssl on;
     ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
     ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
     ssl_session_timeout 5m;
     ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
     ssl_prefer_server_ciphers on;
     ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

     location / {

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header Host $host;

        proxy_pass http://sockets;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;

        proxy_http_version 1.1;
        proxy_ssl_session_reuse off;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
     }

}
</code>```

Title: Socket.io with NGINX and https2

Body:
I have node.js app which is served by NGINX. I can't connect socket.io and keep getting 404 for POST requests to establishing a connection.

It's working locally, so it must be an NGINX problem.

  # HTTP - redirect all requests to HTTPS:
  server {
     listen 80;
     listen [::]:80;
     return 301 https://$host$request_uri;
  }
  # HTTPS - proxy requests on to local Node.js app:
  server {
     listen 443 ssl http2;
     server_name example.com;
     ssl on;
     ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
     ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
     ssl_session_timeout 5m;
     ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
     ssl_prefer_server_ciphers on;
     ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
     location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-Proto https;
        proxy_pass http://127.0.0.1:8080;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
     }
}

Thanks for any help.

Body:
Since Websockets are using the Upgrade header introduced in HTTP 1.1, you'll need to specifically use this protocol in your route and set the Connection header to upgrade.

You'll also need to specify a proxy_pass directive with a unique name.

Your config would be something like that:

upstream sockets {
  server localhost:8080;
}

# HTTP - redirect all requests to HTTPS:
server {
  listen 80;
  listen [::]:80;
  return 301 https://$host$request_uri;
}

# HTTPS - proxy requests on to local Node.js app:
server {
     listen 443 ssl http2;
     server_name example.com;
     ssl on;
     ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
     ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
     ssl_session_timeout 5m;
     ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
     ssl_prefer_server_ciphers on;
     ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

     location / {

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header Host $host;

        proxy_pass http://sockets;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;

        proxy_http_version 1.1;
        proxy_ssl_session_reuse off;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
     }

}


问:
C - How to make sure that an array contains 8 integers with the value 0 or 1?
That's my code so far:

```<code>int main(void) {
    int byte[8], position = 0, match8 = 0;
    printf("Please enter 1 byte as a binary sequence: ");
    match8 = scanf("%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
    return 0;
}
</code>```

Now I want to make sure that the user made a correct input and if not the program should say "Error! Please enter 1 byte as a binary sequence: " and check the input again.

I tried:

```<code>while(getchar() != '\n' || match8 != 8) {
    ...do something
}
</code>```

But I can't figure out how to check if the array contains only 0 and 1.

I hope you can help me with my problem :)

答:
try this...</p>

```<code>int main(void) {

int byte[8]={0};

    printf("Please enter 1 byte as a binary sequence: ");
    for(int i=0; i<8; i++)
{
byte[i]=getchar()-'0';
if(byte[i]!=0&&byte[i]!=1) /*error*/;
}
return 0;
}
</code>```

Body:
That's my code so far:

int main(void) {
    int byte[8], position = 0, match8 = 0;
    printf("Please enter 1 byte as a binary sequence: ");
    match8 = scanf("%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
    return 0;
}

Now I want to make sure that the user made a correct input and if not the program should say "Error! Please enter 1 byte as a binary sequence: " and check the input again.

I tried:

while(getchar() != '\n' || match8 != 8) {
    ...do something
}

But I can't figure out how to check if the array contains only 0 and 1.

I hope you can help me with my problem :)

Body:
try this...

int main(void) {

int byte[8]={0};

    printf("Please enter 1 byte as a binary sequence: ");
    for(int i=0; i<8; i++)
{
byte[i]=getchar()-'0';
if(byte[i]!=0&&byte[i]!=1) /*error*/;
}
return 0;
}


问:
Automating new cell entries based on condition
First-time caller, long-time listener. I'm sorry if the title is a bit off, not really sure how to vocalize this issue. I have built a system at work for our work-study students to clock-in on. Unfortunately, the rest of our University is on a paper system and I cannot accept that. The system is made from two parts. The first part is a Google form where clock-in information is reported, it also includes a filter that separates that information based on pay period. The second is another sheet that imports that data and formats it into a printable timecard.

Here is the problem in a nutshell. We have students that work past midnight, potentially to 2:00 am. I need this system (or some system) to clock them out at midnight and clock them back in on the following day at 12:00 am.

Not even sure where to start with this one. I guess I need a script? A solution, advice or just a point in the right direction would be greatly appreciated. Thanks for your time all!

Form & Filter:
https://docs.google.com/spreadsheets/d/19LfKUQY6etiRY2wuyFYM8Jzay7IGXrwn0rHKgDwnmE4/edit?usp=sharing

Pay info and Timecard format:
https://docs.google.com/spreadsheets/d/1-2-7D7AHi6J-4cURlOsQOC1KznCR6zsejkTbyBFamjA/edit?usp=sharing

答:
This might point you in the right direction. I check for a PM followed by AM. If it finds this condition, it splits it into two calculations. One up to midnight and the other on for after midnight. The next day looks back and if after midnight time occurs it picks it up. If no after midnight time occurs, it does what you do now. I think you can make this work (you will need to add a couple of columns which you can hide). I don't know what you would do on the last day of your time card. Below is an example you can copy:

https://docs.google.com/spreadsheets/d/1cO1ggY05kz70lfPE0YZCXaaa0AiaGKDM1s9FQPnw6Zs/edit?usp=sharing


问:
Webkit Color Transition Loop on text doesn't work in firefox
I want my H3 tags to change color in an infinite loop. My code works fine in Safari but Firefox isn't making the tag change color?

Here is my code:

```<code>    h3 {color: #333 !important;}
@-webkit-keyframes colours {
      0% {color: #333;}
     15% {color: #8bc5d1;}
     30% {color: #f8cb4a;}
     45% {color: #95b850;}
     60% {color: #944893;}
     75% {color: #c71f00;}
     90% {color: #bdb280;}
    100% {color: #333;}
}
h3 {
    -webkit-animation-direction: normal;
    -webkit-animation-duration: 60s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-name: colours;
    -webkit-animation-timing-function: ease;
}
</code>```

答:
You're using the -webkit prefix, which will only work in webkit enabled browsers. You can add the non-prefixed versions to support modern browsers that support the syntax, and you can also add the prefixed versions for all browsers.

h3 {
  color: #333;
}

@-webkit-keyframes colours {
  0% {
    color: #333;
  }
  15% {
    color: #8bc5d1;
  }
  30% {
    color: #f8cb4a;
  }
  45% {
    color: #95b850;
  }
  60% {
    color: #944893;
  }
  75% {
    color: #c71f00;
  }
  90% {
    color: #bdb280;
  }
  100% {
    color: #333;
  }
}

@keyframes colours {
  0% {
    color: #333;
  }
  15% {
    color: #8bc5d1;
  }
  30% {
    color: #f8cb4a;
  }
  45% {
    color: #95b850;
  }
  60% {
    color: #944893;
  }
  75% {
    color: #c71f00;
  }
  90% {
    color: #bdb280;
  }
  100% {
    color: #333;
  }
}

h3 {
  -webkit-animation-direction: normal;
          animation-direction: normal;
  -webkit-animation-duration: 60s;
          animation-duration: 60s;
  -webkit-animation-iteration-count: infinite;
          animation-iteration-count: infinite;
  -webkit-animation-name: colours;
          animation-name: colours;
  -webkit-animation-timing-function: ease;
          animation-timing-function: ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>foo</h3></code>```

Body:
I want my H3 tags to change color in an infinite loop. My code works fine in Safari but Firefox isn't making the tag change color?

Here is my code:

    h3 {color: #333 !important;}
@-webkit-keyframes colours {
      0% {color: #333;}
     15% {color: #8bc5d1;}
     30% {color: #f8cb4a;}
     45% {color: #95b850;}
     60% {color: #944893;}
     75% {color: #c71f00;}
     90% {color: #bdb280;}
    100% {color: #333;}
}
h3 {
    -webkit-animation-direction: normal;
    -webkit-animation-duration: 60s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-name: colours;
    -webkit-animation-timing-function: ease;
}

Body:
You're using the -webkit prefix, which will only work in webkit enabled browsers. You can add the non-prefixed versions to support modern browsers that support the syntax, and you can also add the prefixed versions for all browsers.

h3 {
  color: #333;
}

@-webkit-keyframes colours {
  0% {
    color: #333;
  }
  15% {
    color: #8bc5d1;
  }
  30% {
    color: #f8cb4a;
  }
  45% {
    color: #95b850;
  }
  60% {
    color: #944893;
  }
  75% {
    color: #c71f00;
  }
  90% {
    color: #bdb280;
  }
  100% {
    color: #333;
  }
}

@keyframes colours {
  0% {
    color: #333;
  }
  15% {
    color: #8bc5d1;
  }
  30% {
    color: #f8cb4a;
  }
  45% {
    color: #95b850;
  }
  60% {
    color: #944893;
  }
  75% {
    color: #c71f00;
  }
  90% {
    color: #bdb280;
  }
  100% {
    color: #333;
  }
}

h3 {
  -webkit-animation-direction: normal;
          animation-direction: normal;
  -webkit-animation-duration: 60s;
          animation-duration: 60s;
  -webkit-animation-iteration-count: infinite;
          animation-iteration-count: infinite;
  -webkit-animation-name: colours;
          animation-name: colours;
  -webkit-animation-timing-function: ease;
          animation-timing-function: ease;
}

<h3>foo</h3>


问:
Using SDL2 with CMake
I'm trying to use CLion to create a SDL2 project.
The problem is that the SDL headers can't be found when using #include's.

My CMakeLists.txt file:

```<code>cmake_minimum_required(VERSION 2.8.4)
project(ChickenShooter)

set(SDL2_INCLUDE_DIR C:/SDL/SDL2-2.0.3/include)
set(SDL2_LIBRARY C:/SDL/SDL2-2.0.3/lib/x64)

include_directories(${SDL2_INCLUDE_DIR})
set(SOURCE_FILES main.cpp)

add_executable(ChickenShooter ${SOURCE_FILES})
target_link_libraries(ChickenShooter ${SDL2_LIBRARY})
</code>```

My test main.cpp:

```<code>#include <iostream>
#include "SDL.h" /* This one can't be found */

int main(){
    if (SDL_Init(SDL_INIT_VIDEO) != 0){
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }
    SDL_Quit();
    return 0;
}
</code>```

Thank you for any help you could give me.

Edit:
I'm using Windows and CLion is configured to use cygwin64.

答:
This blog post shows how you can do it: Using SDL2 with CMake

On Linux you can use a recent CMake (e.g. version 3.7) and using SDL2 works out of the box.

```<code>cmake_minimum_required(VERSION 3.7)
project(SDL2Test)

find_package(SDL2 REQUIRED)
include_directories(SDL2Test ${SDL2_INCLUDE_DIRS})

add_executable(SDL2Test Main.cpp)
target_link_libraries(SDL2Test ${SDL2_LIBRARIES})
</code>```

Under Windows you can download the SDL2 development package, extract it somewhere and then create a sdl-config.cmake file in the extracted location with the following content:

```<code>set(SDL2_INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}/include")

# Support both 32 and 64 bit builds
if (${CMAKE_SIZEOF_VOID_P} MATCHES 8)
  set(SDL2_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/lib/x64/SDL2.lib;${CMAKE_CURRENT_LIST_DIR}/lib/x64/SDL2main.lib")
else ()
  set(SDL2_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/lib/x86/SDL2.lib;${CMAKE_CURRENT_LIST_DIR}/lib/x86/SDL2main.lib")
endif ()

string(STRIP "${SDL2_LIBRARIES}" SDL2_LIBRARIES)
</code>```

When you now configure inside the CMake-GUI application there will be a SDL2_DIR variable. You have to point it to the SDL2 directory where you extracted the dev package and reconfigure then everything should work.

You can then include SDL2 headers by just writing #include "SDL.h".

Title: Using SDL2 with CMake

Body:
I'm trying to use CLion to create a SDL2 project.
The problem is that the SDL headers can't be found when using #include's.

My CMakeLists.txt file:

cmake_minimum_required(VERSION 2.8.4)
project(ChickenShooter)

set(SDL2_INCLUDE_DIR C:/SDL/SDL2-2.0.3/include)
set(SDL2_LIBRARY C:/SDL/SDL2-2.0.3/lib/x64)

include_directories(${SDL2_INCLUDE_DIR})
set(SOURCE_FILES main.cpp)

add_executable(ChickenShooter ${SOURCE_FILES})
target_link_libraries(ChickenShooter ${SDL2_LIBRARY})

My test main.cpp:

#include <iostream>
#include "SDL.h" /* This one can't be found */

int main(){
    if (SDL_Init(SDL_INIT_VIDEO) != 0){
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }
    SDL_Quit();
    return 0;
}

Thank you for any help you could give me.

Edit:
I'm using Windows and CLion is configured to use cygwin64.

Body:
This blog post shows how you can do it: Using SDL2 with CMake

On Linux you can use a recent CMake (e.g. version 3.7) and using SDL2 works out of the box.

cmake_minimum_required(VERSION 3.7)
project(SDL2Test)

find_package(SDL2 REQUIRED)
include_directories(SDL2Test ${SDL2_INCLUDE_DIRS})

add_executable(SDL2Test Main.cpp)
target_link_libraries(SDL2Test ${SDL2_LIBRARIES})

Under Windows you can download the SDL2 development package, extract it somewhere and then create a sdl-config.cmake file in the extracted location with the following content:

set(SDL2_INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}/include")

# Support both 32 and 64 bit builds
if (${CMAKE_SIZEOF_VOID_P} MATCHES 8)
  set(SDL2_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/lib/x64/SDL2.lib;${CMAKE_CURRENT_LIST_DIR}/lib/x64/SDL2main.lib")
else ()
  set(SDL2_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/lib/x86/SDL2.lib;${CMAKE_CURRENT_LIST_DIR}/lib/x86/SDL2main.lib")
endif ()

string(STRIP "${SDL2_LIBRARIES}" SDL2_LIBRARIES)

When you now configure inside the CMake-GUI application there will be a SDL2_DIR variable. You have to point it to the SDL2 directory where you extracted the dev package and reconfigure then everything should work.

You can then include SDL2 headers by just writing #include "SDL.h".


问:
Octave call a function as a variable of another function
I wrote a bisection method in Octave but it can't consume another function..

My bisection method code is like:

function[x,b] = bisection(f,a,b)

  t = 10e-8

  while abs(b-a) > t;
    c = (a+b)/2;

    if f(a) * f(b) <= 0
       a = a;
       b = c;
    else
       b = b;
       a = c
    endif
  endwhile

  x = (a+b)/2
endfunction
```

<p>And I already have a file f1.m:</p>

```function y = f1(x)
  y = x^2 - 4;
endfunction
```

<p>But when I call <code>[x,v] = bisection[f1,0,5]</code>, I get:</p>

```>> [t,v] = bisection(f1,0,5)
   error: 'x' undefined near line 2 column 5
   error: called from
          f1 at line 2 column 3
   error: evaluating argument list element number 1
```

Body:
I wrote a bisection method in Octave but it can't consume another function..

My bisection method code is like:

function[x,b] = bisection(f,a,b)

  t = 10e-8

  while abs(b-a) > t;
    c = (a+b)/2;

    if f(a) * f(b) <= 0
       a = a;
       b = c;
    else
       b = b;
       a = c
    endif
  endwhile

  x = (a+b)/2
endfunction

And I already have a file f1.m:

function y = f1(x)
  y = x^2 - 4;
endfunction

But when I call [x,v] = bisection[f1,0,5], I get:

>> [t,v] = bisection(f1,0,5)
   error: 'x' undefined near line 2 column 5
   error: called from
          f1 at line 2 column 3
   error: evaluating argument list element number 1

Body:
what you want is to pass a pointer to f1 to your function bisection so the right call would be

[t,v] = bisection(@f1,0,5)

which outputs:

t =    1.0000e-07
a =  0.62500
a =  0.93750
a =  1.0938
a =  1.1719
a =  1.2109
a =  1.2305
a =  1.2402
a =  1.2451
a =  1.2476
a =  1.2488
a =  1.2494
a =  1.2497
a =  1.2498
a =  1.2499
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
a =  1.2500
x =  1.2500
t =  1.2500
v =  1.2500


问:
Angular JS : Filter using textbox and Checkbox
I'm New with angularJS and I just want to filter my data using textbox together with checkbox.

Here is my data:

```<code>  $scope.array = [
    {name: 'Tobias', lname: 'TLname', company: 'x'},
    {name: 'Jeff', lname: 'JLname', company: 'x'},
    {name: 'Brian', lname: 'BLname', company: 'x'},
    {name: 'Igor', lname: 'ILname', company: 'y'},
    {name: 'James', lname: 'JLname', company: 'z'},
    {name: 'Brad', lname: 'BLname', company: 'y'}
  ];
</code>```

All I want is if I going to choose x from checkbox it will show the rows related with Tobias Jeff Brian and if I'm going to uncheck the checkbox and type br, Brian and Brad will show but if I'm going to check the x checkbox only  Bryan should show.

Thanks in advance.

答:
```<code><div ng-controller="ctrl2">
<div>
  <input type="text" ng-model="myfilter" placeholder="filter">
  <br>avilable:<input type="checkbox" ng-model="check" checked value="avilable">
  <br>
  <span ng-click="sortby('name')">name</span><span ng-click="sortby('country')">country</span>
</div>
<p></p>
<div class="row1" ng-repeat="x in names | orderBy:myorder | filter:check | filter:myfilter">
  <span class="row2">
  {{x.name}}
</span>
  <span class="row2">
  {{x.country}}
</span>
</div>
<h1>{{myfilter}}</h1>
</code>```

Body:
I'm New with angularJS and I just want to filter my data using textbox together with checkbox.

Here is my data:

  $scope.array = [
    {name: 'Tobias', lname: 'TLname', company: 'x'},
    {name: 'Jeff', lname: 'JLname', company: 'x'},
    {name: 'Brian', lname: 'BLname', company: 'x'},
    {name: 'Igor', lname: 'ILname', company: 'y'},
    {name: 'James', lname: 'JLname', company: 'z'},
    {name: 'Brad', lname: 'BLname', company: 'y'}
  ];

All I want is if I going to choose x from checkbox it will show the rows related with Tobias Jeff Brian and if I'm going to uncheck the checkbox and type br, Brian and Brad will show but if I'm going to check the x checkbox only  Bryan should show.

Thanks in advance.


问:
How do I place a UIWebView in a table view cell and maintain its scroll bars?
How can I place a UIWebView in a table view cell, yet maintain the UIWebView's scrollbars?  My table view does have multiple cells and a header frame as well, and I do need it to be scrollable because it has many rows.

The text displays perfectly fine when I use UITextView and it shows scrollers as well, but the problem is that my content is rich text, so I don't have any other option but to show the content in UIWebView. Any ideas, hacks?

答: UIWebView will automatically display scrollbars when it has content that exceeds the height of the UIView.</p>

OwnerDisplayName: Mustafa

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: lostInTransit


问:
GIT lets me checkout another branch with uncommitted changes, and alters files in that branch
GIF demonstrating the sequence of events

I create a branch foo, alter a file, then without committing the change I checkout master. GIT lets me do the checkout and the modification is carried over.

I commit this change.

Switch back to the branch foo, alter a file -- coincidentally in a way that makes it identical to the version in master -- then without committing the change I checkout master. This time I get an error "Error: Your local changes to the following files would be overwritten by checkout: index.html Please commit your changes or stash them before you can switch branches.  Aborting"

What is responsible for this inconsistent behavior?

答:
As because master got your first commit, moving another active change from foo to master will be prevented as a fail safe condition. If you commit your second change in foo that won't be an issue though.

However, as a better way, I suggest you to rebase foo over master to make it same instead of trying to make the same modification.


问:
How can I split data in an input field using only JavaScript?
I have a form with an option to add a post code (or zip code for US readers), and I want to split the input into the following format: XXX XXXX.

I am using the following JavaScript to split it into threes (XXX XXX XXX); however, I would like to split the first three characters from the second four characters. How can I do that?

```<code>var ecode = document.getElementById("postcode");
ecode.oninput = function() {
    var format = ecode.value.split(" ").join("");
    if (format.length > 0) {
        format = format.match(new RegExp('.{1, 3}','g')).join(" ");
    }
    this.value = format;
};
</code>```

答:
I would probably do this:

```<code>var format = ecode.value.replace(/ /g, "");
ecode.value = format.substr(0, 3) + " " + format.substr(3, 4);
</code>```

Note this will discard anything past the 7 first non-whitespace characters.

ContentLicense: CC BY-SA 4.0

Body:
I have a form with an option to add a post code (or zip code for US readers), and I want to split the input into the following format: XXX XXXX.

I am using the following JavaScript to split it into threes (XXX XXX XXX); however, I would like to split the first three characters from the second four characters. How can I do that?

var ecode = document.getElementById("postcode");
ecode.oninput = function() {
    var format = ecode.value.split(" ").join("");
    if (format.length > 0) {
        format = format.match(new RegExp('.{1, 3}','g')).join(" ");
    }
    this.value = format;
};

Body:
I would probably do this:

var format = ecode.value.replace(/ /g, "");
ecode.value = format.substr(0, 3) + " " + format.substr(3, 4);

Note this will discard anything past the 7 first non-whitespace characters.


问:
How to turn arrays into a dataframe?
I have this array, and wish to turn it into a DataFrame, but get an error.

The array k looks like this:

```<code>In[10]: print(k)

Out[10]:
(array([        nan,         nan,         nan, ...,  0.73820147,
        0.7381864 ,  0.73820208]), array([        nan,         nan,         nan, ...,  0.74638753,
        0.74618251,  0.745983  ]))
</code>```

Then I tried to:

```<code>In[11]: df=pd.DataFrame(k)

Out[11]:..

  File "C:\Users\admin\Anaconda2\lib\site-packages\pandas\core\frame.py", line 354, in __init__
    raise ValueError('DataFrame constructor not properly called!')

ValueError: DataFrame constructor not properly called!
</code>```

答:
You are passing a tuple to the DataFrame constructor.  You need to pass a list.

Try this:

```<code>import pandas as pd

data = (np.array([np.nan, 0.738202]),
        np.array([np.nan, 0.745983]))

df = pd.DataFrame(list(data))
df = pd.DataFrame(data)
</code>```

The second constructor will fail.

Title: How to turn arrays into a dataframe?

Body:
I have this array, and wish to turn it into a DataFrame, but get an error.

The array k looks like this:

In[10]: print(k)

Out[10]:
(array([        nan,         nan,         nan, ...,  0.73820147,
        0.7381864 ,  0.73820208]), array([        nan,         nan,         nan, ...,  0.74638753,
        0.74618251,  0.745983  ]))

Then I tried to:

In[11]: df=pd.DataFrame(k)

Out[11]:..

  File "C:\Users\admin\Anaconda2\lib\site-packages\pandas\core\frame.py", line 354, in __init__
    raise ValueError('DataFrame constructor not properly called!')

ValueError: DataFrame constructor not properly called!

Body:
You are passing a tuple to the DataFrame constructor.  You need to pass a list.

Try this:

import pandas as pd

data = (np.array([np.nan, 0.738202]),
        np.array([np.nan, 0.745983]))

df = pd.DataFrame(list(data))
df = pd.DataFrame(data)

The second constructor will fail.


问:
Save periodically with AJAX
I'd like to write a code that will save content of an element either after some many characters have been typed or once so often.

I will call ajax function and send content to a script to save in the background. Just not sure how to get that count going. Here's if I count to 30, but how would it look if it were continuous typing, i.e. every 30 chars?

```<code>var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         $.ajax({
             ...
         });
     }
     count++;
});
</code>```

答:
Could use a custom event that can be triggered either by count or time interval

$(document).on("keyup", "#target", function(count) {
  var $input = $(this),
    count = ($input.data('count') || 0) + 1;
  if (count >= 30) {
    $input.trigger('server_update');
    count = 0;
  }
  $input.data('count', count);
}).on('server_update', '#target', function() {
  var $input = $(this);
  // no need to update server if count is zero
  if ($input.data('count')) {
    $input.data('count', 0);
    // do ajax
    console.log( this.value)
  }
});

setInterval(function() {
  $('#target').trigger('server_update');

}, 1000)```
<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>
<input id="target" value="test"></code>```

Title: Save periodically with AJAX

Body:
I'd like to write a code that will save content of an element either after some many characters have been typed or once so often.

I will call ajax function and send content to a script to save in the background. Just not sure how to get that count going. Here's if I count to 30, but how would it look if it were continuous typing, i.e. every 30 chars?

var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         $.ajax({
             ...
         });
     }
     count++;
});

Body:
Could use a custom event that can be triggered either by count or time interval

$(document).on("keyup", "#target", function(count) {
  var $input = $(this),
    count = ($input.data('count') || 0) + 1;
  if (count >= 30) {
    $input.trigger('server_update');
    count = 0;
  }
  $input.data('count', count);
}).on('server_update', '#target', function() {
  var $input = $(this);
  // no need to update server if count is zero
  if ($input.data('count')) {
    $input.data('count', 0);
    // do ajax
    console.log( this.value)
  }
});

setInterval(function() {
  $('#target').trigger('server_update');

}, 1000)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="target" value="test">


答:
You could use a replace for the first three characters.

var format = '',
    i;

for (i = 0; i < 10; i++) {
    format += 'X';
    console.log(format.replace(/.../, '$& '));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: How can I split data in an input field using only JavaScript?

Body:
You could use a replace for the first three characters.

var format = '',
    i;

for (i = 0; i < 10; i++) {
    format += 'X';
    console.log(format.replace(/.../, '$& '));
}

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
parameter type 'System.Collections.Generic.List<WindowsFormsApplication8.receipt>' is less accessible than method
List _list;
        string _total, _cash, _change, _date;

```<code>public Form8(List<receipt> datasource, string total, string cash, string change, string date)
{
    InitializeComponent();
    _list = datasource;
    _total = total;
    _cash = cash;
    _change = change;
    _date = date;
}
</code>```

enter image description here

Here I got an error.

Error 1 Inconsistent accessibility: parameter type 'System.Collections.Generic.List' is less accessible than method 'WindowsFormsApplication8.Form8.Form8(System.Collections.Generic.List, string, string, string, string)' C:\Users\thush\Documents\Visual Studio 2012\Projects\WindowsFormsApplication8\WindowsFormsApplication8\Form8.cs 18 16 WindowsFormsApplication8

答:
Unless you've created your own System.Collections.Generic.List<T> class, the error is specifically referring to your receipt class.  Note the accessibility of where it's being used:

```<code>public Form8(List<receipt> ...
</code>```

This is in turn part of a public class (Form8).  So the error is telling you that these things are more accessible than the types you're requiring in them, specifically receipt.

From the perspective of consuming code, any code can see your Form8 class and can see its constructor.  But if that same consuming code can't see the receipt class, then that constructor would make no sense.  The compiler prevents this by the error you're seeing.

In short, if you want to use receipt in a public way like this, then receipt itself needs to be public.

So basically just as your Form8 class is public:

```<code>public partial class Form8 : Form
{
    //...
</code>```

So must your receipt class be:

```<code>public class receipt
{
    //...
</code>```

(Mostly guessing as to the declaration of the receipt class, since you don't show it.)

Body:
List _list;
        string _total, _cash, _change, _date;

public Form8(List<receipt> datasource, string total, string cash, string change, string date)
{
    InitializeComponent();
    _list = datasource;
    _total = total;
    _cash = cash;
    _change = change;
    _date = date;
}

enter image description here

Here I got an error.

Error 1 Inconsistent accessibility: parameter type 'System.Collections.Generic.List' is less accessible than method 'WindowsFormsApplication8.Form8.Form8(System.Collections.Generic.List, string, string, string, string)' C:\Users\thush\Documents\Visual Studio 2012\Projects\WindowsFormsApplication8\WindowsFormsApplication8\Form8.cs 18 16 WindowsFormsApplication8

Body:
Unless you've created your own System.Collections.Generic.List<T> class, the error is specifically referring to your receipt class.  Note the accessibility of where it's being used:

public Form8(List<receipt> ...

This is in turn part of a public class (Form8).  So the error is telling you that these things are more accessible than the types you're requiring in them, specifically receipt.

From the perspective of consuming code, any code can see your Form8 class and can see its constructor.  But if that same consuming code can't see the receipt class, then that constructor would make no sense.  The compiler prevents this by the error you're seeing.

In short, if you want to use receipt in a public way like this, then receipt itself needs to be public.

So basically just as your Form8 class is public:

public partial class Form8 : Form
{
    //...

So must your receipt class be:

public class receipt
{
    //...

(Mostly guessing as to the declaration of the receipt class, since you don't show it.)


问:
I can't resize numpy.ndarrays
I know that several questions have been asked about numpy.resize(array, new_size), but it's not doing anything for me. Right now, I have x_array.shape == (1456, 26) and x_array.shape == (1456, 1). I need a way to make their shapes equal. I have tried np.resize(x_array, y_array.shape) but it's not doing anything (no errors, no change). Is it even possible to change the shape like that? Both are numpy.ndarray types. Thank you.</p>

答:
np.resize from the docs Return a new array with the specified shape., so x_array will remain (1456, 26).

```<code>x_array = np.ones([1456, 26])
print x_array

y_array = np.ones([1456, 1])
print y_array

new_array = np.resize(x_array, y_array.shape)
print new_array
</code>```

will need to assign resized array to a new array.

Title: I can't resize numpy.ndarrays

Body:
np.resize from the docs Return a new array with the specified shape., so x_array will remain (1456, 26).

x_array = np.ones([1456, 26])
print x_array

y_array = np.ones([1456, 1])
print y_array

new_array = np.resize(x_array, y_array.shape)
print new_array

will need to assign resized array to a new array.


问:
How to include html page in another page (angular)
I have this page:

 http://www.interload.co.il/upload/5798737.jpg

When I use the "create" page as a differrent html page it works grate, but when I include it in the main page it doesn't work.

I tried this code: (just the last row of the include matters)

<!DOCTYPE html>

<meta charset="windows-1255">
<title>Insert title here</title>

   id
   name
   password
   email
   actions

   {{c.id}}
   {{c.name}}
   {{c.password}}
   {{c.email}}
   <button data-ng-click="g.deleteCompany($index)">X</button>
    <button name="update" ng-click="g.showUpdateCompany()">O</button>

   Company id: <input value="{{c.id}}" disabled="disabled">

   Company name: <input value="{{c.name}}" disabled="disabled">

   Company password: <input ng-model="c.password">

   Company email: <input ng-model="c.email">

   <button ng-click="g.hideUpdateCompany(c)">Save</button>

```
</div>
</div>
</p>

<p>This is the page I want to include: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="windows-1255">
<title>Insert title here</title>
</head>
<body>
<h2>Create new Company:</h2>
Company ID: <input type="text" ng-model="c.newCompany.id"> <br>
Company name: <input type="text" ng-model="c.newCompany.name"> <br>
Company password: <input type="password" ng-model="c.newCompany.password"> <br>
Company email: <input type="email" ng-model="c.newCompany.email"> <br>
<button ng-click="c.createCompany()">Sumbit</button> <br>
<p ng-show="c.success"> Company Added Successfully ! </p>
<p ng-show="c.failure"> Company Failed to be added ! </p>
</div>
</body>
</html></code>```

the conrollers are set in here (ui-view):

/**
 *
 */
var app = angular.module("myApp", [ "ui.router" ]);

app.config([ '$locationProvider', function($locationProvider) {
 $locationProvider.hashPrefix('');
} ]);

app.config(function($stateProvider, $urlRouterProvider) {

 $stateProvider
 .state("main", {
  url : "/main",
  templateUrl : "../HTMLs/AdminMain.html",
 })
 .state("getCompanies", {
  url : "/getCompanies",
  templateUrl : "../HTMLs/getCompanies.html",
  controller : "getCompaniesCTRL as g"
 })
 .state("createCompany", {
  url : "/createCompany",
  templateUrl : "../HTMLs/createCompany.html",
  controller : "createCompanyCTRL as c"
 })
 .state("404", {
     url : "/404",
        templateUrl : "../HTMLs/404.html"
    });
 $urlRouterProvider.when("", "/main"); // first browsing postfix is empty
           // --> route it to /main
 $urlRouterProvider.otherwise('/404'); // when no switch case matches -->
           // route to /404
});```

答:
The correct syntax for ng-include is this:

```<code><div ng-include src="updateCompany.html"></div>
</code>```

or

```<code><ng-include src="updateCompany.html"></ng-include>
</code>```

or

```<code><ng-include src="'updateCompany.html'"></ng-include>
</code>```

or

```<code><div ng-include src="'updateCompany.html'"></div>
</code>```

Hope it helps you

Body:
I have this page:

 http://www.interload.co.il/upload/5798737.jpg

When I use the "create" page as a differrent html page it works grate, but when I include it in the main page it doesn't work.

I tried this code: (just the last row of the include matters)

<!DOCTYPE html>

<meta charset="windows-1255">
<title>Insert title here</title>

   id
   name
   password
   email
   actions

   {{c.id}}
   {{c.name}}
   {{c.password}}
   {{c.email}}
   <button data-ng-click="g.deleteCompany($index)">X</button>
    <button name="update" ng-click="g.showUpdateCompany()">O</button>

   Company id: <input value="{{c.id}}" disabled="disabled">

   Company name: <input value="{{c.name}}" disabled="disabled">

   Company password: <input ng-model="c.password">

   Company email: <input ng-model="c.email">

   <button ng-click="g.hideUpdateCompany(c)">Save</button>

This is the page I want to include:

<!DOCTYPE html>

<meta charset="windows-1255">
<title>Insert title here</title>

Create new Company:

Company ID: <input type="text" ng-model="c.newCompany.id">

Company name: <input type="text" ng-model="c.newCompany.name">

Company password: <input type="password" ng-model="c.newCompany.password">

Company email: <input type="email" ng-model="c.newCompany.email">

<button ng-click="c.createCompany()">Sumbit</button>

 Company Added Successfully !

 Company Failed to be added !

the conrollers are set in here (ui-view):

/**
 *
 */
var app = angular.module("myApp", [ "ui.router" ]);

app.config([ '$locationProvider', function($locationProvider) {
 $locationProvider.hashPrefix('');
} ]);

app.config(function($stateProvider, $urlRouterProvider) {

 $stateProvider
 .state("main", {
  url : "/main",
  templateUrl : "../HTMLs/AdminMain.html",
 })
 .state("getCompanies", {
  url : "/getCompanies",
  templateUrl : "../HTMLs/getCompanies.html",
  controller : "getCompaniesCTRL as g"
 })
 .state("createCompany", {
  url : "/createCompany",
  templateUrl : "../HTMLs/createCompany.html",
  controller : "createCompanyCTRL as c"
 })
 .state("404", {
     url : "/404",
        templateUrl : "../HTMLs/404.html"
    });
 $urlRouterProvider.when("", "/main"); // first browsing postfix is empty
           // --> route it to /main
 $urlRouterProvider.otherwise('/404'); // when no switch case matches -->
           // route to /404
});

Body:
The correct syntax for ng-include is this:

<div ng-include src="updateCompany.html"></div>

or

<ng-include src="updateCompany.html"></ng-include>

or

<ng-include src="'updateCompany.html'"></ng-include>

or

<div ng-include src="'updateCompany.html'"></div>

Hope it helps you


问:
Aborting task that contains never-ending library method (no ability of checking cancellation requests)
I use Pcap.Net for traffic monitoring, and I need it to receive packets until user requests cancellation. I create monitoring task this way (simplified):

```<code>var task1 = Task.Run(() => { communicator.ReceivePackets(0, PacketHandlerCallback); } /*, token*/);
</code>```

Here 0 says execution of ReceivePackets never ends, PacketHandlerCallback is a method that will be executed for each received packet. ReceivePackets is synchronous and does not support cancellation. Generally in my question it could be any other endless synchronous method which code we cannot edit.

The question is how to stop this method execution?

Just passing cancellation token to the task doesn't help because we should also explicitly check if cancellation is requested, e. g. by calling token.throwIfCancellationRequested().

Passing token to callback method is not a solution too because this method will not be invoked until new packet is received but I'd like to stop my task immediately after cancellation.

Using BackgroundWorker causes the same question since we should check CancellationPending.

Creating task2 that periodically checks cancellation requests and then writing var task = Task.WhenAny(task1, task2) doesn't help since ReceivePackets will still be executing.

Should I use Thread.Abort() or maybe there is any other elegant solution?

There are similar questions about TPL on SO but I cannot find any simple and helpful answer.

答:
Usually the Thread.Abort really shouldn't be used as very outdated and dangerous method. However, your situation looks like that you have to kill the thread/process to stop the infinite method.

I suggest you to avoid the aborting for any of your threads, as this can lead you to unstable system, as aborted thread wouldn't be able to clean resources correctly. You may run your method in new AppDomain, and unload that domain in case of cancellation request. Also, as Scott mentioned, a separate Process is a solution too.

If and only if, so some reason this isn't an option for you, you can subscribe for cancellation of your token with Thread.CurrentThread.Abort, but if I were you, I would avoid this option as much as I could.

Also you may create a task from cancellation token and use WhenAll for asynchronously wait for cancellation.

Body:
I use Pcap.Net for traffic monitoring, and I need it to receive packets until user requests cancellation. I create monitoring task this way (simplified):

var task1 = Task.Run(() => { communicator.ReceivePackets(0, PacketHandlerCallback); } /*, token*/);

Here 0 says execution of ReceivePackets never ends, PacketHandlerCallback is a method that will be executed for each received packet. ReceivePackets is synchronous and does not support cancellation. Generally in my question it could be any other endless synchronous method which code we cannot edit.

The question is how to stop this method execution?

Just passing cancellation token to the task doesn't help because we should also explicitly check if cancellation is requested, e. g. by calling token.throwIfCancellationRequested().

Passing token to callback method is not a solution too because this method will not be invoked until new packet is received but I'd like to stop my task immediately after cancellation.

Using BackgroundWorker causes the same question since we should check CancellationPending.

Creating task2 that periodically checks cancellation requests and then writing var task = Task.WhenAny(task1, task2) doesn't help since ReceivePackets will still be executing.

Should I use Thread.Abort() or maybe there is any other elegant solution?

There are similar questions about TPL on SO but I cannot find any simple and helpful answer.


问:
How to execute a Java program from C#?
Wondering if anyone knows a nice way to execute a Java command-line program from C# code at run-time ?

Is it the same as executing native .EXE files ?

Will it run synchronously or asynchronously (which means I may have to wait for the thread to finish to find out the results)

Specifically I would like to call a little utility (which happens to be written in Java) from a web-application on the server side to do some processing on a text file.  I want to wait for it to finish because after the Java program is done processing the text file I want to grab the processed text, and use it within the C# application.

答: Maybe it would run faster if you use jni4net - C#/Java bridge</p>

Title: How to execute a Java program from C#?


问:
How to get a float value from a Input.GetKey in C#
I got it to work but I was hoping for a cleaner solution. Basically its to orbit around the player and you use Q and E to change the value of angle so that you can orbit left and right.

```<code>    if (Input.GetKey(KeyCode.Q)) {
        gotQ = orbitSpeed;
    }

    else {
        gotQ = 0;
    }

    if (Input.GetKey(KeyCode.E)) {
        gotE = orbitSpeed;
    }
    else {
        gotE = 0;
    }
    angle = angle + gotQ - gotE;
</code>```

As you can see I set gotQ and gotE to a positive float value when a key is pressed and set it to 0 when its not. Then angle is changed accordingly. Im trying to clean this up and make it use less resources.

答:
Try this:

```<code>if( Input.GetKey( KeyCode.Q ) )
    angle += orbitSpeed;
if( Input.GetKey( KeyCode.E ) )
    angle -= orbitSpeed;
</code>```

That having been said, the "resources" that are "used" by your piece of code are negligible, and the resources used by this piece of code are negligibly smaller, if not exactly the same.  But readability always counts, and this is certainly more readable.

Body:
I got it to work but I was hoping for a cleaner solution. Basically its to orbit around the player and you use Q and E to change the value of angle so that you can orbit left and right.

    if (Input.GetKey(KeyCode.Q)) {
        gotQ = orbitSpeed;
    }

    else {
        gotQ = 0;
    }

    if (Input.GetKey(KeyCode.E)) {
        gotE = orbitSpeed;
    }
    else {
        gotE = 0;
    }
    angle = angle + gotQ - gotE;

As you can see I set gotQ and gotE to a positive float value when a key is pressed and set it to 0 when its not. Then angle is changed accordingly. Im trying to clean this up and make it use less resources.

Body:
Try this:

if( Input.GetKey( KeyCode.Q ) )
    angle += orbitSpeed;
if( Input.GetKey( KeyCode.E ) )
    angle -= orbitSpeed;

That having been said, the "resources" that are "used" by your piece of code are negligible, and the resources used by this piece of code are negligibly smaller, if not exactly the same.  But readability always counts, and this is certainly more readable.


问:
Should I be encrypting data in a CloudSQL database?
Google CloudSQL documentation states that the data is encrypted in transit and at rest.

I'm using pgcrypto in a Django app to encrypt sensitive information. However I'm wondering if there's any point in doing this since it's already encrypted at rest. The only thing I can imagine is an event where the Google App Engine server with the deployed code gets compromised and the password to the database is somehow leaked - the hackers would eventually have access to unencrypted data as they 'read' it in. But then even with pgcrypto, in the event the GAE server is compromised, they'd still be able to run code to fetch unencrypted data.

Am I overthinking this? The goal is to provide total piece of mind to the end-user with as many 'hurdles' introduced as possible to ensure their data stays completely secure. I have a feeling I don't really need pgcrypto, but looking for an educated reply.

答:
The rather educated answer is: Yes.

Underlying encryption offered by CloudSQL is like FileVault offered by OS X - your stuff truly is encrypted, but if you're logged in, everything is world-readable to you.

The main worry is that you, or someone who is able to compromise your server, is able to read data in plain-text. Data needs to to be encrypted, and I've personally gone beyond the default AES 128-bit offered by most databases and switched to AES 256-bit with initialisation vector (a different one for each encrypted content). This will ensure that the data is encrypted, inaccessible and unreadable by even yourself. Yes, your code is eventually able to decrypt but storing and protecting the decryption keys is a different topic altogether.


问:
How to load a menu module in header and footer in joomla?
I have attached joomla's Menu module in my template. But I needed it to load in footer position at the same time. So that if I add another menu it should be get added in both the positions in Header and in the footer... What i want to do to load a menu module to two different positions in a page, in header and in footer.

I had tried to add multiple positions in administrator section for a menu module...

screen shots are as follows

答:
If I understand correctly, you should simply be able to duplicate your menu module (in extensions->modules) and add the duplicate module to a module position in the footer of your template. If there is no module position in the footer, you add one to the  - list in templateDetails.xml, and add it to index.php in your template, like: </p>

```<code><jdoc:include type="modules" name="footer-menu" style="xhtml" />
</code>```

Body:
If I understand correctly, you should simply be able to duplicate your menu module (in extensions->modules) and add the duplicate module to a module position in the footer of your template. If there is no module position in the footer, you add one to the  - list in templateDetails.xml, and add it to index.php in your template, like:

<jdoc:include type="modules" name="footer-menu" style="xhtml" />


问:
grepl with regex
I have a difficulty using grepl with regex.

Here is a small example:

I have a character vector:

```<code>text <- c(

  "D_Purpose__Repairs" ,
  "Age" ,
  "F_Job"
)
</code>```

And I want to select the words that start with D_ or F_.  So I write:

```<code>grepl("\\>D_.+ | \\>F_.+", text)

grepl("\\D_.+ | \\F_.+", text)

grepl("\\^D_.+ | \\^F_.+", text)
</code>```

However this returns:

```<code>[1] FALSE FALSE FALSE
</code>```

Could you help me understand what I am doing wrong and how should I correct my code?

Your advice will be appreciated.

答:
You don't need to (and must not) escape the caret character with backslashes, and you can't put extra whitespace in your regex around the |.  This works as you intend:</p>

```<code>> grepl("^D_.+|^F_.+", text)
[1]  TRUE FALSE  TRUE
</code>```

Title: grepl with regex

Body:
I have a difficulty using grepl with regex.

Here is a small example:

I have a character vector:

text <- c(

  "D_Purpose__Repairs" ,
  "Age" ,
  "F_Job"
)

And I want to select the words that start with D_ or F_.  So I write:

grepl("\\>D_.+ | \\>F_.+", text)

grepl("\\D_.+ | \\F_.+", text)

grepl("\\^D_.+ | \\^F_.+", text)

However this returns:

[1] FALSE FALSE FALSE

Could you help me understand what I am doing wrong and how should I correct my code?

Your advice will be appreciated.

Body:
You don't need to (and must not) escape the caret character with backslashes, and you can't put extra whitespace in your regex around the |.  This works as you intend:

> grepl("^D_.+|^F_.+", text)
[1]  TRUE FALSE  TRUE


问:
Algorithm/Data structure to rank elements in a tree
Here's what I have: a tree with an arbitrary number of levels.  I need a way to rank all of the nodes at each level FOR each level.  If that's not clear, let's say my first level is the World.  My second level is continents.  My third level is countries.  My fourth level is cities.  Each country has a list of it's cities, ranked in order of population.  Each continent has a list of countries ranked by population.  Each continent ALSO has a list of cities ranked by population. And etc.

The algorithm I imagine is pretty simple recursion, but I'm not sure what the best data structure would be to keep track of these lists.  Each level doesn't know how many sub levels it has, so I can't declare an arbitrary number of lists.

Any thoughts?

Here's some sample code:

```<code>public void calcStats()
    {
        initWorldRanks();//clears ranks for the world
        for(Entity continent:theWorld.getChildren())
        {
            initContinentRanks();//clears ranks for the continent
            for(Entity country:continent.getChildren())
            {
                initCountryRanks();//clears ranks for the country
                for(Entity city:country.getChildren())
                {
                                    //Assume that add preserves sorted order.  Sorting is easy.  The tricky part is that each entity needs to be added to its ancestors.  I don't want to have fixed data structures
                    worldCityRanks.add(city);
                    continentCityRanks.add(city);
                    countryCityRanks.add(city);
                }
                worldCountryRanks.add(country);
                            continentCountryRanks.add(country);
            }
            worldContinentRanks.add(continent);
        }
</code>```

Everything is correctly ranked but this restricts me to a definite 4 level structure.

答:
The key thing is that you don't want to have to recompute the count for each node by traversing its entire subtree. Cache the total count in each node. Each node then only needs to collect the values from its children to compute its own total (which it should also cache).

You don't say whether these nodes are mutable or not. If they're immutable, then it's easy: you construct a node's total when all of it's children are added at construction time.

If they're mutable you can have each node tell its parent when its count changes. The parent could update its own count and tell its parent, and so-on up the tree. This makes updating a count O(depth of tree) or roughly O(logn) (depending on how well-balanced your tree is).

For actually sorting each node's children do whatever you'd normally do: use an ArrayList and sort it, or use some kind of sorted collection that maintains sort order (eg: TreeSet, though make sure you distingiguish between elements that have the same population). The important thing is that you'll only look at your immediate children's value (ie: the cached sum) when comparing, never your indirect descendants.

Update

Based on your update to the question, one of your problems is that you've get separate methods for adding things at different levels. ie: worldCityRanks.add, continentCityRanks.add, countryCityRanks.add, etc. You should replace these all with a single method that takes the depth as a parameter. eg:

```<code>// Probably in your Entity class
public void addDescendant(int distance, Entity descendant) {
  // this replaces worldCityRanks.add, continentCityRanks.add,
  // countryCityRanks.add, etc.
}
</code>```

Then instead of having 4 fields for your descendant collections, you'd have a collection (probably an ArrayList) to hold them. You'd expand this as necessary.

Another problem is that you have these hard-coded nested for loops. To handle arbitrary (within reason) depth the easiest approach is to use recursion. eg:

```<code>public void calcStats() {
  theWorld.initAllRanks();
  List<Entity> ancestors = new ArrayList<Entity>();
  theWorld.accumulateAllRanks(ancestors);
}

class Entity ... {
  ...

  void initAllRanks() {
    initRanks();
    for(Entity child: getChildren()) {
      child.initAllRanks();
    }
  }

  void accumulateAllRanks(List<Entity> ancestors) {
    int distance = ancestors.size();
    for(Entity ancestor: ancestors) {
      distance--;
      ancestor.addDescendant(distance, this);
    }
    ancestors.add(this); // push this
    for(Entity child: getChildren()) {
      child.accumulateAllRanks(ancestors);
    }
    ancestors.remove(ancestors.size() - 1); // pop this
  }
</code>```

This is assuming you really want to store rankings for each level (which is what your code sample implies). That approach makes lookups fast, but it can make updates slow and it also consumes more memory than some other approaches. In particular, you could just maintain lists of global rankings, and then filter these lists at query time. Again, this makes updates faster and consumes less memory, but makes queries slower than the approach you appear to be using currently.

Body:
Here's what I have: a tree with an arbitrary number of levels.  I need a way to rank all of the nodes at each level FOR each level.  If that's not clear, let's say my first level is the World.  My second level is continents.  My third level is countries.  My fourth level is cities.  Each country has a list of it's cities, ranked in order of population.  Each continent has a list of countries ranked by population.  Each continent ALSO has a list of cities ranked by population. And etc.

The algorithm I imagine is pretty simple recursion, but I'm not sure what the best data structure would be to keep track of these lists.  Each level doesn't know how many sub levels it has, so I can't declare an arbitrary number of lists.

Any thoughts?

Here's some sample code:

public void calcStats()
    {
        initWorldRanks();//clears ranks for the world
        for(Entity continent:theWorld.getChildren())
        {
            initContinentRanks();//clears ranks for the continent
            for(Entity country:continent.getChildren())
            {
                initCountryRanks();//clears ranks for the country
                for(Entity city:country.getChildren())
                {
                                    //Assume that add preserves sorted order.  Sorting is easy.  The tricky part is that each entity needs to be added to its ancestors.  I don't want to have fixed data structures
                    worldCityRanks.add(city);
                    continentCityRanks.add(city);
                    countryCityRanks.add(city);
                }
                worldCountryRanks.add(country);
                            continentCountryRanks.add(country);
            }
            worldContinentRanks.add(continent);
        }

Everything is correctly ranked but this restricts me to a definite 4 level structure.

Body:
The key thing is that you don't want to have to recompute the count for each node by traversing its entire subtree. Cache the total count in each node. Each node then only needs to collect the values from its children to compute its own total (which it should also cache).

You don't say whether these nodes are mutable or not. If they're immutable, then it's easy: you construct a node's total when all of it's children are added at construction time.

If they're mutable you can have each node tell its parent when its count changes. The parent could update its own count and tell its parent, and so-on up the tree. This makes updating a count O(depth of tree) or roughly O(logn) (depending on how well-balanced your tree is).

For actually sorting each node's children do whatever you'd normally do: use an ArrayList and sort it, or use some kind of sorted collection that maintains sort order (eg: TreeSet, though make sure you distingiguish between elements that have the same population). The important thing is that you'll only look at your immediate children's value (ie: the cached sum) when comparing, never your indirect descendants.

Update

Based on your update to the question, one of your problems is that you've get separate methods for adding things at different levels. ie: worldCityRanks.add, continentCityRanks.add, countryCityRanks.add, etc. You should replace these all with a single method that takes the depth as a parameter. eg:

// Probably in your Entity class
public void addDescendant(int distance, Entity descendant) {
  // this replaces worldCityRanks.add, continentCityRanks.add,
  // countryCityRanks.add, etc.
}

Then instead of having 4 fields for your descendant collections, you'd have a collection (probably an ArrayList) to hold them. You'd expand this as necessary.

Another problem is that you have these hard-coded nested for loops. To handle arbitrary (within reason) depth the easiest approach is to use recursion. eg:

public void calcStats() {
  theWorld.initAllRanks();
  List<Entity> ancestors = new ArrayList<Entity>();
  theWorld.accumulateAllRanks(ancestors);
}

class Entity ... {
  ...

  void initAllRanks() {
    initRanks();
    for(Entity child: getChildren()) {
      child.initAllRanks();
    }
  }

  void accumulateAllRanks(List<Entity> ancestors) {
    int distance = ancestors.size();
    for(Entity ancestor: ancestors) {
      distance--;
      ancestor.addDescendant(distance, this);
    }
    ancestors.add(this); // push this
    for(Entity child: getChildren()) {
      child.accumulateAllRanks(ancestors);
    }
    ancestors.remove(ancestors.size() - 1); // pop this
  }

This is assuming you really want to store rankings for each level (which is what your code sample implies). That approach makes lookups fast, but it can make updates slow and it also consumes more memory than some other approaches. In particular, you could just maintain lists of global rankings, and then filter these lists at query time. Again, this makes updates faster and consumes less memory, but makes queries slower than the approach you appear to be using currently.


问:
Scipy.optimize differential_evolution Index error: tuple index out of range
I have a smooth function f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2) The task is to find a minimum of a non-smooth function h(x) = int(f(x)) on the interval of 1 to 30. In other words, each value of f (x) is converted to type int and the function takes only integer values.

I am using 2 methods to find a minimum from scipy.optimize: minimize and differential_evolution. The minimize gives me the result of -5 whereas differential_evolution gives Index error: tuple index out of range
The question is why and what is wrong?

Here is the code:

```<code>import math
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import differential_evolution
from scipy.linalg import *
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return f(x).astype(int)

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()

#res = minimize(h, 30, method='BFGS')
#print res

res = differential_evolution(h, [1, 30])
print res
</code>```

答:
That's because the bounds parameter of differential_evolution expects a sequence of (min, max) pairs. Given that you only have a pair of min and max values for x, you can do the following:

```<code>res = differential_evolution(h, [(1, 30)])
print res
</code>```

which would result in:

```<code>     fun: -11.0
 message: 'Optimization terminated successfully.'
    nfev: 92
     nit: 5
 success: True
       x: array([ 25.76747524])
</code>```

For more information, please see the official documentation: https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.differential_evolution.html

I hope this helps.

Body:
I have a smooth function f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2) The task is to find a minimum of a non-smooth function h(x) = int(f(x)) on the interval of 1 to 30. In other words, each value of f (x) is converted to type int and the function takes only integer values.

I am using 2 methods to find a minimum from scipy.optimize: minimize and differential_evolution. The minimize gives me the result of -5 whereas differential_evolution gives Index error: tuple index out of range
The question is why and what is wrong?

Here is the code:

import math
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import differential_evolution
from scipy.linalg import *
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return f(x).astype(int)

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()

#res = minimize(h, 30, method='BFGS')
#print res

res = differential_evolution(h, [1, 30])
print res

Body:
That's because the bounds parameter of differential_evolution expects a sequence of (min, max) pairs. Given that you only have a pair of min and max values for x, you can do the following:

res = differential_evolution(h, [(1, 30)])
print res

which would result in:

     fun: -11.0
 message: 'Optimization terminated successfully.'
    nfev: 92
     nit: 5
 success: True
       x: array([ 25.76747524])

For more information, please see the official documentation: https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.differential_evolution.html

I hope this helps.


问:
GitHub API: how efficiently get the total contributors amount per repository?
Is there a way to efficiently get the amount of all different contributors of a GitHub repository using the GitHub API?

I mean, without necessarily getting all the contributor objects and manually count the total amount.

答:
A solution may be using pagination.

When we use pagination, we get some information in the Response Header about the total amount of pages according to how many items per page we are requesting (using the per_page parameter).

So a trick could be requesting the list of contributors with one item per page:

```<code>https://api.github.com/repos/:owner/:repo/contributors?per_page=1
</code>```

doing this in our Response Header there will be a Link property with the following content:

Link:https://api.github.com/repositories/ID/contributors?per_page=1&page=2;
  rel="next",
  https://api.github.com/repositories/ID/contributors?per_page=1&page=XXXXXXXX;
  rel="last"

the XXXXXXXX value, just before rel="last" will be the total amount of pages, but since we are requesting one item per page, it will be also the total amount of contributors.

Body:
A solution may be using pagination.

When we use pagination, we get some information in the Response Header about the total amount of pages according to how many items per page we are requesting (using the per_page parameter).

So a trick could be requesting the list of contributors with one item per page:

https://api.github.com/repos/:owner/:repo/contributors?per_page=1

doing this in our Response Header there will be a Link property with the following content:

Link:https://api.github.com/repositories/ID/contributors?per_page=1&page=2;
  rel="next",
  https://api.github.com/repositories/ID/contributors?per_page=1&page=XXXXXXXX;
  rel="last"

the XXXXXXXX value, just before rel="last" will be the total amount of pages, but since we are requesting one item per page, it will be also the total amount of contributors.


问:
SetText EditText not working in Fragment using OnStart, OnResume and onCreateView
I am using Fragment and due to some reasons, EditText is not displaying the data retrieved from a POST request which gives JSON response.

There is no issue in JSON response. I also used OnResume and OnStart methods but still nothing working.

Am I missing anthing?

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View fragment_profile = inflater.inflate(R.layout.fragment_profile, container, false);
    InitializeControls(fragment_profile);
    NM_Profile.getInstance(this.getContext()).ViewProfile(new IResultListener<JOM_User>() {
        @Override
        public void getResult(JOM_User object) {
            user = object.getUser();
            if(user != null) {
                txtEmailAddress_Profile.setText(user.getEmailAddress());
            }
        }
    });

    return inflater.inflate(R.layout.fragment_profile, container, false);
}

@Override
public void OnStart() {
    if(user != null) {
        txtEmailAddress_Profile.setText(user.getEmailAddress());
    }
    return super.OnStart();
}

@Override
public void OnResume() {
    if(user != null) {
        txtEmailAddress_Profile.setText(user.getEmailAddress());
    }
    return super.OnStart();
}
</code>```

答:
Try initialising txtEmailAddress_Profile EditText inside the onCreateView() rather than InitializeControls().

Try something like this:

```<code>private EditText txtEmailAddress_Profile;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View fragment_profile = inflater.inflate(R.layout.fragment_profile, container, false);
    InitializeControls(fragment_profile);
    txtEmailAddress_Profile =(EditText) view.findViewById(R.id.YourEditText);
    NM_Profile.getInstance(this.getContext()).ViewProfile(new IResultListener<JOM_User>() {
        @Override
        public void getResult(JOM_User object) {
            user = object.getUser();
            if(user != null) {
                txtEmailAddress_Profile.setText(user.getEmailAddress());
            }
        }
    });

    return inflater.inflate(R.layout.fragment_profile, container, false);
}
</code>```

Body:
I am using Fragment and due to some reasons, EditText is not displaying the data retrieved from a POST request which gives JSON response.

There is no issue in JSON response. I also used OnResume and OnStart methods but still nothing working.

Am I missing anthing?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View fragment_profile = inflater.inflate(R.layout.fragment_profile, container, false);
    InitializeControls(fragment_profile);
    NM_Profile.getInstance(this.getContext()).ViewProfile(new IResultListener<JOM_User>() {
        @Override
        public void getResult(JOM_User object) {
            user = object.getUser();
            if(user != null) {
                txtEmailAddress_Profile.setText(user.getEmailAddress());
            }
        }
    });

    return inflater.inflate(R.layout.fragment_profile, container, false);
}

@Override
public void OnStart() {
    if(user != null) {
        txtEmailAddress_Profile.setText(user.getEmailAddress());
    }
    return super.OnStart();
}

@Override
public void OnResume() {
    if(user != null) {
        txtEmailAddress_Profile.setText(user.getEmailAddress());
    }
    return super.OnStart();
}

Body:
Try initialising txtEmailAddress_Profile EditText inside the onCreateView() rather than InitializeControls().

Try something like this:

private EditText txtEmailAddress_Profile;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View fragment_profile = inflater.inflate(R.layout.fragment_profile, container, false);
    InitializeControls(fragment_profile);
    txtEmailAddress_Profile =(EditText) view.findViewById(R.id.YourEditText);
    NM_Profile.getInstance(this.getContext()).ViewProfile(new IResultListener<JOM_User>() {
        @Override
        public void getResult(JOM_User object) {
            user = object.getUser();
            if(user != null) {
                txtEmailAddress_Profile.setText(user.getEmailAddress());
            }
        }
    });

    return inflater.inflate(R.layout.fragment_profile, container, false);
}


问:
Angular JS : Filter using textbox and Checkbox
I'm New with angularJS and I just want to filter my data using textbox together with checkbox.

Here is my data:

```<code>  $scope.array = [
    {name: 'Tobias', lname: 'TLname', company: 'x'},
    {name: 'Jeff', lname: 'JLname', company: 'x'},
    {name: 'Brian', lname: 'BLname', company: 'x'},
    {name: 'Igor', lname: 'ILname', company: 'y'},
    {name: 'James', lname: 'JLname', company: 'z'},
    {name: 'Brad', lname: 'BLname', company: 'y'}
  ];
</code>```

All I want is if I going to choose x from checkbox it will show the rows related with Tobias Jeff Brian and if I'm going to uncheck the checkbox and type br, Brian and Brad will show but if I'm going to check the x checkbox only  Bryan should show.

Thanks in advance.

答:
```<code>app.controller('ctrl2', function ($scope) {
$scope.sortby = function (x) {
    $scope.myorder = x;
}

$scope.names = [
    { name: 'Jani', country: 'Norway', available: true },
    { name: 'Carl', country: 'Sweden', available: false },
    { name: 'Margareth', country: 'England', available: true },
    { name: 'Hege', country: 'Norway', available: true },
    { name: 'Joe', country: 'Denmark', available: false },
    { name: 'Gustav', country: 'Sweden', available: false },
    { name: 'Birgit', country: 'Denmark', available: false },
    { name: 'Mary', country: 'England', available: true },
    { name: 'Kai', country: 'Norway', available: false }
];
</code>```

<p>});</p>

Body:
I'm New with angularJS and I just want to filter my data using textbox together with checkbox.

Here is my data:

  $scope.array = [
    {name: 'Tobias', lname: 'TLname', company: 'x'},
    {name: 'Jeff', lname: 'JLname', company: 'x'},
    {name: 'Brian', lname: 'BLname', company: 'x'},
    {name: 'Igor', lname: 'ILname', company: 'y'},
    {name: 'James', lname: 'JLname', company: 'z'},
    {name: 'Brad', lname: 'BLname', company: 'y'}
  ];

All I want is if I going to choose x from checkbox it will show the rows related with Tobias Jeff Brian and if I'm going to uncheck the checkbox and type br, Brian and Brad will show but if I'm going to check the x checkbox only  Bryan should show.

Thanks in advance.

Body:
app.controller('ctrl2', function ($scope) {
$scope.sortby = function (x) {
    $scope.myorder = x;
}

$scope.names = [
    { name: 'Jani', country: 'Norway', available: true },
    { name: 'Carl', country: 'Sweden', available: false },
    { name: 'Margareth', country: 'England', available: true },
    { name: 'Hege', country: 'Norway', available: true },
    { name: 'Joe', country: 'Denmark', available: false },
    { name: 'Gustav', country: 'Sweden', available: false },
    { name: 'Birgit', country: 'Denmark', available: false },
    { name: 'Mary', country: 'England', available: true },
    { name: 'Kai', country: 'Norway', available: false }
];

});


问:
Node.js application listens to message queue and add messages to redis asynchronously
I am developing a node.js component that listens to a message queue (ActiveMQ) and adds the received messages to redis in batches (must be 20 per batch).

There is no problem when number of messages received from ActiveMQ is 10 per second or less.

My problem is that messages are added to the queue every 4 milliseconds. Which causes the number of records added to the batch to be sometimes more than 20 per batch.

```<code>const stompit = require('stompit');
var uuid = require('node-uuid');
var Redis = require('ioredis');

var redis = new Redis();
var pipeline = redis.pipeline();
var batchCounter = 0;

stompit.connect({ host: 'localhost', port: 61613 }, function(err1, client) {

client.subscribe({ destination: 'MyQueue' }, function(err2, msg) {
    msg.readString('UTF-8', function(err3, body) {

        if (batchCounter >= 20){
            pipeline.exec(function(err4, results) {
                pipeline = redis.pipeline();
                batchCounter = 0;
                console.log(results);
            });
        }

        batchCounter++;
        pipeline.set(uuid.v1(), JSON.stringify(body));
        //client.disconnect();
      });
  });
  });
</code>```

How can fix this problem?
Thank you

答:
I ended up controlling number of records per batch using flags. I believe there is another possible, probably more efficient, fix to this which is controlling the process of reading from ActiveMQ. But, in this situation, flags did the job for me. Complete code using flags is in the following link:

https://github.com/TamerB/ToActiveMQToRedis/blob/master/consumer/app.js

Body:
I am developing a node.js component that listens to a message queue (ActiveMQ) and adds the received messages to redis in batches (must be 20 per batch).

There is no problem when number of messages received from ActiveMQ is 10 per second or less.

My problem is that messages are added to the queue every 4 milliseconds. Which causes the number of records added to the batch to be sometimes more than 20 per batch.

const stompit = require('stompit');
var uuid = require('node-uuid');
var Redis = require('ioredis');

var redis = new Redis();
var pipeline = redis.pipeline();
var batchCounter = 0;

stompit.connect({ host: 'localhost', port: 61613 }, function(err1, client) {

client.subscribe({ destination: 'MyQueue' }, function(err2, msg) {
    msg.readString('UTF-8', function(err3, body) {

        if (batchCounter >= 20){
            pipeline.exec(function(err4, results) {
                pipeline = redis.pipeline();
                batchCounter = 0;
                console.log(results);
            });
        }

        batchCounter++;
        pipeline.set(uuid.v1(), JSON.stringify(body));
        //client.disconnect();
      });
  });
  });

How can fix this problem?
Thank you