问:
Subtracting each element of list from every elements on its right in the same list
I need to manipulate list to get subtraction (subtracting each number from every number on its right).

I have tried using below code which is working with 2 for loops, is there anyway I can do it in only 1 for loop or in a better way then I did.

```<code>list=[3,2,5,4,3]
output_list = [0]

    for element in list:
        for i in range(0, length(list)):
            new_element = [ (list[i] - element) if i > index(element) else 0]
            if new_element > 0:
                output_list.append( new_element )
</code>```

example:
input [3,2,5,4,3]

subtract like [2-3, 5-3, 4-3, 3-3, 5-2, 4-2, 3-2, 4-5, 3-5, 3-4] = [-1, 2, 1, 0, 3, 2, 1, -1, -2, 1]

output with values > 0, first 0 is from initialization [0, 2, 1, 3, 2, 1, 1]

答:
using list comprehension

```<code>a=[3,2,5,4,3]
b= [j-a[i] for i,v in enumerate(a) for j in a[i+1:] if j-a[i]>0]

print(b)
</code>```

output

```<code> [2, 1, 3, 2, 1]
</code>```

Body:
I need to manipulate list to get subtraction (subtracting each number from every number on its right).

I have tried using below code which is working with 2 for loops, is there anyway I can do it in only 1 for loop or in a better way then I did.

list=[3,2,5,4,3]
output_list = [0]

    for element in list:
        for i in range(0, length(list)):
            new_element = [ (list[i] - element) if i > index(element) else 0]
            if new_element > 0:
                output_list.append( new_element )

example:
input [3,2,5,4,3]

subtract like [2-3, 5-3, 4-3, 3-3, 5-2, 4-2, 3-2, 4-5, 3-5, 3-4] = [-1, 2, 1, 0, 3, 2, 1, -1, -2, 1]

output with values > 0, first 0 is from initialization [0, 2, 1, 3, 2, 1, 1]

Body:
using list comprehension

a=[3,2,5,4,3]
b= [j-a[i] for i,v in enumerate(a) for j in a[i+1:] if j-a[i]>0]

print(b)

output

 [2, 1, 3, 2, 1]


来源: stackexchange

问:
How to create a collapsing tree table in html/css/js?
I have some data to display that is both tabular and hierarchical. I'd like to let the user be able to expand and collapse the nodes.

Sort of like this, except functional:

http://www.maxdesign.com.au/articles/tree-table/

What would be the best way to approach this? I'm not adverse to using an off-the-shelf plugin.

答:
jquery is your friend here.

http://docs.jquery.com/UI/Tree

If you want to make your own, here is some high level guidance:

Display all of your data as
 elements with the inner data as nested
, and then use the jquery:

```<code>$('.ulClass').click(function(){ $(this).children().toggle(); });
</code>```

I believe that is correct.  Something like that.

EDIT:

Here is a complete example.

 $(".Collapsable").click(function () {

    $(this).parent().children().toggle();
    $(this).toggle();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li><span class="Collapsable">item 1</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span><ul>
            <li><span class="Collapsable">item 1</span></li>
            <li><span class="Collapsable">item 2</span></li>
            <li><span class="Collapsable">item 3</span></li>
            <li><span class="Collapsable">item 4</span></li>
        </ul>
        </li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span><ul>
            <li><span class="Collapsable">item 1</span></li>
            <li><span class="Collapsable">item 2</span></li>
            <li><span class="Collapsable">item 3</span></li>
            <li><span class="Collapsable">item 4</span></li>
        </ul>
        </li>
    </ul>
    </li>
    <li><span class="Collapsable">item 2</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span></li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span></li>
    </ul>
    </li>
    <li><span class="Collapsable">item 3</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span></li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span></li>
    </ul>
    </li>
    <li><span class="Collapsable">item 4</span></li>
</ul></code>```

ContentLicense: CC BY-SA 3.0

Body:
jquery is your friend here.

http://docs.jquery.com/UI/Tree

If you want to make your own, here is some high level guidance:

Display all of your data as <ul /> elements with the inner data as nested <ul />, and then use the jquery:

$('.ulClass').click(function(){ $(this).children().toggle(); });

I believe that is correct.  Something like that.

EDIT:

Here is a complete example.

 $(".Collapsable").click(function () {

    $(this).parent().children().toggle();
    $(this).toggle();

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li><span class="Collapsable">item 1</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span><ul>
            <li><span class="Collapsable">item 1</span></li>
            <li><span class="Collapsable">item 2</span></li>
            <li><span class="Collapsable">item 3</span></li>
            <li><span class="Collapsable">item 4</span></li>
        </ul>
        </li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span><ul>
            <li><span class="Collapsable">item 1</span></li>
            <li><span class="Collapsable">item 2</span></li>
            <li><span class="Collapsable">item 3</span></li>
            <li><span class="Collapsable">item 4</span></li>
        </ul>
        </li>
    </ul>
    </li>
    <li><span class="Collapsable">item 2</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span></li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span></li>
    </ul>
    </li>
    <li><span class="Collapsable">item 3</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span></li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span></li>
    </ul>
    </li>
    <li><span class="Collapsable">item 4</span></li>
</ul>

ContentLicense: CC BY-SA 4.0


问:
What's the bad magic number error?
What's the "Bad magic number" ImportError in python, and how do I fix it?

The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.

The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:

```<code>Traceback (most recent call last):
  File "run.py", line 7, in <module>
    from Normalization import Normalizer
</code>```

答:
You will need to run this command in every path you have in your environment.

```<code>>>> import sys
>>> sys.path
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/source_code/src/python', '/usr/lib/python3/dist-packages']

</code>```

Then run the command in every directory here

```<code>find /usr/lib/python3.6/ -name "*.pyc" -delete
find /usr/local/lib/python3.6/dist-packages -name "*.pyc" -delete
# etc...
</code>```

OwnerDisplayName: Noah

ContentLicense: CC BY-SA 2.5

Title: What's the bad magic number error?

Body:
What's the "Bad magic number" ImportError in python, and how do I fix it?

The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why.

The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps:

Traceback (most recent call last):
  File "run.py", line 7, in <module>
    from Normalization import Normalizer

LastEditorDisplayName: Noah

Body:
You will need to run this command in every path you have in your environment.

>>> import sys
>>> sys.path
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/source_code/src/python', '/usr/lib/python3/dist-packages']

Then run the command in every directory here

find /usr/lib/python3.6/ -name "*.pyc" -delete
find /usr/local/lib/python3.6/dist-packages -name "*.pyc" -delete
# etc...


问:
bootstrap4 dataTables search Option not working
I am using bootstrap4 dataTables to populate data from server. I have successfully populated data in table. But when I type value in search table, table become empty. I don't know why it is happening here is my code...

On load  I have used bellow code

```<code><script type="text/javascript">
  $(document).ready(function() {
    $('#tb_product_details').DataTable();
    getData();
  });
</script>
</code>```

I have populated data from server using bellow code

```<code>function getData() {
    $.ajax({
        type : "POST",
        url : "productDetails/getProductList",

        success : function(data) {

            var trHTML = '';
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                trHTML += '<tr>';
                trHTML += '<td>'+ item.slno + '</td>';
                trHTML += '<td>'+ item.productid + '</td>';
                trHTML += '<td>'+ item.name + '</td>';

                trHTML += '</tr>';
            }
            $('#tb_product_details tbody').append(trHTML);
        }
    })
}
</code>```

I have used bellow html table code..

```<code><table class="table table-bordered" id="tb_product_details" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>SL</th>
            <th>Product ID</th>
            <th>Product Name</th>
        </tr>
    </thead>
     <tbody>
      </tbody>
</table>
</code>```

Here is the datatables js

```<code><link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<script src=" https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</code>```

Here is a jsfiddle showing the current situation: https://jsfiddle.net/035adhcx/

Please help me to find out why search is not working....

答:
You're appending your data on tbody ($('#tb_product_details tbody').append(trHTML);) when there is actually no tbody set in your table, try adding the tbody tag manually and look if that fixes your issue, also try adding class="display" onto your table tag as shown here : https://datatables.net/manual/installation

UPDATE : you also populate your table after you call DataTable plugin, which is a no go as the plugin needs to have the proper table set before you load it, see this fiddle I made with the table demo provided in the documentation which works fine : https://jsfiddle.net/zn7gv3ux/

I think you should call DataTable in your success callback after you populated the data from your ajax request, that way you will make sure that your table is ready to be processed by the plugin.

So do it like so :

```<code><script type="text/javascript">
  $(document).ready(function() {
    getData();
  });
</script>

function getData() {
$.ajax({
    type : "POST",
    url : "productDetails/getProductList",

    success : function(data) {

        var trHTML = '';
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            trHTML += '<tr>';
            trHTML += '<td>'+ item.slno + '</td>';
            trHTML += '<td>'+ item.productid + '</td>';
            trHTML += '<td>'+ item.name + '</td>';

            trHTML += '</tr>';
        }
        $('#tb_product_details tbody').append(trHTML);
        $('#tb_product_details').DataTable(); //call the plugin here after appending datas
    }
})
}
</code>```

Snippet from GrafiCode Studio's jsfiddle who tested my solution :

$(document).ready(function() {
 var trHTML = '
1	1	1

2	2	2
';
 $('#tb_product_details tbody').append(trHTML);
 $('#tb_product_details').DataTable();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script
     src="https://code.jquery.com/jquery-3.4.1.min.js"
     integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
     crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table class="table table-bordered" id="tb_product_details" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>SL</th>
            <th>Product ID</th>
            <th>Product Name</th>
        </tr>
    </thead>
     <tbody>
      </tbody>
</table></code>```

Body:
I am using bootstrap4 dataTables to populate data from server. I have successfully populated data in table. But when I type value in search table, table become empty. I don't know why it is happening here is my code...

On load  I have used bellow code

I have populated data from server using bellow code

function getData() {
    $.ajax({
        type : "POST",
        url : "productDetails/getProductList",

        success : function(data) {

            var trHTML = '';
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                trHTML += '
';
                trHTML += ''+ item.slno + '	';
                trHTML += ''+ item.productid + '	';
                trHTML += ''+ item.name + '	';

                trHTML += '
';
            }
            $('#tb_product_details tbody').append(trHTML);
        }
    })
}

I have used bellow html table code..

            SL
            Product ID
            Product Name

Here is the datatables js

<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">

Here is a jsfiddle showing the current situation: https://jsfiddle.net/035adhcx/

Please help me to find out why search is not working....

Body:
You're appending your data on tbody ($('#tb_product_details tbody').append(trHTML);) when there is actually no tbody set in your table, try adding the tbody tag manually and look if that fixes your issue, also try adding class="display" onto your table tag as shown here : https://datatables.net/manual/installation

UPDATE : you also populate your table after you call DataTable plugin, which is a no go as the plugin needs to have the proper table set before you load it, see this fiddle I made with the table demo provided in the documentation which works fine : https://jsfiddle.net/zn7gv3ux/

I think you should call DataTable in your success callback after you populated the data from your ajax request, that way you will make sure that your table is ready to be processed by the plugin.

So do it like so :

<script type="text/javascript">
  $(document).ready(function() {
    getData();
  });
</script>

function getData() {
$.ajax({
    type : "POST",
    url : "productDetails/getProductList",

    success : function(data) {

        var trHTML = '';
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            trHTML += '<tr>';
            trHTML += '<td>'+ item.slno + '</td>';
            trHTML += '<td>'+ item.productid + '</td>';
            trHTML += '<td>'+ item.name + '</td>';

            trHTML += '</tr>';
        }
        $('#tb_product_details tbody').append(trHTML);
        $('#tb_product_details').DataTable(); //call the plugin here after appending datas
    }
})
}

Snippet from GrafiCode Studio's jsfiddle who tested my solution :

$(document).ready(function() {
 var trHTML = '<tr><td>1</td><td>1</td><td>1</td></tr><tr><td>2</td><td>2</td><td>2</td></tr>';
 $('#tb_product_details tbody').append(trHTML);
 $('#tb_product_details').DataTable();

});

<link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script
     src="https://code.jquery.com/jquery-3.4.1.min.js"
     integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
     crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table class="table table-bordered" id="tb_product_details" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>SL</th>
            <th>Product ID</th>
            <th>Product Name</th>
        </tr>
    </thead>
     <tbody>
      </tbody>
</table>


问:
Convert multiline bytestring, typed as string type to proper string
My log files have some multiline bytestring in them, like

[2019-05-25 19:16:31] b'logstring\r\n\r\nmore log'

After I try to extract the original multiline string, how do I convert that to a real string
using Python 3?

As a simplified example, after reading the log file and stripping the time, I end up with a variable that has the type str and has the b' prefix, as a string.

```<code># note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
# convert here
print(tmp)
</code>```

I'm looking for a way to tell python that the content needs to get decoded. But str doesn't allow decoding.

The result I'd like to see from the print command is

```<code>logstring
more log
</code>```

UPDATE: The "eval" function will produce this result, but this would execute the code, so it's not safe.

```<code># note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
tmp = eval(tmp)
print(tmp)
</code>```

Is there a better way?

答:
You can use regex:

```<code>import re
tmp =  "b'logstring\r\n\r\nmore log'"
r = re.compile(r"b'(.+)'", re.DOTALL|re.MULTILINE)
result = r.sub(r"\1", tmp)
print(result) # logstring\r\n\r\nmore log
</code>```

You could use this for the entire file or line by line but you may need to slightly change this code to meet your needs.

- Edit -

If you want to remove duplicate newlines (as your desired output shows) you can do it like this:

```<code>import re
tmp =  "b'logstring\r\n\r\nmore log'"
binary_regex = re.compile(r"b'(.+)'", re.DOTALL|re.MULTILINE)
newline_regex = re.compile(r"(\r\n)+", re.DOTALL|re.MULTILINE)
# Make sure to do the compiles outside of any loops you have
result = binary_regex.sub(r"\1", tmp) # Remove the b''
result = newline_regex.sub(r"\r\n", result) # Remove duplicate new lines
print(result)
</code>```

Output:

```<code>logstring
more log
</code>```

Body:
My log files have some multiline bytestring in them, like

[2019-05-25 19:16:31] b'logstring\r\n\r\nmore log'

After I try to extract the original multiline string, how do I convert that to a real string
using Python 3?

As a simplified example, after reading the log file and stripping the time, I end up with a variable that has the type str and has the b' prefix, as a string.

# note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
# convert here
print(tmp)

I'm looking for a way to tell python that the content needs to get decoded. But str doesn't allow decoding.

The result I'd like to see from the print command is

logstring
more log

UPDATE: The "eval" function will produce this result, but this would execute the code, so it's not safe.

# note: b'' is inside the str (taken from log)
tmp =  "b'logstring\r\n\r\nmore log'"
tmp = eval(tmp)
print(tmp)

Is there a better way?

Body:
You can use regex:

import re
tmp =  "b'logstring\r\n\r\nmore log'"
r = re.compile(r"b'(.+)'", re.DOTALL|re.MULTILINE)
result = r.sub(r"\1", tmp)
print(result) # logstring\r\n\r\nmore log

You could use this for the entire file or line by line but you may need to slightly change this code to meet your needs.

- Edit -

If you want to remove duplicate newlines (as your desired output shows) you can do it like this:

import re
tmp =  "b'logstring\r\n\r\nmore log'"
binary_regex = re.compile(r"b'(.+)'", re.DOTALL|re.MULTILINE)
newline_regex = re.compile(r"(\r\n)+", re.DOTALL|re.MULTILINE)
# Make sure to do the compiles outside of any loops you have
result = binary_regex.sub(r"\1", tmp) # Remove the b''
result = newline_regex.sub(r"\r\n", result) # Remove duplicate new lines
print(result)

Output:

logstring
more log


问:
MYSQL server running query very slow on 1 Million records
I am using MYSQL to manage book library data, here is my main table

```<code>CREATE TABLE `book` (
`id` int(11) NOT NULL,
`bookId` int(11) DEFAULT NULL,
`pageNum` smallint(6) DEFAULT NULL,
`pageData` longtext
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
</code>```

Now when I run this query

```<code>SELECT c.id, c.bookId,c.pageNum, c.pageData, o.BookName FROM book c  left
join kotarbooks o on c.bookId=o.BookId WHERE pageData like '%[Search Word]%'"
</code>```

It takes about 3 minutes

and when I run query

```<code>SELECT * FROM book WHERE bookid=[bookid] AND pageNum=[pageNumber]
</code>```

it takes about 2 minutes
Is there any idea to speed up these queries?
Thanks a lot

答:
The LIKE expression:

```<code>WHERE book.pageData LIKE '%[Search Word]%'
</code>```

is not sargable, and therefore any index on the book table likely would not be used by MySQL.  So, we can instead approach a strategy of a full table scan on the book table along with an index on the kotarbooks table:

```<code>CREATE INDEX kotaridx ON kotarabooks (BookId, BookName);
</code>```

The inclusion of the BookId column should help the join, and BookName covers this column, since it appears the select clause.

Body:
I am using MYSQL to manage book library data, here is my main table

CREATE TABLE `book` (
`id` int(11) NOT NULL,
`bookId` int(11) DEFAULT NULL,
`pageNum` smallint(6) DEFAULT NULL,
`pageData` longtext
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Now when I run this query

SELECT c.id, c.bookId,c.pageNum, c.pageData, o.BookName FROM book c  left
join kotarbooks o on c.bookId=o.BookId WHERE pageData like '%[Search Word]%'"

It takes about 3 minutes

and when I run query

SELECT * FROM book WHERE bookid=[bookid] AND pageNum=[pageNumber]

it takes about 2 minutes
Is there any idea to speed up these queries?
Thanks a lot

Body:
The LIKE expression:

WHERE book.pageData LIKE '%[Search Word]%'

is not sargable, and therefore any index on the book table likely would not be used by MySQL.  So, we can instead approach a strategy of a full table scan on the book table along with an index on the kotarbooks table:

CREATE INDEX kotaridx ON kotarabooks (BookId, BookName);

The inclusion of the BookId column should help the join, and BookName covers this column, since it appears the select clause.


问:
show georss feed on gmap
I am new to georss. i have my georss feed but i don't know how to check it on gmap.

Is there any way to check geoRss feed on google map.
(I work on php platform)

答: This post on the google maps api blog should pont you in the right direction - http://googlemapsapi.blogspot.com/2007/03/kml-and-georss-support-added-to-google.html  </p>

Title: show georss feed on gmap


问:
Calculating Percentages in Postgres
I'm completely new to PostgreSQL. I have the following table called my_table:

```<code>a    b    c        date
1    0    good     2019-05-02
0    1    good     2019-05-02
1    1    bad      2019-05-02
1    1    good     2019-05-02
1    0    bad      2019-05-01
0    1    good     2019-05-01
1    1    bad      2019-05-01
0    0    bad      2019-05-01
</code>```

I want to calculate the percentage of 'good' from column c for each date. I know how to get the number of 'good':

```<code>SELECT COUNT(c), date FROM my_table WHERE c != 'bad' GROUP BY date;
</code>```

That returns:

```<code>count    date
3        2019-05-02
1        2019-05-01
</code>```

My goal is to get this:

```<code>date         perc_good
2019-05-02   25
2019-05-01   75
</code>```

So I tried the following:

```<code>SELECT date,
       (SELECT COUNT(c)
        FROM my_table
        WHERE c != 'bad'
        GROUP BY date) / COUNT(c) * 100 as perc_good
FROM my_table
GROUP BY date;
</code>```

And I get an error saying

more than one row returned by a subquery used as an expression.

I found this answer but not sure how to or if it applies to my case:

Calculating percentage in PostgreSql

How do I go about calculating the percentage for multiple rows?

答:
avg() is convenient for this purpose:

```<code>select date,
       avg( (c = 'good')::int ) * 100 as percent_good
from t
group by date
order by date;
</code>```

How does this work?  c = 'good' is a boolean expression.  The ::int converts it to a number, with 1 for true and 0 for false.  The average is then the average of a bunch of 1s and 0s -- and is the ratio of the true values.

Title: Calculating Percentages in Postgres

Body:
I'm completely new to PostgreSQL. I have the following table called my_table:

a    b    c        date
1    0    good     2019-05-02
0    1    good     2019-05-02
1    1    bad      2019-05-02
1    1    good     2019-05-02
1    0    bad      2019-05-01
0    1    good     2019-05-01
1    1    bad      2019-05-01
0    0    bad      2019-05-01

I want to calculate the percentage of 'good' from column c for each date. I know how to get the number of 'good':

SELECT COUNT(c), date FROM my_table WHERE c != 'bad' GROUP BY date;

That returns:

count    date
3        2019-05-02
1        2019-05-01

My goal is to get this:

date         perc_good
2019-05-02   25
2019-05-01   75

So I tried the following:

SELECT date,
       (SELECT COUNT(c)
        FROM my_table
        WHERE c != 'bad'
        GROUP BY date) / COUNT(c) * 100 as perc_good
FROM my_table
GROUP BY date;

And I get an error saying

more than one row returned by a subquery used as an expression.

I found this answer but not sure how to or if it applies to my case:

Calculating percentage in PostgreSql

How do I go about calculating the percentage for multiple rows?

Body:
avg() is convenient for this purpose:

select date,
       avg( (c = 'good')::int ) * 100 as percent_good
from t
group by date
order by date;

How does this work?  c = 'good' is a boolean expression.  The ::int converts it to a number, with 1 for true and 0 for false.  The average is then the average of a bunch of 1s and 0s -- and is the ratio of the true values.


问:
Inherited Method using Child class object returns Parent Class variable
Parent and child class having same variable - "name," which has been accessed through inherited method - getName() in Parent Class

```<code>class A {
    String name = "A";
    String getName() {
        return name;
    }
    String greeting() {
        return "Class A";
    }
}

class B extends A {
    String name = "B";

    String greeting() {
        return "Class B";
    }
}

public class Client {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        System.out.println(a.greeting() + " has name " + a.getName());
        System.out.println(b.greeting() + " has name " + b.getName());
    }
}
</code>```

Output:

Class A has name A

  Class B has name A

In the above snippet, b.getName() returns the output as "A" though accessed using child class reference. Can someone pls explain this?

Note:
I have visited this link already - Overriding member variables in Java ( Variable Hiding), where in that link, the variable is accessed directly using the reference. In the given code snippet above, it has been accessed through the inherited method, which produced the output using the parent class variable, though called via the Child Class reference and Child Class Object.

答:
Reference - https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#d5e10238
Section - Example 8.3.1.1-3

Class B now has two variables,

String name = "A" --> from class A

String name = "B" --> from class B
(but this will hide the above one and can't be called directly)

Assume the below class references:

A a = new A();
B b = new B();```

String name = "A" can be obtained by: super.name or a.name or a.getName()

String name = "B" can be obtained by: b.name or overriding the method getName() in class B

With the given code snippet in question,

We are calling inherited method getName() from parent class A in class B

This inherited method is aware of the instance variable "name" in class A only

Hence it points to String name = "A" in class B, as class B contains both and the output is "A" here, though the class reference and object is of type 'B'

Body:
Parent and child class having same variable - "name," which has been accessed through inherited method - getName() in Parent Class

class A {
    String name = "A";
    String getName() {
        return name;
    }
    String greeting() {
        return "Class A";
    }
}

class B extends A {
    String name = "B";

    String greeting() {
        return "Class B";
    }
}

public class Client {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        System.out.println(a.greeting() + " has name " + a.getName());
        System.out.println(b.greeting() + " has name " + b.getName());
    }
}

Output:

Class A has name A

  Class B has name A

In the above snippet, b.getName() returns the output as "A" though accessed using child class reference. Can someone pls explain this?

Note:
I have visited this link already - Overriding member variables in Java ( Variable Hiding), where in that link, the variable is accessed directly using the reference. In the given code snippet above, it has been accessed through the inherited method, which produced the output using the parent class variable, though called via the Child Class reference and Child Class Object.

Body:
Reference - https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#d5e10238
Section - Example 8.3.1.1-3

Class B now has two variables,

String name = "A" --> from class A

String name = "B" --> from class B
(but this will hide the above one and can't be called directly)

Assume the below class references:

A a = new A();
B b = new B();

String name = "A" can be obtained by: super.name or a.name or a.getName()

String name = "B" can be obtained by: b.name or overriding the method getName() in class B

With the given code snippet in question,

We are calling inherited method getName() from parent class A in class B

This inherited method is aware of the instance variable "name" in class A only

Hence it points to String name = "A" in class B, as class B contains both and the output is "A" here, though the class reference and object is of type 'B'


问:
List directory contents of an S3 bucket using Python and Boto3?
I am trying to list all directories within an S3 bucket using Python and Boto3.

I am using the following code:

```<code>s3 = session.resource('s3')  # I already have a boto3 Session object
bucket_names = [
    'this/bucket/',
    'that/bucket/'
]
for name in bucket_names:
    bucket = s3.Bucket(name)
    for obj in bucket.objects.all():  # this raises an exception
        # handle obj
</code>```

When I run this I get the following exception stack trace:

```<code>File "botolist.py", line 67, in <module>
  for obj in bucket.objects.all():
File "/Library/Python/2.7/site-packages/boto3/resources/collection.py", line 82, in __iter__
  for page in self.pages():
File "/Library/Python/2.7/site-packages/boto3/resources/collection.py", line 165, in pages
  for page in pages:
File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 83, in __iter__
  response = self._make_request(current_kwargs)
File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 155, in _make_request
  return self._method(**current_kwargs)
File "/Library/Python/2.7/site-packages/botocore/client.py", line 270, in _api_call
  return self._make_api_call(operation_name, kwargs)
File "/Library/Python/2.7/site-packages/botocore/client.py", line 335, in _make_api_call
  raise ClientError(parsed_response, operation_name)

botocore.exceptions.ClientError: An error occurred (NoSuchKey) when calling the ListObjects operation: The specified key does not exist.
</code>```

What is the correct way to list directories inside a bucket?

答:
The best way to get the list of ALL objects with a specific prefix in a S3 bucket is using list_objects_v2 along with ContinuationToken to overcome the 1000 object pagination limit.

```<code>import boto3
s3 = boto3.client('s3')

s3_bucket = 'your-bucket'
s3_prefix = 'your/prefix'
partial_list = s3.list_objects_v2(
        Bucket=s3_bucket,
        Prefix=s3_prefix)
obj_list = partial_list['Contents']
while partial_list['IsTruncated']:
    next_token = partial_list['NextContinuationToken']
    partial_list = s3.list_objects_v2(
        Bucket=s3_bucket,
        Prefix=s3_prefix,
        ContinuationToken=next_token)
    obj_list.extend(partial_list['Contents'])
</code>```

Body:
I am trying to list all directories within an S3 bucket using Python and Boto3.

I am using the following code:

s3 = session.resource('s3')  # I already have a boto3 Session object
bucket_names = [
    'this/bucket/',
    'that/bucket/'
]
for name in bucket_names:
    bucket = s3.Bucket(name)
    for obj in bucket.objects.all():  # this raises an exception
        # handle obj

When I run this I get the following exception stack trace:

File "botolist.py", line 67, in <module>
  for obj in bucket.objects.all():
File "/Library/Python/2.7/site-packages/boto3/resources/collection.py", line 82, in __iter__
  for page in self.pages():
File "/Library/Python/2.7/site-packages/boto3/resources/collection.py", line 165, in pages
  for page in pages:
File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 83, in __iter__
  response = self._make_request(current_kwargs)
File "/Library/Python/2.7/site-packages/botocore/paginate.py", line 155, in _make_request
  return self._method(**current_kwargs)
File "/Library/Python/2.7/site-packages/botocore/client.py", line 270, in _api_call
  return self._make_api_call(operation_name, kwargs)
File "/Library/Python/2.7/site-packages/botocore/client.py", line 335, in _make_api_call
  raise ClientError(parsed_response, operation_name)

botocore.exceptions.ClientError: An error occurred (NoSuchKey) when calling the ListObjects operation: The specified key does not exist.

What is the correct way to list directories inside a bucket?

Body:
The best way to get the list of ALL objects with a specific prefix in a S3 bucket is using list_objects_v2 along with ContinuationToken to overcome the 1000 object pagination limit.

import boto3
s3 = boto3.client('s3')

s3_bucket = 'your-bucket'
s3_prefix = 'your/prefix'
partial_list = s3.list_objects_v2(
        Bucket=s3_bucket,
        Prefix=s3_prefix)
obj_list = partial_list['Contents']
while partial_list['IsTruncated']:
    next_token = partial_list['NextContinuationToken']
    partial_list = s3.list_objects_v2(
        Bucket=s3_bucket,
        Prefix=s3_prefix,
        ContinuationToken=next_token)
    obj_list.extend(partial_list['Contents'])


问:
Difference between two lists
I Have two generic list filled with CustomsObjects.

I need to retrieve the difference between those two lists(Items who are in the first without the items in the second one)  in a third one.

I was thinking using .Except() was a good idea but I don't see how to use this..
Help!

答:
If both your lists implement IEnumerable interface you can achieve this using LINQ.</p>

```<code>list3 = list1.where(i => !list2.contains(i));
</code>```

Title: Difference between two lists

Body:
If both your lists implement IEnumerable interface you can achieve this using LINQ.

list3 = list1.where(i => !list2.contains(i));


问:
Spring Cloud Config client doesn't get values from server
I have been following this tutorial from Baeldung in setting up a Spring Cloud Config server and client. I believe I have set up the server correctly since going to http://localhost:8888/service-config/development/master will seemingly correctly show the json with the user.role defined:

```<code>{"name":"service-config","profiles":["development"],"label":"master","version":"d30a6015a6b8cb1925f6e61cee22721f331e5783","state":null,"propertySources":[{"name":"file:///C:.../git/service-config-data/service-config-development.properties","source":{"user.role":"Developer"}},{"name":"file:///C:.../git/service-config-data/service-config.properties","source":{"user.role":"Developer"}}]}
</code>```

However, I cannot seem to correctly connect the Spring Cloud Config client to the server - the client fails to run with cannot resolve placeholder errors on the @Value("${user.role}") annotation. I've tried adding a default value to the annotation and then manually refreshing the values (using the @refreshscope annotation), but to no avail.

I've looked at the debug and trace logs by running the tools with --debug --trace flags but I cannot find when/if the client is making the call to the server and which config-data .properties file the server is actually looking for. I am a bit lost on how to proceed.

Here is my server application.properties:

```<code>spring.application.name=service-config
server.port=8888
spring.cloud.config.server.git.uri=file:///${user.home}/git/service-config-data
spring.cloud.config.server.git.clone-on-start=false
spring.security.user.name=root
spring.security.user.password=toor
</code>```

And inside the service-config-data folder, there are files with this inside:

```<code>user.role=Developer
</code>```

I have tried files called service-config.properties, service-config-client.properties, service-config-development.properties, and service-config-client-development.properties, and none of them seem to pull through the user.role.

Here is my client:

```<code>@SpringBootApplication
@RestController
@RefreshScope
public class ServiceConfigClient {

    @Value("${user.role:unknown}")
    private String role;

    @RequestMapping(
      value = "/whoami/{username}",
      method = RequestMethod.GET,
      produces = MediaType.TEXT_PLAIN_VALUE)
    public String whoami(@PathVariable("username") String username) {
        return String.format("Hello! You're %s and you'll become a(n) %s...\n", username, role);
    }
}
</code>```

And my client bootstrap.properties:

```<code>spring.application.name=service-config-client
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:8888
spring.cloud.config.username=root
spring.cloud.config.password=toor

management.endpoints.web.exposure.include=*
</code>```

How do I correctly connect the client to the server so that it can successfully pull the config data? Thank you.

答:
There is confusion about client service name and corresponding property sources in config server.

You need to do one of the following:

Change client service name:

```<code>//client bootstrap.properties
spring.application.name=service-config
</code>```

Change folder name in git repo from service-config to service-config-client

Body:
I have been following this tutorial from Baeldung in setting up a Spring Cloud Config server and client. I believe I have set up the server correctly since going to http://localhost:8888/service-config/development/master will seemingly correctly show the json with the user.role defined:

{"name":"service-config","profiles":["development"],"label":"master","version":"d30a6015a6b8cb1925f6e61cee22721f331e5783","state":null,"propertySources":[{"name":"file:///C:.../git/service-config-data/service-config-development.properties","source":{"user.role":"Developer"}},{"name":"file:///C:.../git/service-config-data/service-config.properties","source":{"user.role":"Developer"}}]}

However, I cannot seem to correctly connect the Spring Cloud Config client to the server - the client fails to run with cannot resolve placeholder errors on the @Value("${user.role}") annotation. I've tried adding a default value to the annotation and then manually refreshing the values (using the @refreshscope annotation), but to no avail.

I've looked at the debug and trace logs by running the tools with --debug --trace flags but I cannot find when/if the client is making the call to the server and which config-data .properties file the server is actually looking for. I am a bit lost on how to proceed.

Here is my server application.properties:

spring.application.name=service-config
server.port=8888
spring.cloud.config.server.git.uri=file:///${user.home}/git/service-config-data
spring.cloud.config.server.git.clone-on-start=false
spring.security.user.name=root
spring.security.user.password=toor

And inside the service-config-data folder, there are files with this inside:

user.role=Developer

I have tried files called service-config.properties, service-config-client.properties, service-config-development.properties, and service-config-client-development.properties, and none of them seem to pull through the user.role.

Here is my client:

@SpringBootApplication
@RestController
@RefreshScope
public class ServiceConfigClient {

    @Value("${user.role:unknown}")
    private String role;

    @RequestMapping(
      value = "/whoami/{username}",
      method = RequestMethod.GET,
      produces = MediaType.TEXT_PLAIN_VALUE)
    public String whoami(@PathVariable("username") String username) {
        return String.format("Hello! You're %s and you'll become a(n) %s...\n", username, role);
    }
}

And my client bootstrap.properties:

spring.application.name=service-config-client
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:8888
spring.cloud.config.username=root
spring.cloud.config.password=toor

management.endpoints.web.exposure.include=*

How do I correctly connect the client to the server so that it can successfully pull the config data? Thank you.

Body:
There is confusion about client service name and corresponding property sources in config server.

You need to do one of the following:

Change client service name:

//client bootstrap.properties
spring.application.name=service-config

Change folder name in git repo from service-config to service-config-client


问:
AWS API Gateway integration with Socket.io
I want to map an API Gateway endpoint with a Socket.io server endpoint, in order to authenticate users through Cognito and, if successful, redirect to the Socket.io server and establish a socket with optional namespace and rooms.

Is that makes sense? I didn't found any example, and API Gateway has only recently enabled a WebSocket API but without support for Socket.io

答:
Your question has two parts:

First, the API Gateway using Cognito to authenticate your client;

Second, assuming you are using an EC2 running Node.JS with Socket.IO using API Gateway as an endpoint for your clients.

For the First part, you may use the following reference from AWS documentation.
There are several sub-parts when you talk about AWS Cognito, for example including AIM permissions Method Execution to enable API resource endpoint HTTP method.

For the second point, enable API Gateway to establish a synchronous connection with EC2 port running Socket.io you may read some references like this one.
You should configure your API Gateway:

Protocol WebSocket connection

Select your Route Selection expression ,e.g. \$default

Map the target backend for each $connect, $disconnect and $default

Use integration type AWS Service

Select EC2 and fill the rest of configs.


问:
Receive text message using J2ME
I am trying to make a J2ME application to SEND and RECEIVE text messages. I'm done with the sending part of it but I am not able to receive any message..

Below is what I tried in order to receive text message;

```<code>    try {
        MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
        conn.setMessageListener(new MessageListener() {
            public void notifyIncomingMessage(MessageConnection conn) {
                try {
                    Message msg;
                    msg = conn.receive();
                    if (msg instanceof TextMessage) {
                        TextMessage tmsg = (TextMessage) msg;
                        stringItem.setText("Msg: " + tmsg.getPayloadText());
                        System.out.println(tmsg.getPayloadText());
                    }
                    // else if(msg instanceof BinaryMessage) {
                    // .....
                    // } else {
                    // ......
                    // }
                } catch (IOException ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        conn.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    } catch (Exception e1) {
        System.out.println(e1);
    }
</code>```

But this is not working...No errors are showing up either...what is that I am doing wrong?...Can we receive message using J2ME?

The code for sending a message: (UPDATED)

```<code>MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setPayloadText(message);
tmsg.setAddress("sms://" + number);
conn.send();
</code>```

I have both the send and receive functions in two different forms. What I did is to install and start the application in two different mobiles, send a message from one mobile to the other and receive in the other.

The message is sent and received successfully, but not in the application. The message goes to the inbox of the other mobile.

What can I do?

答: Try replacing tmsg.setAddress("sms://" + number); with tmsg.setAddress("sms://" + number + ":50001");.

Title: Receive text message using J2ME

Body:
I am trying to make a J2ME application to SEND and RECEIVE text messages. I'm done with the sending part of it but I am not able to receive any message..

Below is what I tried in order to receive text message;

    try {
        MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
        conn.setMessageListener(new MessageListener() {
            public void notifyIncomingMessage(MessageConnection conn) {
                try {
                    Message msg;
                    msg = conn.receive();
                    if (msg instanceof TextMessage) {
                        TextMessage tmsg = (TextMessage) msg;
                        stringItem.setText("Msg: " + tmsg.getPayloadText());
                        System.out.println(tmsg.getPayloadText());
                    }
                    // else if(msg instanceof BinaryMessage) {
                    // .....
                    // } else {
                    // ......
                    // }
                } catch (IOException ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        conn.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    } catch (Exception e1) {
        System.out.println(e1);
    }

But this is not working...No errors are showing up either...what is that I am doing wrong?...Can we receive message using J2ME?

The code for sending a message: (UPDATED)

MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setPayloadText(message);
tmsg.setAddress("sms://" + number);
conn.send();

I have both the send and receive functions in two different forms. What I did is to install and start the application in two different mobiles, send a message from one mobile to the other and receive in the other.

The message is sent and received successfully, but not in the application. The message goes to the inbox of the other mobile.

What can I do?


问:
Re-plotting contour filled plot using a PatchCollection
I am trying to display a filled contour plot using the collection coming from an original other contourplot. However, I am missing something as my code does not exactly reproduce the contour plot.

Minimal code I am working on:

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection, PolyCollection

x = np.arange(0, 300,1)
y = np.arange(0, 300,1)
X, Y = np.meshgrid(y, x)
Topo = np.cos(X*2*np.pi/50)*np.sin(Y*2*np.pi/200)*y

plt.figure()
ax = plt.subplot(1,2,1)
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
ax.set_xticks([])
ax.set_yticks([])

Ncolors = 50
levels = np.linspace(np.min(Topo),np.max(Topo),Ncolors)
# h = plt.contourf(X,Y, Topo, levels = levels, cmap = cmap, vmin = 0.85*np.min(Topo), zorder = -10)
h = plt.contourf(Y, X, Topo, levels = levels)

ax = plt.subplot(1,2,2)
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
ax.set_xticks([])
ax.set_yticks([])

i = 0
for levellines in h.collections:
    for lines in levellines.get_paths():
        plt.gca().add_collection(PatchCollection( [ Polygon( lines.vertices ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )
    i = i+1
plt.xlim([x.min(), x.max()])
plt.ylim([y.min(), y.max()])
</code>```

As you may ask why I am trying to passe thourgh a the Polygon function and the path vertices: later, I will need to change a little bit the coordinates of the vertices lines.vertices to make some projections, changing view points, etc ..

Note that the result highly depend on the plotted surface .. Sometimes no artefact appear, sometimes it is much worse than this.

答:
I managed to found the problem. The artefacts appear when the paths contained in lines are not simple paths, but bezier curves or others.

Therfore, you need to plot paths instead of polygons to add this information contained in the codes attribute.

Juste use :

```<code>from matplotlib.path import Path
import matplotlib.patches as patches
</code>```

and then :

```<code>plt.gca().add_patch(patches.PathPatch( Path(lines.vertices, lines.codes) , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )
</code>```

instead of

```<code> plt.gca().add_collection(PatchCollection( [ Polygon( lines.vertices ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )
</code>```

Finally, you can also convert the paths to Polygons using .to_polygons():

```<code> plt.gca().add_collection(PatchCollection( [ Polygon( lines.to_polygons() ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )
</code>```

Body:
I am trying to display a filled contour plot using the collection coming from an original other contourplot. However, I am missing something as my code does not exactly reproduce the contour plot.

Minimal code I am working on:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection, PolyCollection

x = np.arange(0, 300,1)
y = np.arange(0, 300,1)
X, Y = np.meshgrid(y, x)
Topo = np.cos(X*2*np.pi/50)*np.sin(Y*2*np.pi/200)*y

plt.figure()
ax = plt.subplot(1,2,1)
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
ax.set_xticks([])
ax.set_yticks([])

Ncolors = 50
levels = np.linspace(np.min(Topo),np.max(Topo),Ncolors)
# h = plt.contourf(X,Y, Topo, levels = levels, cmap = cmap, vmin = 0.85*np.min(Topo), zorder = -10)
h = plt.contourf(Y, X, Topo, levels = levels)

ax = plt.subplot(1,2,2)
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
ax.set_xticks([])
ax.set_yticks([])

i = 0
for levellines in h.collections:
    for lines in levellines.get_paths():
        plt.gca().add_collection(PatchCollection( [ Polygon( lines.vertices ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )
    i = i+1
plt.xlim([x.min(), x.max()])
plt.ylim([y.min(), y.max()])

As you may ask why I am trying to passe thourgh a the Polygon function and the path vertices: later, I will need to change a little bit the coordinates of the vertices lines.vertices to make some projections, changing view points, etc ..

Note that the result highly depend on the plotted surface .. Sometimes no artefact appear, sometimes it is much worse than this.

Body:
I managed to found the problem. The artefacts appear when the paths contained in lines are not simple paths, but bezier curves or others.

Therfore, you need to plot paths instead of polygons to add this information contained in the codes attribute.

Juste use :

from matplotlib.path import Path
import matplotlib.patches as patches

and then :

plt.gca().add_patch(patches.PathPatch( Path(lines.vertices, lines.codes) , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )

instead of

 plt.gca().add_collection(PatchCollection( [ Polygon( lines.vertices ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )

Finally, you can also convert the paths to Polygons using .to_polygons():

 plt.gca().add_collection(PatchCollection( [ Polygon( lines.to_polygons() ) ] , facecolor = levellines.get_facecolor()[0], edgecolor = levellines.get_facecolor()[0]) )


问:
Separate columns by their strings if they are different
I have a data frame, and I want to spli their columns if they contain different strings or words.

I am tryng different methods in R and it is not working

My data frame looks like this:

```<code>df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2", "TAP2", "TAP3" ))
</code>```

And, for example, I am trying with the first column this:

```<code>df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"))
df %>% separate(x, c("TAP1", "TAP2"), extra = "drop", fill = "right")
</code>```

but is not working

I am having the next output:

```<code>TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 TAP2 <NA>
</code>```

My expected output is:

```<code> TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 <NA> TAP2
</code>```

And I would like to do the same for all columns in the complete data frame where I have different combinations of words like TAP1, TAP2, TAP3 ... etc.

In this example, the final table taking in to account column x and y would be.

```<code> df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2",   "TAP2", "TAP3" ))

  TAP1 TAP2 TAP1.1 TAP2.2 TAP3.3
1 <NA> <NA> TAP1   <NA>   <NA>
2 TAP1 <NA> <NA>   TAP2   <NA>
3 TAP1 <NA> <NA>   TAP2   <NA>
4 <NA> TAP2 <NA>   <NA>   TAP3
</code>```

答:
A solution using the tidyverse and the dummies package. df3 is the final output.

```<code>library(tidyverse)
library(dummies)

df2 <- dummy.data.frame(df) %>% select(-ends_with("NA"))

cols <- str_remove(names(df2), regex("^x|^y"))

df3 <- modify2(df2, cols, ~ifelse(.x == 0, NA, .y))

df3
#   xTAP1 xTAP2 yTAP1 yTAP2 yTAP3
# 1  <NA>  <NA>  TAP1  <NA>  <NA>
# 2  TAP1  <NA>  <NA>  TAP2  <NA>
# 3  TAP1  <NA>  <NA>  TAP2  <NA>
# 4  <NA>  TAP2  <NA>  <NA>  TAP3
</code>```

Body:
I have a data frame, and I want to spli their columns if they contain different strings or words.

I am tryng different methods in R and it is not working

My data frame looks like this:

df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2", "TAP2", "TAP3" ))

And, for example, I am trying with the first column this:

df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"))
df %>% separate(x, c("TAP1", "TAP2"), extra = "drop", fill = "right")

but is not working

I am having the next output:

TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 TAP2 <NA>

My expected output is:

 TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 <NA> TAP2

And I would like to do the same for all columns in the complete data frame where I have different combinations of words like TAP1, TAP2, TAP3 ... etc.

In this example, the final table taking in to account column x and y would be.

 df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2",   "TAP2", "TAP3" ))

  TAP1 TAP2 TAP1.1 TAP2.2 TAP3.3
1 <NA> <NA> TAP1   <NA>   <NA>
2 TAP1 <NA> <NA>   TAP2   <NA>
3 TAP1 <NA> <NA>   TAP2   <NA>
4 <NA> TAP2 <NA>   <NA>   TAP3

Body:
A solution using the tidyverse and the dummies package. df3 is the final output.

library(tidyverse)
library(dummies)

df2 <- dummy.data.frame(df) %>% select(-ends_with("NA"))

cols <- str_remove(names(df2), regex("^x|^y"))

df3 <- modify2(df2, cols, ~ifelse(.x == 0, NA, .y))

df3
#   xTAP1 xTAP2 yTAP1 yTAP2 yTAP3
# 1  <NA>  <NA>  TAP1  <NA>  <NA>
# 2  TAP1  <NA>  <NA>  TAP2  <NA>
# 3  TAP1  <NA>  <NA>  TAP2  <NA>
# 4  <NA>  TAP2  <NA>  <NA>  TAP3


答:
For this case you need to use conditional AVG():

```<code>SELECT
  date,
  100 * avg(case when c = 'good' then 1 else 0 end) perc_good
FROM my_table
GROUP BY date;
</code>```

See the demo.

Title: Calculating Percentages in Postgres

Body:
For this case you need to use conditional AVG():

SELECT
  date,
  100 * avg(case when c = 'good' then 1 else 0 end) perc_good
FROM my_table
GROUP BY date;

See the demo.


问:
Get unique parent elements from array using Typescript
I have this structure on my angular project:

```<code>export interface Campo {
  id?: number;
  nome?: string;
  tabela?: Tabela;
  campos?: Campo[];
}

export interface Tabela {
  id?: number;
  name?: string
  arquivo?: Arquivo;
}

export interface Arquivo {
  id?: number;
  name?: string;
  tabelas?: Tabela[];
}
</code>```

i.e., An "Arquivo" has many "Tabela", and "Tabela" has many "Campo". I subscribe on a service that return all "Campo" and I keep it on "campos" variable. This service return more than 200 "Campos", associated with about 10 "Tabelas" and only 3 "Arquivos".

I want to return all unique "Arquivo" (i.e. all 3 "Arquivo").

When I do:

```<code>let arquivos = this.campos
        .map(campo => campo.tabela.arquivo.id)
        .filter((value, index, self) => self.indexOf(value) === index);
</code>```

It returns

[1001, 1002, 1003]

So it is the ids of all 3 "Arquivo" that I have. But I dont want the ids, I want the "Arquivo" objects. When I try:

```<code>let arquivos = this.campos
        .map(campo => campo.tabela.arquivo)
        .filter((value, index, self) => self.indexOf(value) === index);
</code>```

It returns more than 200 registers, because I have more than 200 "Campos" and it can't know what "Arquivos" is unique or not.

How can I do that?

答:
You could try mapping the unique arquivo ids to the arquivo objects, and then, get the values</p>

```<code>let arquivos = Object.values(this.campos
  .map(campo => campo.tabela.arquivo)
  .reduce((totals, arquivo) => {
    if (!totals[arquivo.id]) {
      totals[arquivo.id] = arquivo;
    }
    return totals;
  }, {})
);
</code>```

Body:
I have this structure on my angular project:

export interface Campo {
  id?: number;
  nome?: string;
  tabela?: Tabela;
  campos?: Campo[];
}

export interface Tabela {
  id?: number;
  name?: string
  arquivo?: Arquivo;
}

export interface Arquivo {
  id?: number;
  name?: string;
  tabelas?: Tabela[];
}

i.e., An "Arquivo" has many "Tabela", and "Tabela" has many "Campo". I subscribe on a service that return all "Campo" and I keep it on "campos" variable. This service return more than 200 "Campos", associated with about 10 "Tabelas" and only 3 "Arquivos".

I want to return all unique "Arquivo" (i.e. all 3 "Arquivo").

When I do:

let arquivos = this.campos
        .map(campo => campo.tabela.arquivo.id)
        .filter((value, index, self) => self.indexOf(value) === index);

It returns

[1001, 1002, 1003]

So it is the ids of all 3 "Arquivo" that I have. But I dont want the ids, I want the "Arquivo" objects. When I try:

let arquivos = this.campos
        .map(campo => campo.tabela.arquivo)
        .filter((value, index, self) => self.indexOf(value) === index);

It returns more than 200 registers, because I have more than 200 "Campos" and it can't know what "Arquivos" is unique or not.

How can I do that?

Body:
You could try mapping the unique arquivo ids to the arquivo objects, and then, get the values

let arquivos = Object.values(this.campos
  .map(campo => campo.tabela.arquivo)
  .reduce((totals, arquivo) => {
    if (!totals[arquivo.id]) {
      totals[arquivo.id] = arquivo;
    }
    return totals;
  }, {})
);


问:
How to deleting and recursing images?
I made the image move from right to left.
But i wanna plus function that when image reach at x : 50, this image deleted
and to draw left.

I tried to using  control statement like "if" but it's not working

```<code>var canvas = document.getElementById("Canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.src = "img1.png";
var speed = 0;
var xpos = 800;
var CXpos = 0;  //changeing xpos
var result = Math.floor(Math.random() * 500) + 1;

function icon(){
    ctx.beginPath();
    speed -= 1;
    CXpos = xpos + speed;
    ctx.drawImage(img, CXpos, result, 60, 60);
    if(Cxpos == 50){
        canvas.width = canvas.width;    //I don't know it's correct code?
        icon();
    }
    ctx.closePath();
}

function iconypos(){
    var num = Math.floor(Math.random*100)+1
    return num;
}

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    icon();
}

setInterval(draw, 10);
</code>```

答:
If I understand you correctly, this is what you're looking for. Just "reset" the speed var to the starting point (which is 0).

No need to call to icon() again because the next tick in the interval will call this anyway.

var canvas = document.getElementById("Canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.src = "https://avatars2.githubusercontent.com/u/15933454?s=60&v=4";
var speed = 0;
var xpos = 800;
var CXpos = 0;  //changeing xpos
var result = Math.floor(Math.random() * 500) + 1;

function icon(){
    ctx.beginPath();
    speed -= 1;
    CXpos = xpos + speed;
    ctx.drawImage(img, CXpos, result, 60, 60);
    if(CXpos == 50){
        speed = 0;    //I don't know it's correct code?
        //icon();
    }
    ctx.closePath();
}

function iconypos(){
    var num = Math.floor(Math.random*100)+1
    return num;
}

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    icon();
}

setInterval(draw, 10);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="Canvas" width="800" height="350"></canvas></code>```

Title: How to deleting and recursing images?

Body:
I made the image move from right to left.
But i wanna plus function that when image reach at x : 50, this image deleted
and to draw left.

I tried to using  control statement like "if" but it's not working

var canvas = document.getElementById("Canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.src = "img1.png";
var speed = 0;
var xpos = 800;
var CXpos = 0;  //changeing xpos
var result = Math.floor(Math.random() * 500) + 1;

function icon(){
    ctx.beginPath();
    speed -= 1;
    CXpos = xpos + speed;
    ctx.drawImage(img, CXpos, result, 60, 60);
    if(Cxpos == 50){
        canvas.width = canvas.width;    //I don't know it's correct code?
        icon();
    }
    ctx.closePath();
}

function iconypos(){
    var num = Math.floor(Math.random*100)+1
    return num;
}

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    icon();
}

setInterval(draw, 10);

Body:
If I understand you correctly, this is what you're looking for. Just "reset" the speed var to the starting point (which is 0).

No need to call to icon() again because the next tick in the interval will call this anyway.

var canvas = document.getElementById("Canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.src = "https://avatars2.githubusercontent.com/u/15933454?s=60&v=4";
var speed = 0;
var xpos = 800;
var CXpos = 0;  //changeing xpos
var result = Math.floor(Math.random() * 500) + 1;

function icon(){
    ctx.beginPath();
    speed -= 1;
    CXpos = xpos + speed;
    ctx.drawImage(img, CXpos, result, 60, 60);
    if(CXpos == 50){
        speed = 0;    //I don't know it's correct code?
        //icon();
    }
    ctx.closePath();
}

function iconypos(){
    var num = Math.floor(Math.random*100)+1
    return num;
}

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    icon();
}

setInterval(draw, 10);

<canvas id="Canvas" width="800" height="350"></canvas>


问:
How to get RAR files volume index using 7-zip commands (or any alternative solutions)
I have some files (207 RAR files downloaded), and they don't have a proper name to refer each part/index, and if I want to extract them I should name them manually by checking volume index (from Properties section), and as you notice that can be too time-consuming

I thought that I might do it using a batch or a python script, so the first thing I needed to do is to get the volume index from CMD "7z i FileName.rar", but I couldn't find the volume index number (or maybe HEX) from the output
Am I using the wrong command?
Or maybe it is printed but I can't find it?

I attach one of RAR files output (Volume index is 18 [It is 19th part])
https://www.pastiebin.com/5cee55060c642

I would be thankful if you can help me.

答:
You should be able to accomplish this with the l (list) command.

Here is a simple Windows command:

```<code>for %a in (*.rar) do @ECHO %a & "C:\Program Files\7-Zip\7z.exe" l %a | FIND "Index" & ECHO.
</code>```

Here is the batch file version (%% instead of %):

```<code>@ECHO off
for %%a in (*.rar) do ECHO %%a & "C:\Program Files\7-Zip\7z.exe" l %%a | FIND "Index" & ECHO.
</code>```

This will echo the filename and the "Volume Index" field from the output of the l (list) command for that file like the example below:

```<code>myFile.part1.rar
Volume Index = 0

myFile.part2.rar
Volume Index = 1

myFile.part3.rar
Volume Index = 2
</code>```

To rename all of the files in order, you can use the following batch file.

Warning This will affect all files in the directory it's run in and the original file names will be lost.

```<code>@ECHO off

SET PATH=%PATH%;C:\Program Files\7-Zip\
for %%a in (*) do CALL:Index "%%~a"
GOTO:EOF

:Index
ECHO %~1
SETLOCAL EnableDelayedExpansion
for /f "tokens=3 delims== " %%a in ('7z.exe l "%~1" ^| FIND "Index"') do CALL:Rename "%~1" %%a
ENDLOCAL
GOTO:EOF

:Rename
SET /A Index=%2+1
REN "%~1" file%Index%.rar
</code>```

Body:
You should be able to accomplish this with the l (list) command.

Here is a simple Windows command:

for %a in (*.rar) do @ECHO %a & "C:\Program Files\7-Zip\7z.exe" l %a | FIND "Index" & ECHO.

Here is the batch file version (%% instead of %):

@ECHO off
for %%a in (*.rar) do ECHO %%a & "C:\Program Files\7-Zip\7z.exe" l %%a | FIND "Index" & ECHO.

This will echo the filename and the "Volume Index" field from the output of the l (list) command for that file like the example below:

myFile.part1.rar
Volume Index = 0

myFile.part2.rar
Volume Index = 1

myFile.part3.rar
Volume Index = 2

To rename all of the files in order, you can use the following batch file.

Warning This will affect all files in the directory it's run in and the original file names will be lost.

@ECHO off

SET PATH=%PATH%;C:\Program Files\7-Zip\
for %%a in (*) do CALL:Index "%%~a"
GOTO:EOF

:Index
ECHO %~1
SETLOCAL EnableDelayedExpansion
for /f "tokens=3 delims== " %%a in ('7z.exe l "%~1" ^| FIND "Index"') do CALL:Rename "%~1" %%a
ENDLOCAL
GOTO:EOF

:Rename
SET /A Index=%2+1
REN "%~1" file%Index%.rar


问:
JavaFX Controlsfx library Check-ComboBox autocomplete
I have check-combo box I have taken it from controlsFX library which has more than 80 items in it. How can I write check-Combobox autocomplete logic? As while selecting items from CheckComboBox I need to scroll down and search item manually. I want a search option for it.</p>

答: The check-combobox control is not editable and as such you cannot make it auto complete. Use combobox and set the cellFactory, extend ListCell and add checkbox </p>


问:
jQuery DataTables: Delay search until 3 characters been typed OR a button clicked
Is there please an option to start the search only after 3 characters have been typed in?

I have written a PHP-script for colleagues displaying 20,000 entries and they complain, that when typing a word, the first few letters cause everything to freeze.

An alternative would be to have the search to be started by a button clicked and not by character typing.

Below is my current code:

```<code>$("#my_table").dataTable( {
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bAutoWidth": false,
        "aoColumns": [
                /* qdatetime */   { "bSearchable": false },
                /* id */          null,
                /* name */        null,
                /* category */    null,
                /* appsversion */ null,
                /* osversion */   null,
                /* details */     { "bVisible": false },
                /* devinfo */     { "bVisible": false, "bSortable": false }
        ],
        "oLanguage": {
                "sProcessing":   "Wait please...",
                "sZeroRecords":  "No ids found.",
                "sInfo":         "Ids from _START_ to _END_ of _TOTAL_ total",
                "sInfoEmpty":    "Ids from 0 to 0 of 0 total",
                "sInfoFiltered": "(filtered from _MAX_ total)",
                "sInfoPostFix":  "",
                "sSearch":       "Search:",
                "sUrl":          "",
                "oPaginate": {
                        "sFirst":    "<<",
                        "sLast":     ">>",
                        "sNext":     ">",
                        "sPrevious": "<"
                },
                "sLengthMenu": 'Display <select>' +
                        '<option value="10">10</option>' +
                        '<option value="20">20</option>' +
                        '<option value="50">50</option>' +
                        '<option value="100">100</option>' +
                        '<option value="-1">all</option>' +
                        '</select> ids'
        }
} );
</code>```

答:
Is there a reason you wouldn't just check length on 'change'?</p>

```<code>$('.input').change(function() {
  if( $('.input').length > 3 ) {
     //do the search
  }
});
</code>```

Body:
Is there please an option to start the search only after 3 characters have been typed in?

I have written a PHP-script for colleagues displaying 20,000 entries and they complain, that when typing a word, the first few letters cause everything to freeze.

An alternative would be to have the search to be started by a button clicked and not by character typing.

Below is my current code:

$("#my_table").dataTable( {
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bAutoWidth": false,
        "aoColumns": [
                /* qdatetime */   { "bSearchable": false },
                /* id */          null,
                /* name */        null,
                /* category */    null,
                /* appsversion */ null,
                /* osversion */   null,
                /* details */     { "bVisible": false },
                /* devinfo */     { "bVisible": false, "bSortable": false }
        ],
        "oLanguage": {
                "sProcessing":   "Wait please...",
                "sZeroRecords":  "No ids found.",
                "sInfo":         "Ids from _START_ to _END_ of _TOTAL_ total",
                "sInfoEmpty":    "Ids from 0 to 0 of 0 total",
                "sInfoFiltered": "(filtered from _MAX_ total)",
                "sInfoPostFix":  "",
                "sSearch":       "Search:",
                "sUrl":          "",
                "oPaginate": {
                        "sFirst":    "<<",
                        "sLast":     ">>",
                        "sNext":     ">",
                        "sPrevious": "<"
                },
                "sLengthMenu": 'Display <select>' +
                        '<option value="10">10</option>' +
                        '<option value="20">20</option>' +
                        '<option value="50">50</option>' +
                        '<option value="100">100</option>' +
                        '<option value="-1">all</option>' +
                        '</select> ids'
        }
} );

Body:
Is there a reason you wouldn't just check length on 'change'?

$('.input').change(function() {
  if( $('.input').length > 3 ) {
     //do the search
  }
});


问:
one echo command appending 1 message to 2 different lines
Im trying to echo a line in a for loop ,something like this.

```<code>echo "IP=$p some message $l" >> /dir/file
</code>```

the problem is that its coming out like this

```<code>IP=ipadress
some message loutput
</code>```

the p variable is coming from a for p in ... and the l variable is equal to a line coming from a tail command
i think its due to the variable substitution in $p , but im not sure.
i want all of it to come out in just one line, what am i doing wrong?

```<code>for p in $(cat /home/ips)
do
</code>```

答:
Try this:

```<code>echo "IP="$p" some message "$l >> /dir/file
</code>```

I suggest this because, for example:

```<code>temp=$(ls -1)
echo $temp
</code>```

gives:

```<code>file0 file1
</code>```

But

```<code>echo "$temp"
</code>```

gives:

```<code>file0
file1
</code>```

Body:
Im trying to echo a line in a for loop ,something like this.

echo "IP=$p some message $l" >> /dir/file

the problem is that its coming out like this

IP=ipadress
some message loutput

the p variable is coming from a for p in ... and the l variable is equal to a line coming from a tail command
i think its due to the variable substitution in $p , but im not sure.
i want all of it to come out in just one line, what am i doing wrong?

for p in $(cat /home/ips)
do

Body:
Try this:

echo "IP="$p" some message "$l >> /dir/file

I suggest this because, for example:

temp=$(ls -1)
echo $temp

gives:

file0 file1

But

echo "$temp"

gives:

file0
file1


问:
Trying to make an infinite scroll with a list of div already in the html
I'm trying to write a function in jQuery that could create an infinite scroll with divs that are already in my page. I would like to make them appear and load randomly when you reached the end of the original content. The thing is that I'm just starting to use jQuery and I don't really know who to do it!

All my divs have a class of item and are inside a .content div. For the moment I have 11 of them.

I tried to .append(specific div) and it worked, but I don't know how to do it with a list of div.

Does anyone have an idea of what I should do?

    $(document).ready(function() {
      var collection = $("div.content .item").get();
      collection.sort(function() {
        return Math.random() * 10 > 5 ? 1 : -1;
      });

      $.each(collection, function(i, el) {
        $(el).appendTo($(el).parent());
      });
    });

    $(window).scroll(function() {
      if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        $(".content").append('Here is where I dont know what I should write')
      });
    });
  }
});
```

答:
Hi :3 The jquery clone() function may be of help, in your case:

```<code>let triggerDistance = $(document).height() - $(window).height() - 50;
let OriginalItems = $(".item").length;

$(window).scroll(function() {
    let scrolledDistance = $(window).scrollTop();
    if ( scrolledDistance > triggerDistance) {
        var randomItem = Math.floor(Math.random() * OriginalItems);
        var clonedItem = $("#item_"+randomItem).clone();
        clonedItem.removeAttr('id');
        clonedItem.appendTo("html");
    }
});
</code>```

You select a random item from the original ones, you create a new copy of said item using clone, you append the clone to the document :)

Here's a fiddle: https://jsfiddle.net/collederfomento/d98a15cu/4/

A few things could be improved:

preventing the function from firing too often

preventing the function from cloning the same item twice in a row

Body:
Hi :3 The jquery clone() function may be of help, in your case:

let triggerDistance = $(document).height() - $(window).height() - 50;
let OriginalItems = $(".item").length;

$(window).scroll(function() {
    let scrolledDistance = $(window).scrollTop();
    if ( scrolledDistance > triggerDistance) {
        var randomItem = Math.floor(Math.random() * OriginalItems);
        var clonedItem = $("#item_"+randomItem).clone();
        clonedItem.removeAttr('id');
        clonedItem.appendTo("html");
    }
});

You select a random item from the original ones, you create a new copy of said item using clone, you append the clone to the document :)

Here's a fiddle: https://jsfiddle.net/collederfomento/d98a15cu/4/

A few things could be improved:

preventing the function from firing too often

preventing the function from cloning the same item twice in a row


问:
How to listen to mousemove inside angular material dialog component?
In my app Ineed to track the mouse movment all the time.

At the app.component.ts file I have placed the following code:

```<code>ngOnInit() {
document.addEventListener("mousemove", (e) => {
  //foo()
 });
})
</code>```

Everything works as expected besides inside the dialog.

The dialog is an Angular Material Dialog component and the code of creating it like this:

```<code>openModal() {
    const dialogRef = this.dialog.open(ModalComponent, {
      panelClass: 'generic-dialog-container',
      data: {
        header: 'Leave session',
        content:
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
        isInfo: false,
      },
    });

    this.dialogSub = dialogRef.componentInstance.isApprove.subscribe(
      isApprove => {
        if (isApprove) {
          this.navigateBack();
        }
      },
    );
  }
</code>```

I have tried adding an event listener inside the modal's OnInit - didn't work, Plus I saw that when I add It at the app.component.ts to the document than the listener is added to the body element and wraps the whole app, like this:

While the dialog is open the Event Listener listens to mouse events at the component in the background (the component who called to open the dialog), but not in the dialog itself.

After closing the dialog and then reopen it, the Event Listener listens to mouse events also inside the dialog as expected.

答: I would avoid using the document object to add listeners, and instead create an Observable with the fromEvent operator. As for the dialog, Angular Material may be interfering with event propagation. Try the Observable, and see what happens.

Body:
In my app Ineed to track the mouse movment all the time.

At the app.component.ts file I have placed the following code:

ngOnInit() {
document.addEventListener("mousemove", (e) => {
  //foo()
 });
})

Everything works as expected besides inside the dialog.

The dialog is an Angular Material Dialog component and the code of creating it like this:

openModal() {
    const dialogRef = this.dialog.open(ModalComponent, {
      panelClass: 'generic-dialog-container',
      data: {
        header: 'Leave session',
        content:
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
        isInfo: false,
      },
    });

    this.dialogSub = dialogRef.componentInstance.isApprove.subscribe(
      isApprove => {
        if (isApprove) {
          this.navigateBack();
        }
      },
    );
  }

I have tried adding an event listener inside the modal's OnInit - didn't work, Plus I saw that when I add It at the app.component.ts to the document than the listener is added to the body element and wraps the whole app, like this:

While the dialog is open the Event Listener listens to mouse events at the component in the background (the component who called to open the dialog), but not in the dialog itself.

After closing the dialog and then reopen it, the Event Listener listens to mouse events also inside the dialog as expected.


问:
QuickSort doesnt work with more than ~2000 elements. Why?
If I want to sort via the following QuickSort algorithm I get either a "RecursionError: maximum recursion depth exceeded in comparison" failure, or if I set the recursion limit much higher, Python stops working after it sortied via BubbleSort with (Process finished with exit code -1073741571 (0xC00000FD)). Does anyone have a idea, how i can fix this problem

Set recursion limit higher

import time
import random
from sys import setrecursionlimit
#setrecursionlimit(1000000)

#------------------------------Sortieralgorithmen-----------------------------------------------
#-----------------------------------------------------------------------------------------------

def bubbleSort(array):

    length = len(array)

    for sorted in range(length):

        for j in range(0, length-sorted-1):
            if array[j] > array[j+1] :
                array[j], array[j+1] = array[j+1], array[j]

def help(array, low, high):
    pivot = array[low]
    fromhigh = high
    fromlow = low
    while True:
        while(array[fromhigh]>pivot):
            fromhigh = fromhigh-1
        while(array[fromlow]<pivot):
            fromlow = fromlow+1
        if(fromlow<fromhigh):
            array[fromlow], array[fromhigh] = array[fromhigh], array[fromlow]
        else:
            return fromhigh

def quickSort(array, low, high):
   if (low<high):
       pivot = help(array, low, high)
       quickSort(array, low, pivot)
       quickSort(array, pivot + 1, high)

#--------------------------------Zeitmessung-----------------------------------------------------
#------------------------------------------------------------------------------------------------

numb_elements = 6000

sortedarray = []
for i in range (0,numb_elements):
    sortedarray.append(i)

notsortedarray = random.sample(range(0,numb_elements),numb_elements)

copy1 = sortedarray.copy()
before = time.time()
bubbleSort(copy1)
after = time.time()
total = after-before
print("Bubblesort sortiertes Array:\t\t" + str(total))

copy2 = notsortedarray.copy()
before = time.time()
bubbleSort(copy2)
after = time.time()
total = after-before
print("Bubblesort nicht sortiertes Array:\t" + str(total))

copy3 = sortedarray.copy()
before = time.time()
quickSort(copy3, 0, len(copy3)-1)
after = time.time()
total = after-before
print("QuickSort sortiertes Array:\t\t\t" + str(total))

copy4 = notsortedarray.copy()
before = time.time()
quickSort(copy4, 0, len(copy4)-1)
after = time.time()
total = after-before
print("QuickSort nicht sortiertes Array:\t" + str(total)+"\t (Worst Case)")

```

答:
A bit of introductory tracing shows the problem:

```<code>indent = ""

def quickSort(array, low, high):
   global indent
   # print(indent, "quickSort ENTER", low, high)
   indent += "  "
   if (low<high):
       pivot = help(array, low, high)
       print(low, high, pivot)
       quickSort(array, low, pivot)
       quickSort(array, pivot + 1, high)

   indent = indent[2:]
</code>```

After seeing the stack problem, I inserted the print statement that includes the pivot.  The output is

```<code>0 5999 0
1 5999 1
2 5999 2
3 5999 3
4 5999 4
5 5999 5
6 5999 6
...
994 5999 994
995 5999 995
996 5999 996
Traceback (most recent call last):
  File "so.py", line 79, in <module>
    quickSort(copy3, 0, len(copy3)-1)
  File "so.py", line 46, in quickSort
    quickSort(array, pivot + 1, high)
  File "so.py", line 46, in quickSort
    quickSort(array, pivot + 1, high)
  File "so.py", line 46, in quickSort
    quickSort(array, pivot + 1, high)
  [Previous line repeated 994 more times]
  File "so.py", line 43, in quickSort
    pivot = help(array, low, high)
  File "so.py", line 28, in help
    while(array[fromhigh]>pivot):
RecursionError: maximum recursion depth exceeded in comparison
</code>```

Your problem is that your pivot logic always returns the low element, which alters your algorithm to O(N^2), dying when N is greater than your allowed stack depth.

Can you take it from there?
See this lovely debug blog for help.

Even a trivial print will give you a lot of clues.

Body:
A bit of introductory tracing shows the problem:

indent = ""

def quickSort(array, low, high):
   global indent
   # print(indent, "quickSort ENTER", low, high)
   indent += "  "
   if (low<high):
       pivot = help(array, low, high)
       print(low, high, pivot)
       quickSort(array, low, pivot)
       quickSort(array, pivot + 1, high)

   indent = indent[2:]

After seeing the stack problem, I inserted the print statement that includes the pivot.  The output is

0 5999 0
1 5999 1
2 5999 2
3 5999 3
4 5999 4
5 5999 5
6 5999 6
...
994 5999 994
995 5999 995
996 5999 996
Traceback (most recent call last):
  File "so.py", line 79, in <module>
    quickSort(copy3, 0, len(copy3)-1)
  File "so.py", line 46, in quickSort
    quickSort(array, pivot + 1, high)
  File "so.py", line 46, in quickSort
    quickSort(array, pivot + 1, high)
  File "so.py", line 46, in quickSort
    quickSort(array, pivot + 1, high)
  [Previous line repeated 994 more times]
  File "so.py", line 43, in quickSort
    pivot = help(array, low, high)
  File "so.py", line 28, in help
    while(array[fromhigh]>pivot):
RecursionError: maximum recursion depth exceeded in comparison

Your problem is that your pivot logic always returns the low element, which alters your algorithm to O(N^2), dying when N is greater than your allowed stack depth.

Can you take it from there?
See this lovely debug blog for help.

Even a trivial print will give you a lot of clues.


问:
JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'
In short: I am trying to understand the meaning of this TypeError:
Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
The error appears while lunching Mediawiki's VisualEditor, as can be seen here:

http://www.wiki.org.il/index.php?title=new-page&veaction=edit

The error doesn't enables creating new pages or editing the wiki anonymously.
However, with the use of a different skin the error disappears:

http://www.wiki.org.il/index.php/Main_Page?useskin=vector

The wiki runs on 1.25alpha.

答:
The error message says that getComputedStyle requires the parameter to be Element type. You receive it because the parameter has an incorrect type.

The most common case is that you try to pass an element that doesn't exist as an argument:

```<code>my_element = document.querySelector(#non_existing_id);
</code>```

Now that element is null, this will result in mentioned error:

```<code>my_style = window.getComputedStyle(my_element);
</code>```

If it's not possible to always get element correctly, you can, for example, use the following to end function if querySelector didn't find any match:

```<code>if (my_element === null) return;
</code>```

Body:
The error message says that getComputedStyle requires the parameter to be Element type. You receive it because the parameter has an incorrect type.

The most common case is that you try to pass an element that doesn't exist as an argument:

my_element = document.querySelector(#non_existing_id);

Now that element is null, this will result in mentioned error:

my_style = window.getComputedStyle(my_element);

If it's not possible to always get element correctly, you can, for example, use the following to end function if querySelector didn't find any match:

if (my_element === null) return;


问:
groupby with calculations in series
I have a series of which this is a snippet:

```<code>Dates
1988-01-01        NaN
1988-01-04     257.40
1988-01-05     259.80
1988-01-06     258.60
1988-01-07     262.85
1988-01-08     240.75
1988-01-11     247.70
1988-01-12     246.35
1988-01-13     246.25
1988-01-14     247.45
1988-01-15     251.50
...
2019-03-01    2805.00
2019-03-04    2791.50
2019-03-05    2791.50
2019-03-06    2771.50
2019-03-07    2750.00
2019-03-08    2747.00
2019-03-11    2789.00
2019-03-12    2797.25
2019-03-13    2819.50
2019-03-14    2812.25
2019-03-15    2829.75
Length: 8141, dtype: float64
</code>```

I need to perform a 40 week moving average of this series by weekday: that is, for Mondays, Tuesdays, etc.

I have tried several methods, but only one has been successful.

```<code>werTarget = werTarget.fillna(method='ffill')
i = 0
while i < 5: # for Monday to Friday, do each weekday separately
    tmpTarget = werTarget[werTarget.index.weekday==i]
    tmpIntmdInd = tmpTarget / tmpTarget.rolling(window=40).mean()
    if i == 0:
        IntmdInd = tmpIntmdInd
    else:
        holdindx = IntmdInd
        i = i + 1
</code>```

It took over two hours to complete, and when I plotted it, every single data point was its own line.

I need a single series as a result, and certainly much faster: Some of the series are longer than this, and there are literally thousands of them.

I tried using something more terse,

```<code>werTarget = werTarget.fillna(method='ffill')
IntmdInd = werTarget.groupby('weekday').rolling(window=40).mean()
</code>```

but this results in the error

```<code>Traceback (most recent call last):

  File "<ipython-input-16-1d4ba482ec32>", line 1, in <module>
    runfile('C:/MyFile.py', wdir='C:/MyDir')

  File "C:\Users\Admin\Anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Admin\Anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/MyFile.py", line 62, in <module>
    werGraph(sp,werOne)

  File "C:/MyFile.py", line 44, in werGraph
    IntmdInd = werIntmdInd(werRat)

  File "C:/MyFile.py", line 34, in werIntmdInd
    IntmdInd = werTarget.groupby('weekday').rolling(window=75).mean()

  File "C:\Users\Admin\Anaconda2\lib\site-packages\pandas\core\generic.py", line 7632, in groupby
    observed=observed, **kwargs)

  File "C:\Users\Admin\Anaconda2\lib\site-packages\pandas\core\groupby\groupby.py", line 2110, in groupby
    return klass(obj, by, **kwds)

  File "C:\Users\Admin\Anaconda2\lib\site-packages\pandas\core\groupby\groupby.py", line 360, in __init__
    mutated=self.mutated)

  File "C:\Users\Admin\Anaconda2\lib\site-packages\pandas\core\groupby\grouper.py", line 578, in _get_grouper
    raise KeyError(gpr)

KeyError: 'weekday'
</code>```

Does anyone know a solution?

Title: groupby with calculations in series

Body:
I have a series of which this is a snippet:

Dates
1988-01-01        NaN
1988-01-04     257.40
1988-01-05     259.80
1988-01-06     258.60
1988-01-07     262.85
1988-01-08     240.75
1988-01-11     247.70
1988-01-12     246.35
1988-01-13     246.25
1988-01-14     247.45
1988-01-15     251.50
...
2019-03-01    2805.00
2019-03-04    2791.50
2019-03-05    2791.50
2019-03-06    2771.50
2019-03-07    2750.00
2019-03-08    2747.00
2019-03-11    2789.00
2019-03-12    2797.25
2019-03-13    2819.50
2019-03-14    2812.25
2019-03-15    2829.75
Length: 8141, dtype: float64

I need to perform a 40 week moving average of this series by weekday: that is, for Mondays, Tuesdays, etc.

I have tried several methods, but only one has been successful.

werTarget = werTarget.fillna(method='ffill')
i = 0
while i < 5: # for Monday to Friday, do each weekday separately
    tmpTarget = werTarget[werTarget.index.weekday==i]
    tmpIntmdInd = tmpTarget / tmpTarget.rolling(window=40).mean()
    if i == 0:
        IntmdInd = tmpIntmdInd
    else:
        holdindx = IntmdInd
        i = i + 1

It took over two hours to complete, and when I plotted it, every single data point was its own line.

I need a single series as a result, and certainly much faster: Some of the series are longer than this, and there are literally thousands of them.

I tried using something more terse,

werTarget = werTarget.fillna(method='ffill')
IntmdInd = werTarget.groupby('weekday').rolling(window=40).mean()

but this results in the error

Traceback (most recent call last):

  File "<ipython-input-16-1d4ba482ec32>", line 1, in <module>
    runfile('C:/MyFile.py', wdir='C:/MyDir')

  File "C:\Users\Admin\Anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Admin\Anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/MyFile.py", line 62, in <module>
    werGraph(sp,werOne)

  File "C:/MyFile.py", line 44, in werGraph
    IntmdInd = werIntmdInd(werRat)

  File "C:/MyFile.py", line 34, in werIntmdInd
    IntmdInd = werTarget.groupby('weekday').rolling(window=75).mean()

  File "C:\Users\Admin\Anaconda2\lib\site-packages\pandas\core\generic.py", line 7632, in groupby
    observed=observed, **kwargs)

  File "C:\Users\Admin\Anaconda2\lib\site-packages\pandas\core\groupby\groupby.py", line 2110, in groupby
    return klass(obj, by, **kwds)

  File "C:\Users\Admin\Anaconda2\lib\site-packages\pandas\core\groupby\groupby.py", line 360, in __init__
    mutated=self.mutated)

  File "C:\Users\Admin\Anaconda2\lib\site-packages\pandas\core\groupby\grouper.py", line 578, in _get_grouper
    raise KeyError(gpr)

KeyError: 'weekday'

Does anyone know a solution?

Body:
I'm not sure where the bug is, because I pretty much used the code from your question.
I'll demonstrate this with some data from pandas_datareader

>>> import pandas_datareader as pdr
>>> import pandas as pd  # version 0.24.2
>>>
>>> start = pd.to_datetime('2017-01-01')#datetime(2015, 2, 9)
>>> end = pd.to_datetime('2019-01-01')
>>> f = pdr.data.DataReader('F', 'iex', start, end)
>>> f.head()

               open     high      low    close    volume
date
2017-01-03  10.4286  10.7705  10.3687  10.7619  40510821
2017-01-04  10.9158  11.3432  10.8902  11.2577  77638075
2017-01-05  11.2919  11.3005  10.7961  10.9158  75628443
2017-01-06  10.9414  10.9756  10.8047  10.9072  40315887
2017-01-09  10.9329  10.9927  10.7961  10.7961  39438393

Then I just convert the index to datetime, get the weekday, and perform the rolling average on the grouped data

>>> f.index = pd.to_datetime(f.index)
>>> f['weekday'] = f.index.weekday
>>> f.groupby('weekday').rolling(40).mean().tail()

                        open      high       low     close        volume  weekday
weekday date
4       2018-11-30  9.750638  9.837815  9.640928  9.727008  4.159594e+07      4.0
        2018-12-07  9.722113  9.811025  9.608238  9.692950  4.213964e+07      4.0
        2018-12-14  9.691435  9.780057  9.578423  9.658573  4.151767e+07      4.0
        2018-12-21  9.644488  9.735150  9.528508  9.605200  4.228912e+07      4.0
        2018-12-28  9.576780  9.670210  9.460493  9.536315  4.145531e+07      4.0


问:
Get 2nd parent directory of given file
I have a script which finds files containing certain strings.

Let's say my found file is:

```
C:\temp\drivers\etc\file.INF
```

I want to get the 2nd parent folder for that file.

For example if it's:

```
C:\temp\drivers\etc\file.INF
```

I want to have this path:

```
C:\temp\drivers
```

What makes the most sense to you in a situation like this?

I can make it work with:

```<code>$test = "C:\temp\drivers\etc\file.INF"
$first_parent = Split-path $test -Parent
$second_parent= $first_parent.Substring(0,$first_parent.LastIndexOf('\'))
$second_parent
</code>```

Output:

```
C:\temp\drivers
```

But is it optimal?

答:
if your item is a file - not just a string - you can derive the grandparent dir from the fileinfo object that you get from Get-Item or Get-ChildItem. like this ...

```<code>$FileName_String = 'C:\temp\drivers\etc\file.INF'
# fake reading in the fileinfo object
#    in real life, use Get-Item or Get-ChildItem
$FileName_FileInfoObject = [System.IO.FileInfo]$FileName_String

$2ndParentDir = $FileName_FileInfoObject.Directory.Parent

$FileName_String
$FileName_FileInfoObject.FullName
$2ndParentDir.FullName
</code>```

output ...

```<code>C:\temp\drivers\etc\file.INF
C:\temp\drivers\etc\file.INF
C:\temp\drivers
</code>```

if it is just a string, then you need to use Split-Path twice. [grin]

Title: Get 2nd parent directory of given file

Body:
I have a script which finds files containing certain strings.

Let's say my found file is:

C:\temp\drivers\etc\file.INF

I want to get the 2nd parent folder for that file.

For example if it's:

C:\temp\drivers\etc\file.INF

I want to have this path:

C:\temp\drivers

What makes the most sense to you in a situation like this?

I can make it work with:

$test = "C:\temp\drivers\etc\file.INF"
$first_parent = Split-path $test -Parent
$second_parent= $first_parent.Substring(0,$first_parent.LastIndexOf('\'))
$second_parent

Output:

C:\temp\drivers

But is it optimal?

Body:
if your item is a file - not just a string - you can derive the grandparent dir from the fileinfo object that you get from Get-Item or Get-ChildItem. like this ...

$FileName_String = 'C:\temp\drivers\etc\file.INF'
# fake reading in the fileinfo object
#    in real life, use Get-Item or Get-ChildItem
$FileName_FileInfoObject = [System.IO.FileInfo]$FileName_String

$2ndParentDir = $FileName_FileInfoObject.Directory.Parent

$FileName_String
$FileName_FileInfoObject.FullName
$2ndParentDir.FullName

output ...

C:\temp\drivers\etc\file.INF
C:\temp\drivers\etc\file.INF
C:\temp\drivers

if it is just a string, then you need to use Split-Path twice. [grin]