问:
Multiple commas Javascript when printing an array
This is probably really basic but I keep getting strange output when printing an array, it keeps putting double commas in between values in the arrays. I know it's something simple but I've been at this for a couple of hours now and no joy. You can see at the end I've tried a couple of things but end up with a weird double comma.</p>

```<code><!DOCTYPE html>
<html>
<body>

<p>Click the button to run the digit checker.</p> <!--Text telling the user to hit the button-->

<button onclick="myDigitChecker()" >Submit</button> <!--button that runs my function once they hit-->

<p id="demo"></p>
<p id="demo2"></p>

<script>
function myDigitChecker() {
    var input = prompt("Please enter two positive digits, decimals will be rounded");
    var digits = Math.round(input); //take the inoput and convert it to a whole number

    var evenNumbers = [];
    var oddNumbers = [];

    while (isNaN(digits)|| digits < 10 || digits >99) {//isNaN is a method for checking if something isn't a number
    var digits = prompt("Please enter two positive digits, decimals will be rounded")}

    for (x = 0; x <= digits ;x++){
        if(x % 2 === 0){
            evenNumbers[x] = x;
            console.log(evenNumbers);
        }else{
            oddNumbers[x] = x;
            console.log(oddNumbers);
        }
    }

    document.getElementById("demo").innerHTML = (evenNumbers.join(","));
    var str1 = oddNumbers.toString;
    document.getElementById("demo2").innerHTML = oddNumbers;

}
</script>

</body>
</html>
</code>```

答:
Remove the empty values in arrays, replace evenNumbers.join(",") with evenNumbers.filter(x =>  Number.isInteger(x).join(",").

```<code>document.getElementById("demo").innerHTML = evenNumbers.filter(x =>  Number.isInteger(x).join(",");
document.getElementById("demo2").innerHTML = oddNumbers.filter(x =>  Number.isInteger(x).join(",");
</code>```

Body:
This is probably really basic but I keep getting strange output when printing an array, it keeps putting double commas in between values in the arrays. I know it's something simple but I've been at this for a couple of hours now and no joy. You can see at the end I've tried a couple of things but end up with a weird double comma.

<!DOCTYPE html>

Click the button to run the digit checker.

<button onclick="myDigitChecker()" >Submit</button>

Body:
Remove the empty values in arrays, replace evenNumbers.join(",") with evenNumbers.filter(x =>  Number.isInteger(x).join(",").

document.getElementById("demo").innerHTML = evenNumbers.filter(x =>  Number.isInteger(x).join(",");
document.getElementById("demo2").innerHTML = oddNumbers.filter(x =>  Number.isInteger(x).join(",");


来源: stackexchange

问:
SystemParametersInfoA with SPI_GETMOUSE returns 0's
Go to the answer of the question

I'm trying to get my mouse speed, but when I call the function SystemParametersInfoA with parameter SPI_GETMOUSE it sets the target array to {0,0,0} which I think its not supposed to happen.

Example code:

```<code>int IntArr[3];
SystemParametersInfoA(SPI_GETMOUSE, 0, &IntArr, 0);
</code>```

I tried changing my mouse sensitivity (from the control panel) but that didn't work either.

Does this function is supposed to return those zeros or thats my fault?

答:
The documentation says:

Retrieves the two mouse threshold values and the mouse acceleration.

At first I did tought that these two mouse threshold values were related to my mouse cursor sensitivty.

After a deeper search in the docs for mouse_event, I found out that in the remarks section it says:

The system applies two tests to the specified relative mouse motion when applying acceleration. If the specified distance along either the x or y axis is greater than the first mouse threshold value, and the mouse acceleration level is not zero, the operating system doubles the distance. If the specified distance along either the x- or y-axis is greater than the second mouse threshold value, and the mouse acceleration level is equal to two, the operating system doubles the distance that resulted from applying the first threshold test. It is thus possible for the operating system to multiply relatively-specified mouse motion along the x- or y-axis by up to four times.

Which basically means that these 3 values that I got in the destination array IntArr wasn't anything to do with sensitivity, but rather these 2 mouse threshold values and the "Enhance pointer precission" which was either 0 or 1 indicating it turned on or off, mine was disabled thats why I got all zeros.

In order to get the mouse sensitivity you have to use SystemParametersInfoA function with the SPI_GETMOUSESPEED parameter as uiAction instead.

ContentLicense: CC BY-SA 4.0

Body:
Go to the answer of the question

I'm trying to get my mouse speed, but when I call the function SystemParametersInfoA with parameter SPI_GETMOUSE it sets the target array to {0,0,0} which I think its not supposed to happen.

Example code:

int IntArr[3];
SystemParametersInfoA(SPI_GETMOUSE, 0, &IntArr, 0);

I tried changing my mouse sensitivity (from the control panel) but that didn't work either.

Does this function is supposed to return those zeros or thats my fault?


问:
PHP, POST data from one row only (id) from WHILE loop, when SUBMIT
Issue, how can I POST needed data (id,username, etc.) only for one row, from while loop, when submit?

Code (I am using POST as call "function" delete_member, with if condition, what is better way?).

```<code>if(isset($_POST["delete_member"]))
{
# Delete member
echo $id=$_POST["id"];
$sql="delete from members where id = $id";
mysqli_query($db,$sql) ? $status = true : $status = false;
message($status);
}

$select_members = mysqli_query($db,"select * from members");
while($row = mysqli_fetch_array($select_members))
{
echo('
<tr>
<td><input type="text name="id" value="'.$row['id'].'" readonly></td>
<td><input type="text name="username" value="'.$row['username'].'" readonly></td>
<td><input type="text name="password" value="'.$row['password'].'" readonly></td>
<td><input type="text name="active" value="'.$row['active'].'" readonly></td>
<td><input type="submit" name="delete_member" value="Smazat"></td>
<td><input type="submit" name="send_email" value="Odeslat email"></td>
<tr>
');
}
</code>```

Nothing stored in echo $id=$_POST["id"];. Is possible send id from input type="submit"? For example like this.

```<code><input type="submit" name="delete_member" id=".$row['id']." value="Smazat">
</code>```

Thanks.

答:
```<code>if(isset($_POST["delete_member"]))
{
# Delete member
echo $id=$_POST["id"];
$sql="delete from members where id = $id";
mysqli_query($db,$sql) ? $status = true : $status = false;
message($status);
}

$select_members = mysqli_query($db,"select * from members");
while($row = mysqli_fetch_array($select_members))
{
echo('
<tr>
<td>'.$row['id'].'</td>
<td>'.$row['username'].'</td>
<td>'.$row['password'].'</td>
<td>'.$row['active'].'</td>

<td><form method="post" action="HERE_FILL_IN_SCRIPT_URL"><input type="hidden" name="id" value="'.$row['id'].'"><input type="submit" name="delete_member" value="Smazat"><input type="submit" name="send_email" value="Odeslat email"></form></td>
<tr>
');
}
</code>```

Body:
Issue, how can I POST needed data (id,username, etc.) only for one row, from while loop, when submit?

Code (I am using POST as call "function" delete_member, with if condition, what is better way?).

if(isset($_POST["delete_member"]))
{
# Delete member
echo $id=$_POST["id"];
$sql="delete from members where id = $id";
mysqli_query($db,$sql) ? $status = true : $status = false;
message($status);
}

$select_members = mysqli_query($db,"select * from members");
while($row = mysqli_fetch_array($select_members))
{
echo('

<input type="text name="id" value="'.$row['id'].'" readonly>
<input type="text name="username" value="'.$row['username'].'" readonly>
<input type="text name="password" value="'.$row['password'].'" readonly>
<input type="text name="active" value="'.$row['active'].'" readonly>
<input type="submit" name="delete_member" value="Smazat">
<input type="submit" name="send_email" value="Odeslat email">

');
}

Nothing stored in echo $id=$_POST["id"];. Is possible send id from input type="submit"? For example like this.

<input type="submit" name="delete_member" id=".$row['id']." value="Smazat">

Thanks.


问:
Display date in format of YYYY-MM-DD in SQL
Display the date in the format of YYYY-MM-DD. Explain to me with one simple program.</p>

答:
You can try like this. For different types of date formats to be displayed, you can get help from this link.

Another way is to Convert() function as shown in the link Date and Time Conversions Using SQL Server
.

```<code>SELECT FORMAT (getdate(), 'yyyy-MM-dd') as DateWithFormat
</code>```

The output here will be

```<code>DateWithFormat
--------------
2020-02-15
</code>```

Here is the official documentation of FORMAT (Transact-SQL)
.

Body:
You can try like this. For different types of date formats to be displayed, you can get help from this link.

Another way is to Convert() function as shown in the link Date and Time Conversions Using SQL Server
.

SELECT FORMAT (getdate(), 'yyyy-MM-dd') as DateWithFormat

The output here will be

DateWithFormat
--------------
2020-02-15

Here is the official documentation of FORMAT (Transact-SQL)
.


问:
Cucumber Length?
I am creating a Cucumber test for a multistep registration process and am a little unsure about the best practice for the Scenario Steps...

There are 4 forms / pages in the registration.  Should I loop through the Given, When & Then 4 times in the one scenario or is there a better way to organise it?

So far, I have got...

```<code>Scenario: Company User
Given I am on the registration page
When I follow "Register as a supplier"
When I fill in the following:
  | user_email | test@test.com |
  | user_password | secret |
  | user_password_confirmation | secret |
And I press "Create login - Proceed to step 2"
Then I should see "Create Company Profile"
When I fill in the following:
  | company_name | Test Company |
  | company_description | Lorem |
  | company_telephone | 01928740436 |
  | company_email | info@agency.com |
And I press "Create company - Proceed to step 3"
Then I should see "Test Company office(s)"
</code>```

答:
I would recommend having 4 scenarios covering the detail of each step, e.g:

```<code>Given I am on step 2
When I fill in the following:
  | company_name | Test Company |
  | company_description | Lorem |
  | company_telephone | 01928740436 |
  | company_email | info@agency.com |
And I press "Create company - Proceed to step 3"
Then I should see "Test Company office(s)"
</code>```

You can hide away any necessary but irrelevant form-filling within the definition of "Given I am on step X".

You should probably also have a scenario which covers how everything fits together, e.g.:

```<code>When I complete step 1 with valid information
And I complete step 2 with valid information
And I complete step 3 with valid information
And I complete step 4 with valid information
Then I should see "Thank you for registering"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cucumber Length?

Body:
I am creating a Cucumber test for a multistep registration process and am a little unsure about the best practice for the Scenario Steps...

There are 4 forms / pages in the registration.  Should I loop through the Given, When & Then 4 times in the one scenario or is there a better way to organise it?

So far, I have got...

Scenario: Company User
Given I am on the registration page
When I follow "Register as a supplier"
When I fill in the following:
  | user_email | test@test.com |
  | user_password | secret |
  | user_password_confirmation | secret |
And I press "Create login - Proceed to step 2"
Then I should see "Create Company Profile"
When I fill in the following:
  | company_name | Test Company |
  | company_description | Lorem |
  | company_telephone | 01928740436 |
  | company_email | info@agency.com |
And I press "Create company - Proceed to step 3"
Then I should see "Test Company office(s)"

Body:
I would recommend having 4 scenarios covering the detail of each step, e.g:

Given I am on step 2
When I fill in the following:
  | company_name | Test Company |
  | company_description | Lorem |
  | company_telephone | 01928740436 |
  | company_email | info@agency.com |
And I press "Create company - Proceed to step 3"
Then I should see "Test Company office(s)"

You can hide away any necessary but irrelevant form-filling within the definition of "Given I am on step X".

You should probably also have a scenario which covers how everything fits together, e.g.:

When I complete step 1 with valid information
And I complete step 2 with valid information
And I complete step 3 with valid information
And I complete step 4 with valid information
Then I should see "Thank you for registering"


问:
Parsing specific region of a txt, comparing to list of strings, then generating new list composed of matches
I am trying to do the following:

Read through a specific portion of a text file (there is a known starting point and ending point)

While reading through these lines, check to see if a word matches a word that I have included in a list

If a match is detected, then add that specific word to a new list

I have been able to read through the text and grab other data from it that I need, but I've been unable to do the above mentioned thus far.

I have tried to implement the following example: Python - Search Text File For Any String In a List
But I have failed to make it read correctly.

I have also tried to adapt the following: https://www.geeksforgeeks.org/python-finding-strings-with-given-substring-in-list/
But I was equally unsuccessful.

Here is some of my code:

```<code>import re
from itertools import islice
import os

# list of all countries
oneCountries = "Afghanistan, Albania, Algeria, Andorra, Angola, Antigua & Deps, Argentina, Armenia, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bhutan, Bolivia, Bosnia Herzegovina, Botswana, Brazil, Brunei, Bulgaria, Burkina, Burma, Burundi, Cambodia, Cameroon, Canada, Cape Verde, Central African Rep, Chad, Chile, China, Republic of China, Colombia, Comoros, Democratic Republic of the Congo, Republic of the Congo, Costa Rica,, Croatia, Cuba, Cyprus, Czech Republic, Danzig, Denmark, Djibouti, Dominica, Dominican Republic, East Timor, Ecuador, Egypt, El Salvador, Equatorial Guinea, Eritrea, Estonia, Ethiopia, Fiji, Finland, France, Gabon, Gaza Strip, The Gambia, Georgia, Germany, Ghana, Greece, Grenada, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Holy Roman Empire, Honduras, Hungary, Iceland, India, Indonesia, Iran, Iraq, Republic of Ireland, Israel, Italy, Ivory Coast, Jamaica, Japan, Jonathanland, Jordan, Kazakhstan, Kenya, Kiribati, North Korea, South Korea, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Marshall Islands, Mauritania, Mauritius, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Morocco, Mount Athos, Mozambique, Namibia, Nauru, Nepal, Newfoundland, Netherlands, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Ottoman Empire, Pakistan, Palau, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Poland, Portugal, Prussia, Qatar, Romania, Rome, Russian Federation, Rwanda, St Kitts & Nevis, St Lucia, Saint Vincent & the Grenadines, Samoa, San Marino, Sao Tome & Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, Somalia, South Africa, Spain, Sri Lanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Tajikistan, Tanzania, Thailand, Togo, Tonga, Trinidad & Tobago, Tunisia, Turkey, Turkmenistan, Tuvalu, Uganda, Ukraine, United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Vatican City, Venezuela, Vietnam, Yemen, Zambia, Zimbabwe"
countries = oneCountries.split(",")

path = "C:/Users/me/Desktop/read.txt"
thefile = open(path, errors='ignore')

countryParsing = False
for line in thefile:
    line = line.strip()
#    if line.startswith("Submitting Author:"):
#    if re.match(r"Submitting Author:", line):
#        print("blahblah1")
#        countryParsing = True
#        if countryParsing == True:
#            print("blahblah2")
#
#            res = [x for x in line if re.search(countries, x)]
#            print("blah blah3: " + str(res))
#    elif re.match(r"Running Head:", line):
#        countryParsing = False
#    if countryParsing == True:
#        res = [x for x in line if re.search(countries, x)]
#        print("blah blah4: " + str(res))

#        for x in countries:
#            if x in thefile:
#                print("a country is: " + x)
#        if any(s in line for s in countries):
#            listOfAuthorCountries = listOfAuthorCountries + s + ", "
#    if re.match(f"Submitting Author:, line"):
</code>```

The #commented out lines are versions of the code that I've tried and failed to make work properly.

As requested, this is an example of the text file that I'm trying to grab the data from.  I've modified it to remove sensitive information, but in this particular case, the "new list" should be appended with a certain number of "France" entries:

```<code>    txt above....
Submitting Author:

    asdf, asdf  (proxy)
    France
    asdfasdf
    blah blah
    asdfasdf

    asdf, Provence-Alpes-Côte d'Azu 13354
    France

    blah blah
    France
    asdf
Running Head:
    ...more text below
</code>```

答:
I think your main problem is that, in oneCountries, the country-names are separated by comma+space, but you're only splitting on comma, so for instance the second entry in countries is " Albania", with a space in front. You need to change:

```<code>oneCountries.split(",")
</code>```

to:

```<code>oneCountries.split(", ")
</code>```

After that, it looks like there's enough useful stuff in your commented-out code to achieve what you want.

Body:
I am trying to do the following:

Read through a specific portion of a text file (there is a known starting point and ending point)

While reading through these lines, check to see if a word matches a word that I have included in a list

If a match is detected, then add that specific word to a new list

I have been able to read through the text and grab other data from it that I need, but I've been unable to do the above mentioned thus far.

I have tried to implement the following example: Python - Search Text File For Any String In a List
But I have failed to make it read correctly.

I have also tried to adapt the following: https://www.geeksforgeeks.org/python-finding-strings-with-given-substring-in-list/
But I was equally unsuccessful.

Here is some of my code:

import re
from itertools import islice
import os

# list of all countries
oneCountries = "Afghanistan, Albania, Algeria, Andorra, Angola, Antigua & Deps, Argentina, Armenia, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bhutan, Bolivia, Bosnia Herzegovina, Botswana, Brazil, Brunei, Bulgaria, Burkina, Burma, Burundi, Cambodia, Cameroon, Canada, Cape Verde, Central African Rep, Chad, Chile, China, Republic of China, Colombia, Comoros, Democratic Republic of the Congo, Republic of the Congo, Costa Rica,, Croatia, Cuba, Cyprus, Czech Republic, Danzig, Denmark, Djibouti, Dominica, Dominican Republic, East Timor, Ecuador, Egypt, El Salvador, Equatorial Guinea, Eritrea, Estonia, Ethiopia, Fiji, Finland, France, Gabon, Gaza Strip, The Gambia, Georgia, Germany, Ghana, Greece, Grenada, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Holy Roman Empire, Honduras, Hungary, Iceland, India, Indonesia, Iran, Iraq, Republic of Ireland, Israel, Italy, Ivory Coast, Jamaica, Japan, Jonathanland, Jordan, Kazakhstan, Kenya, Kiribati, North Korea, South Korea, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Marshall Islands, Mauritania, Mauritius, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Morocco, Mount Athos, Mozambique, Namibia, Nauru, Nepal, Newfoundland, Netherlands, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Ottoman Empire, Pakistan, Palau, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Poland, Portugal, Prussia, Qatar, Romania, Rome, Russian Federation, Rwanda, St Kitts & Nevis, St Lucia, Saint Vincent & the Grenadines, Samoa, San Marino, Sao Tome & Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, Somalia, South Africa, Spain, Sri Lanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Tajikistan, Tanzania, Thailand, Togo, Tonga, Trinidad & Tobago, Tunisia, Turkey, Turkmenistan, Tuvalu, Uganda, Ukraine, United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Vatican City, Venezuela, Vietnam, Yemen, Zambia, Zimbabwe"
countries = oneCountries.split(",")

path = "C:/Users/me/Desktop/read.txt"
thefile = open(path, errors='ignore')

countryParsing = False
for line in thefile:
    line = line.strip()
#    if line.startswith("Submitting Author:"):
#    if re.match(r"Submitting Author:", line):
#        print("blahblah1")
#        countryParsing = True
#        if countryParsing == True:
#            print("blahblah2")
#
#            res = [x for x in line if re.search(countries, x)]
#            print("blah blah3: " + str(res))
#    elif re.match(r"Running Head:", line):
#        countryParsing = False
#    if countryParsing == True:
#        res = [x for x in line if re.search(countries, x)]
#        print("blah blah4: " + str(res))

#        for x in countries:
#            if x in thefile:
#                print("a country is: " + x)
#        if any(s in line for s in countries):
#            listOfAuthorCountries = listOfAuthorCountries + s + ", "
#    if re.match(f"Submitting Author:, line"):

The #commented out lines are versions of the code that I've tried and failed to make work properly.

As requested, this is an example of the text file that I'm trying to grab the data from.  I've modified it to remove sensitive information, but in this particular case, the "new list" should be appended with a certain number of "France" entries:

    txt above....
Submitting Author:

    asdf, asdf  (proxy)
    France
    asdfasdf
    blah blah
    asdfasdf

    asdf, Provence-Alpes-Côte d'Azu 13354
    France

    blah blah
    France
    asdf
Running Head:
    ...more text below

Body:
I think your main problem is that, in oneCountries, the country-names are separated by comma+space, but you're only splitting on comma, so for instance the second entry in countries is " Albania", with a space in front. You need to change:

oneCountries.split(",")

to:

oneCountries.split(", ")

After that, it looks like there's enough useful stuff in your commented-out code to achieve what you want.


问:
Lists weirdly modifies itself in a nested loop
The problem happens in the nested loop. In the first iteration everything is fine. The 2nd iteration over i, modifies the first list too and so on. Zeros across the 2d list should be diagonal </p>

```<code>import math
def calcpyth(p1, p2):
    distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
    return distance

tuple0 = (42, 288)
tuple1 = (45, 326)
tuple2 = (50, 364)
tuple3 = (57, 400)

list = [tuple0, tuple1, tuple2, tuple3]
zeros = [[0]*len(list)]*len(list)
test = zeros

for i in range(len(test)):
    for j in range(len(test)):
        test[i][j] = calcpyth(list[i], list[j])

</code>```

答:
The problem is in the line

```<code>zeros = [[0]*len(list)]*len(list)
</code>```

In that line of code, you create two lists:

a list containing many 0s, with [0]*len(list)

a list containing many references to the list created in step one. Here is the problem: You have created many references to one and the same list object. This explains the weird behaviour: If you change your nested list at one place, all 'sublists' appear to be changed as well.

So, what you would probably like to do, is to create a list containing many indepent lists that all contain 0s. Try:

```<code>zeros = [[0 for lv in range(len(list))] for lv in range(len(list))]
</code>```

Body:
The problem happens in the nested loop. In the first iteration everything is fine. The 2nd iteration over i, modifies the first list too and so on. Zeros across the 2d list should be diagonal

import math
def calcpyth(p1, p2):
    distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
    return distance

tuple0 = (42, 288)
tuple1 = (45, 326)
tuple2 = (50, 364)
tuple3 = (57, 400)

list = [tuple0, tuple1, tuple2, tuple3]
zeros = [[0]*len(list)]*len(list)
test = zeros

for i in range(len(test)):
    for j in range(len(test)):
        test[i][j] = calcpyth(list[i], list[j])

Body:
The problem is in the line

zeros = [[0]*len(list)]*len(list)

In that line of code, you create two lists:

a list containing many 0s, with [0]*len(list)

a list containing many references to the list created in step one. Here is the problem: You have created many references to one and the same list object. This explains the weird behaviour: If you change your nested list at one place, all 'sublists' appear to be changed as well.

So, what you would probably like to do, is to create a list containing many indepent lists that all contain 0s. Try:

zeros = [[0 for lv in range(len(list))] for lv in range(len(list))]


问:
How to add objects to a list with a thread and use the list at the same time without getting ConcurrentModificationException?
The title tells it all, I have a Timer t1 which periodically adds objects to a List.
Then I have an other Timer t2 iterating on the list at constant intervals to display its content.

I totaly understand why i'm getting these exceptions but I can't come up with the right answer to avoid it. Iv'e tried running my operations in synchronized(list){} and such things but nothing makes it. My algorithm apears to be working just fine despite these exceptions but i would like to make it clean nontheless.

Any idea?

Edit:
I'm using java.util.Timer;

答:
All access to the List much be wrapped by a synchronized block like so:

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public final class Answer {
    private static final int FIVE_SECONDS = 5 * 1000;
    private static final int TWO_SECONDS = 2 * 1000;

    public static void main(String... args) {
        // this list contains the values that the producer will add to and the consumer will pull from
        final List<Long> theList = new ArrayList<>();

        // consumes all values found in theList
        new Timer("consumer").scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                final List<Long> copy;
                synchronized (theList) {
                    // we make a copy and clear theArray as quickly as possible in
                    // order to not block the producer for too long
                    copy = new ArrayList<>(theList);
                    theList.clear();
                }

                System.out.println("copy = " + copy);
            }
        }, 1, FIVE_SECONDS);

        // adds the current time in ms to theList every 2 seconds
        new Timer("producer").scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                synchronized (theList) {
                    theList.add(System.currentTimeMillis());
                }
            }
        }, 1, TWO_SECONDS);
    }
}
</code>```

That being said using a BlockingQueue will do this for you.

Body:
All access to the List much be wrapped by a synchronized block like so:

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public final class Answer {
    private static final int FIVE_SECONDS = 5 * 1000;
    private static final int TWO_SECONDS = 2 * 1000;

    public static void main(String... args) {
        // this list contains the values that the producer will add to and the consumer will pull from
        final List<Long> theList = new ArrayList<>();

        // consumes all values found in theList
        new Timer("consumer").scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                final List<Long> copy;
                synchronized (theList) {
                    // we make a copy and clear theArray as quickly as possible in
                    // order to not block the producer for too long
                    copy = new ArrayList<>(theList);
                    theList.clear();
                }

                System.out.println("copy = " + copy);
            }
        }, 1, FIVE_SECONDS);

        // adds the current time in ms to theList every 2 seconds
        new Timer("producer").scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                synchronized (theList) {
                    theList.add(System.currentTimeMillis());
                }
            }
        }, 1, TWO_SECONDS);
    }
}

That being said using a BlockingQueue will do this for you.


问:
Kern Individual Letters With JavaScript (using Generated Content)
I have an anchor tag which is generated with Wordpress from the database, and the font the client uses has poor kerning. I need to be able to select individual letters on the anchor link and add a margin-right CSS value to certain letters in the generated text.

How would I go about selecting the 2nd, 3rd, 4th letter etc of the text with Javascript and then add a margin-right value? I really don't know where to start with this?

```<code>var anchorTag = document.querySelectorAll(".taxonomy a");
</code>```

NOTE - I don't have access to the HTML, so cannot wrap the letters in span elements etc. I need to find a way of selecting individual letters with JavaScript if this is possible.

答:
You could wrap each character in a span element with a custom class:

function wrapCharacters(element, prefix) {
  element.innerHTML = element.textContent
    .split('')
    .map(function(char, index) {
      return '' + char + '';
    })
    .join('');
}

document.querySelectorAll('.taxonomy a').forEach(function(element) {
  wrapCharacters(element);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.taxonomy a .span_3 { margin-right: 1px; }
.taxonomy a .span_4 { margin-right: 3px; }
.taxonomy a .span_5 { margin-right: 3px; }
.taxonomy a .span_6 { margin-right: 7px; }</code>```

   SampleText

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

<p>Now you can access the individual characters with CSS like this:</p>

```.taxonomy a .span_0 { margin-right: 1px; }
.taxonomy a .span_1 { margin-right: 4px; }
.taxonomy a .span_2 { margin-right: 2px; }
```

<p>ES6 Version</p>

```const wrapCharacters = (element, prefix) =>
  element.innerHTML = element.textContent
    .split('')
    .map((char, index) => `<span class="${prefix || 'span'}_${index}">${char}</span>`)
    .join('');
```

Body:
I have an anchor tag which is generated with Wordpress from the database, and the font the client uses has poor kerning. I need to be able to select individual letters on the anchor link and add a margin-right CSS value to certain letters in the generated text.

How would I go about selecting the 2nd, 3rd, 4th letter etc of the text with Javascript and then add a margin-right value? I really don't know where to start with this?

var anchorTag = document.querySelectorAll(".taxonomy a");

NOTE - I don't have access to the HTML, so cannot wrap the letters in span elements etc. I need to find a way of selecting individual letters with JavaScript if this is possible.

Body:
You could wrap each character in a span element with a custom class:

function wrapCharacters(element, prefix) {
  element.innerHTML = element.textContent
    .split('')
    .map(function(char, index) {
      return '<span class="' + (prefix || 'span') + '_' + index + '">' + char + '</span>';
    })
    .join('');
}

document.querySelectorAll('.taxonomy a').forEach(function(element) {
  wrapCharacters(element);
});

.taxonomy a .span_3 { margin-right: 1px; }
.taxonomy a .span_4 { margin-right: 3px; }
.taxonomy a .span_5 { margin-right: 3px; }
.taxonomy a .span_6 { margin-right: 7px; }

<div class="taxonomy">
   <a href="#">SampleText</a>
</div>

Now you can access the individual characters with CSS like this:

.taxonomy a .span_0 { margin-right: 1px; }
.taxonomy a .span_1 { margin-right: 4px; }
.taxonomy a .span_2 { margin-right: 2px; }

ES6 Version

const wrapCharacters = (element, prefix) =>
  element.innerHTML = element.textContent
    .split('')
    .map((char, index) => `<span class="${prefix || 'span'}_${index}">${char}</span>`)
    .join('');


问:
Spark submit: Table or view not found using jar
When I run HiveRead.java from intellij ide I can successfully run and get result. Then I created jar file ( It's a maven project ) , then I tried to run from IDE, it gave me

```<code>ClassLoaderResolver for class "" gave error on creation : {1}
</code>```

Then I looked at SO answers and found I had to add datanulcues jars, I did something like this

```<code>java -jar /home/saurab/sparkProjects/spark_hive/target/myJar-jar-with-dependencies.jar --jars jars/datanucleus-api-jdo-3.2.6.jar,jars/datanucleus-core-3.2.10.jar,jars/datanucleus-rdbms-3.2.9.jar,/home/saurab/hadoopec/hive/lib/mysql-connector-java-5.1.38.jar
</code>```

Then I got this error

```<code>org.datanucleus.exceptions.NucleusUserException: Persistence process has been specified to use a ClassLoaderResolver of name "datanucleus" yet this has not been found by the DataNucleus plugin mechanism. Please check your CLASSPATH and plugin specification.
</code>```

Somewhere I found I should do spark-submit. So I did like this

```<code>./bin/spark-submit --class HiveRead --master yarn  --jars jars/datanucleus-api-jdo-3.2.6.jar,jars/datanucleus-core-3.2.10.jar,jars/datanucleus-rdbms-3.2.9.jar,/home/saurab/hadoopec/hive/lib/mysql-connector-java-5.1.38.jar --files /home/saurab/hadoopec/spark/conf/hive-site.xml /home/saurab/sparkProjects/spark_hive/target/myJar-jar-with-dependencies.jar
</code>```

Now I get new type of error

```<code>Table or view not found: `bigmart`.`o_sales`;
</code>```

HELP ME !! :)

I have copied my hive-site.xml to /spark/conf, started hive-metastore service ( hiveserver2 --service metastore )

Here is HiveRead.Java code if anyone is interested.

答:
Spark session is not able to read the hive directory.

Provide the hive-site.xml file path with spark-submit command as below.

For hortonworks - file path /usr/hdp/current/spark2-client/conf/hive-site.xml

pass it as --files /usr/hdp/current/spark2-client/conf/hive-site.xml in spark-submit command.

Body:
When I run HiveRead.java from intellij ide I can successfully run and get result. Then I created jar file ( It's a maven project ) , then I tried to run from IDE, it gave me

ClassLoaderResolver for class "" gave error on creation : {1}

Then I looked at SO answers and found I had to add datanulcues jars, I did something like this

java -jar /home/saurab/sparkProjects/spark_hive/target/myJar-jar-with-dependencies.jar --jars jars/datanucleus-api-jdo-3.2.6.jar,jars/datanucleus-core-3.2.10.jar,jars/datanucleus-rdbms-3.2.9.jar,/home/saurab/hadoopec/hive/lib/mysql-connector-java-5.1.38.jar

Then I got this error

org.datanucleus.exceptions.NucleusUserException: Persistence process has been specified to use a ClassLoaderResolver of name "datanucleus" yet this has not been found by the DataNucleus plugin mechanism. Please check your CLASSPATH and plugin specification.

Somewhere I found I should do spark-submit. So I did like this

./bin/spark-submit --class HiveRead --master yarn  --jars jars/datanucleus-api-jdo-3.2.6.jar,jars/datanucleus-core-3.2.10.jar,jars/datanucleus-rdbms-3.2.9.jar,/home/saurab/hadoopec/hive/lib/mysql-connector-java-5.1.38.jar --files /home/saurab/hadoopec/spark/conf/hive-site.xml /home/saurab/sparkProjects/spark_hive/target/myJar-jar-with-dependencies.jar

Now I get new type of error

Table or view not found: `bigmart`.`o_sales`;

HELP ME !! :)

I have copied my hive-site.xml to /spark/conf, started hive-metastore service ( hiveserver2 --service metastore )

Here is HiveRead.Java code if anyone is interested.


问:
How to disable react navigation's stack navigator transition?
In React Native (iOS), React navigation's stack navigator has a default transition animation to move screens left or right based on the stack order. Is there any way to disable the transition animation?</p>

答:
React Navigation 5

{/* Screen level */}
<NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen
      name="HomeScreen"
      component={HomeScreen}
      options={{
        animationEnabled: false,
      }}
    />
  </Stack.Navigator>
</NavigationContainer>

{/* Whole navigation stack */}
<Stack.Navigator screenOptions={{ animationEnabled: false }}></Stack.Navigator>
```
<p><strong>React Navigation 6</strong></p>
<pre class="lang-js prettyprint-override"><code><Stack.Navigator screenOptions={{ animation: 'none' }}></Stack.Navigator>
</code>```

More options here https://reactnavigation.org/docs/stack-navigator/

Body:
React Navigation 5

{/* Screen level */}
<NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen
      name="HomeScreen"
      component={HomeScreen}
      options={{
        animationEnabled: false,
      }}
    />
  </Stack.Navigator>
</NavigationContainer>

{/* Whole navigation stack */}
<Stack.Navigator screenOptions={{ animationEnabled: false }}></Stack.Navigator>

React Navigation 6

<Stack.Navigator screenOptions={{ animation: 'none' }}></Stack.Navigator>

More options here https://reactnavigation.org/docs/stack-navigator/


问:
Issue with a while loop using GMP
I'm trying to code the extended Euclidean algorithm using the GMP library because I'm using large numbers. My algorithm is the basic one, just adapted for GMP numbers.

But I have a problem with my while loop. The code below is a minable reproducible example of my algorithm. I changed the content of the loop just for testing.

```<code>void euclid(mpz_t a, mpz_t b){

mpz_t r1, r2, u1, u2, v1, v2;

mpz_init_set_ui(u1, 1);
mpz_init_set_ui(v1, 0);
mpz_init_set_ui(u2, 0);
mpz_init_set_ui(v2, 1);

mpz_inits(r1, r2);

mpz_set(r1, a);
mpz_set(r2, b);

while(mpz_cmp_ui(r2, 0))
{
    gmp_printf("r2 : %Zd\n", r2);
    mpz_sub_ui(r2, r2, 1);

    mpz_t q;
    mpz_init(q);
}}
</code>```

The loop doesn't seem to be executed.

Looking for the origin of the problem, I tried to simplify the loop and I get a problem (the loop doesn't execute anymore) whenever I add the line "mpz_init(q);". I called my function euclid with a equal to mpz_t 33 and b equal to mpz_t 5.

答:
Problems like this ("I added a seemingly irrelevant variable/function call and the behaviour changed mysteriously") are almost always the result of Undefined Behaviour. In this case, the UB is in the line

```<code>mpz_inits(r1, r2);
</code>```

which should have been

```<code>mpz_inits(r1, r2, NULL);
</code>```

(See the docs). The list given to mpz_inits must be NULL-terminated so that the function knows when to stop; otherwise it will overwrite random memory.

Valgrind is an invaluable tool for uncovering this kind of issue.

Title: Issue with a while loop using GMP

Body:
I'm trying to code the extended Euclidean algorithm using the GMP library because I'm using large numbers. My algorithm is the basic one, just adapted for GMP numbers.

But I have a problem with my while loop. The code below is a minable reproducible example of my algorithm. I changed the content of the loop just for testing.

void euclid(mpz_t a, mpz_t b){

mpz_t r1, r2, u1, u2, v1, v2;

mpz_init_set_ui(u1, 1);
mpz_init_set_ui(v1, 0);
mpz_init_set_ui(u2, 0);
mpz_init_set_ui(v2, 1);

mpz_inits(r1, r2);

mpz_set(r1, a);
mpz_set(r2, b);

while(mpz_cmp_ui(r2, 0))
{
    gmp_printf("r2 : %Zd\n", r2);
    mpz_sub_ui(r2, r2, 1);

    mpz_t q;
    mpz_init(q);
}}

The loop doesn't seem to be executed.

Looking for the origin of the problem, I tried to simplify the loop and I get a problem (the loop doesn't execute anymore) whenever I add the line "mpz_init(q);". I called my function euclid with a equal to mpz_t 33 and b equal to mpz_t 5.

Body:
Problems like this ("I added a seemingly irrelevant variable/function call and the behaviour changed mysteriously") are almost always the result of Undefined Behaviour. In this case, the UB is in the line

mpz_inits(r1, r2);

which should have been

mpz_inits(r1, r2, NULL);

(See the docs). The list given to mpz_inits must be NULL-terminated so that the function knows when to stop; otherwise it will overwrite random memory.

Valgrind is an invaluable tool for uncovering this kind of issue.


问:
How to make the radio buttons not to change when switching the activities?
i've got an android app with 2 scenes. mainactivity and settings. When I go from the mainactivity to the settingsactivity and change a radiobutton and go back to the mainactivity and than again back, the button goes back to default. Thats because it always goes to the oncreate method. how do I have to place/write the Intent, that the radiobuttons don't go back to default?</p>

答:
Have you tried using a pair of onSaveInstanceState and onRestoreInstanceState? You can save the state of your radioButton in order to restore them later, when the app will reload your page.

Here are some helpful link about both methods from the official Android Developers website.
https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)
https://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)


问:
Flutter - How to use focusNode when a Widget/Page is Loaded
I am new to Flutter and I was creating a settings page for my flutter App. On settings page I am using formbuilder. I wanted to populate the form's fields from values store in Hive when the focus gets on Settings page (a tab in fact). Apparently focusNode is the way to go. However all the examples that I have seen are ficus on TextFields being focused, not the Widget or Page itself.

Can anyone please guide me with a good example how to do that? For example if a Page/Widget gets loaded on mobile screen a message should be displayed.

答:
You need to create a statefull widget first, and the state widget has a method called initState, which is called before the build method of that widget gets called. focusNode can only be used with Input widgets</p>

```<code>class SettingsScreen extends StatefulWidget {
  @override
  _SettingsScreenState createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {

  bool _showDialog = false;
  @override
  void initState() {
    // TODO: implement initState

    // do your thing, perhaps call showDialog ?
     _showDialog=  true;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    if(_showDialog) {
      showDilaog()
   }

    return Container(

    );
  }
}

</code>```

Body:
You need to create a statefull widget first, and the state widget has a method called initState, which is called before the build method of that widget gets called. focusNode can only be used with Input widgets

class SettingsScreen extends StatefulWidget {
  @override
  _SettingsScreenState createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {

  bool _showDialog = false;
  @override
  void initState() {
    // TODO: implement initState

    // do your thing, perhaps call showDialog ?
     _showDialog=  true;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    if(_showDialog) {
      showDilaog()
   }

    return Container(

    );
  }
}


问:
Proper ways to set the path of my app in Python
I have a question in how to properly create a path in Python (Python 3.x).

I developed a small scraping app in Python with the following directory structure.

root
├── Dockerfile
├── README.md
├── tox.ini
├── src
│   └── myapp
│       ├── __init__.py
│       ├── do_something.py
│       └── do_something_else.py
└── tests
    ├── __init__.py
    ├──  test_do_something.py
    └──  test_do_something_else.py
```

<p>When I want to run my code, I can go to the src directory and do with
<code>python do_something.py</code>
But, because do_something.py has an import statement from do_something_else.py, it fails like:</p>

<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
  File "src/myapp/do_something.py", line 1, in <module>
    from src.myapp.do_something_else import do_it
ModuleNotFoundError: No module named 'src'
</code>```

So, I eventually decided to use the following command to specify the python path:
PYTHONPATH=../../ python do_something.py
to make sure that the path is seen.

But, what are the better ways to feed the path so that my app can run?
I want to know this because when I run pytest via tox, the directory that I would run the command tox would be at the root so that tox.ini is seen by tox package. If I do that, then I most likely run into a similar problem due to the Python path not properly set.

Questions I want to ask specifically are:

where should I run my main code when creating my own project like this? root as like python src/myapp/do_something.py? Or, go to the src/myapp directory and run like python do_something.py?

once, the directory where I should execute my program is determined, what is the correct way to import modules from other py file? Is it ok to use from src.myapp.do_something_else import do_it (this means I must add path from src directory)? Or, different way to import?

What are ways I can have my Python recognize the path? I am aware there are several ways to make the pass accessible as below:

a. write export PYTHONPATH=<path_of_my_choice>:$PYTHONPATH to make the
path accessible temporarily, or write that line in my .bashrc to make it permanent (but it's hard to reproduce when I want to automate creating Python environment via ansible or other automation tools)

b. write import sys; sys.path.append(<root>) to have the root as an accessible path

c. use pytest-pythonpath package (but this is not really a generic answer)

Thank you so much for your inputs!

my environment

OS: MacOS and Amazon Linux 2
Python Version: 3.7
Dependency in Python: pytest, tox
```

答:
Two simple steps should make it happen. Python experts can comment if this is a good way to do it (especially going by the concluding caution raised towards the end of this post).

I would have done it like below.

First I would have put a "__init__.py" in root so that hierarchy looks like below. This way python will treat the folder as a package.

root
├── Dockerfile
├── README.md
├── tox.ini
├── __init__.py
├── src
│   └── myapp
│       ├── __init__.py
│       ├── do_something.py
│       └── do_something_else.py
└── tests
    ├── __init__.py
    ├──  test_do_something.py
    └──  test_do_something_else.py
```

<p>Then in "do_something.py", I would have added these lines at the top. In the second line please put the full path to the "root" directory.</p>

<pre class="lang-py prettyprint-override"><code>import sys
sys.path += ['/home/SomeUserName/SomeFolderPath/root']
from  src.myapp.do_something_else import do_it
</code>```

Please note that the second line will essentially modify the sys.path by adding the root folder path (I guess until the interpreter quits). If this is not what you can afford then I am sorry.

Body:
I have a question in how to properly create a path in Python (Python 3.x).

I developed a small scraping app in Python with the following directory structure.

root
├── Dockerfile
├── README.md
├── tox.ini
├── src
│   └── myapp
│       ├── __init__.py
│       ├── do_something.py
│       └── do_something_else.py
└── tests
    ├── __init__.py
    ├──  test_do_something.py
    └──  test_do_something_else.py

When I want to run my code, I can go to the src directory and do with
python do_something.py
But, because do_something.py has an import statement from do_something_else.py, it fails like:

Traceback (most recent call last):
  File "src/myapp/do_something.py", line 1, in <module>
    from src.myapp.do_something_else import do_it
ModuleNotFoundError: No module named 'src'

So, I eventually decided to use the following command to specify the python path:
PYTHONPATH=../../ python do_something.py
to make sure that the path is seen.

But, what are the better ways to feed the path so that my app can run?
I want to know this because when I run pytest via tox, the directory that I would run the command tox would be at the root so that tox.ini is seen by tox package. If I do that, then I most likely run into a similar problem due to the Python path not properly set.

Questions I want to ask specifically are:

where should I run my main code when creating my own project like this? root as like python src/myapp/do_something.py? Or, go to the src/myapp directory and run like python do_something.py?

once, the directory where I should execute my program is determined, what is the correct way to import modules from other py file? Is it ok to use from src.myapp.do_something_else import do_it (this means I must add path from src directory)? Or, different way to import?

What are ways I can have my Python recognize the path? I am aware there are several ways to make the pass accessible as below:

a. write export PYTHONPATH=<path_of_my_choice>:$PYTHONPATH to make the
path accessible temporarily, or write that line in my .bashrc to make it permanent (but it's hard to reproduce when I want to automate creating Python environment via ansible or other automation tools)

b. write import sys; sys.path.append(<root>) to have the root as an accessible path

c. use pytest-pythonpath package (but this is not really a generic answer)

Thank you so much for your inputs!

my environment

OS: MacOS and Amazon Linux 2
Python Version: 3.7
Dependency in Python: pytest, tox

Body:
Two simple steps should make it happen. Python experts can comment if this is a good way to do it (especially going by the concluding caution raised towards the end of this post).

I would have done it like below.

First I would have put a "__init__.py" in root so that hierarchy looks like below. This way python will treat the folder as a package.

root
├── Dockerfile
├── README.md
├── tox.ini
├── __init__.py
├── src
│   └── myapp
│       ├── __init__.py
│       ├── do_something.py
│       └── do_something_else.py
└── tests
    ├── __init__.py
    ├──  test_do_something.py
    └──  test_do_something_else.py

Then in "do_something.py", I would have added these lines at the top. In the second line please put the full path to the "root" directory.

import sys
sys.path += ['/home/SomeUserName/SomeFolderPath/root']
from  src.myapp.do_something_else import do_it

Please note that the second line will essentially modify the sys.path by adding the root folder path (I guess until the interpreter quits). If this is not what you can afford then I am sorry.


答:
EDIT:</p>

```<code>find . -maxdepth 1 -type d ! -name \\.| sort | tac | sed -e '1,10d' | xargs rm -rf
</code>```

Title: Linux - Save only recent 10 folders and delete the rest

Body:
I have a folder that contains versions of my application, each time I upload a new version a new sub-folder is created for it, the sub-folder name is the current timestamp, here is a printout of the main folder used (ls -l |grep ^d):

drwxrwxr-x 7 root root 4096 2011-03-31 16:18 20110331161649
drwxrwxr-x 7 root root 4096 2011-03-31 16:21 20110331161914
drwxrwxr-x 7 root root 4096 2011-03-31 16:53 20110331165035
drwxrwxr-x 7 root root 4096 2011-03-31 16:59 20110331165712
drwxrwxr-x 7 root root 4096 2011-04-03 20:18 20110403201607
drwxrwxr-x 7 root root 4096 2011-04-03 20:38 20110403203613
drwxrwxr-x 7 root root 4096 2011-04-04 14:39 20110405143725
drwxrwxr-x 7 root root 4096 2011-04-06 15:24 20110406151805
drwxrwxr-x 7 root root 4096 2011-04-06 15:36 20110406153157
drwxrwxr-x 7 root root 4096 2011-04-06 16:02 20110406155913
drwxrwxr-x 7 root root 4096 2011-04-10 21:10 20110410210928
drwxrwxr-x 7 root root 4096 2011-04-10 21:50 20110410214939
drwxrwxr-x 7 root root 4096 2011-04-10 22:15 20110410221414
drwxrwxr-x 7 root root 4096 2011-04-11 22:19 20110411221810
drwxrwxr-x 7 root root 4096 2011-05-01 21:30 20110501212953
drwxrwxr-x 7 root root 4096 2011-05-01 23:02 20110501230121
drwxrwxr-x 7 root root 4096 2011-05-03 21:57 20110503215252
drwxrwxr-x 7 root root 4096 2011-05-06 16:17 20110506161546
drwxrwxr-x 7 root root 4096 2011-05-11 10:00 20110511095709
drwxrwxr-x 7 root root 4096 2011-05-11 10:13 20110511100938
drwxrwxr-x 7 root root 4096 2011-05-12 14:34 20110512143143
drwxrwxr-x 7 root root 4096 2011-05-13 22:13 20110513220824
drwxrwxr-x 7 root root 4096 2011-05-14 22:26 20110514222548
drwxrwxr-x 7 root root 4096 2011-05-14 23:03 20110514230258

I'm looking for a command that will leave the last 10 versions (sub-folders) and deletes the rest.

Any thoughts?

Body:
EDIT:

find . -maxdepth 1 -type d ! -name \\.| sort | tac | sed -e '1,10d' | xargs rm -rf


问:
.htaccess redirect with custom url change
I want to redirect posts within the same domain.

The old URL structure is

```<code>/posts/category/340-post-name-with-öäü.html
</code>```

and I want to redirect to

```<code>/category/post-name-without-id-and-changed-oeaeue
</code>```

(The 340 is an -id which is unique and could also be 2 or 20.)

Example:

```<code>/posts/onpage/374-fünf-strategien.html
</code>```

to

```<code>/onpage/fuenf-strategien
</code>```

Is that possible with a .htaccess redirect?

答:
Since the id is "unique" then that would seem to be all you need to match.

For example:

```<code>RedirectMatch ^/posts/category/340- /category/post-name-without-id-and-changed-oeaeue
</code>```

If, however, you are looking for a many-to-many generalised redirect then there's simply not enough information here to perform the redirect in .htaccess. For instance, how do you get from post-name-with to post-name-without-id-and-changed - specifically with regards to the "and-changed" bit?

Any redirect you perform in .htaccess can only look at elements of the original request. If the information is not there to begin with (in some form) then you can't magically use it in the target of the redirect without hardcoding it. (If you have access to the server-config then you can configure RewriteMaps - essentially a "lookup-table" to help with the redirect. But otherwise, .htaccess alone does not have this ability.)

If you have many redirects of this nature then you are better off performing the redirect in your server-side code (application logic), instead of .htaccess.

UPDATE: From your second example: /posts/onpage/374-fünf-strategien.html to /onpage/fuenf-strategien. Again, there's no logical process to get from fünf to fuenf without hardcoding the replacement.

If there is a finite series of replacements, eg. öäü to oeaeue and fünf to fuenf then you could apply these in .htaccess before removing the .html extension, ID, and changing the URL-path, etc. However, if you are adding arbitray text on a per URL basis (eg. the and-changed bit above) then you are back to doing this one URL at a time.

Body:
I want to redirect posts within the same domain.

The old URL structure is

/posts/category/340-post-name-with-öäü.html

and I want to redirect to

/category/post-name-without-id-and-changed-oeaeue

(The 340 is an -id which is unique and could also be 2 or 20.)

Example:

/posts/onpage/374-fünf-strategien.html

to

/onpage/fuenf-strategien

Is that possible with a .htaccess redirect?

Body:
Since the id is "unique" then that would seem to be all you need to match.

For example:

RedirectMatch ^/posts/category/340- /category/post-name-without-id-and-changed-oeaeue

If, however, you are looking for a many-to-many generalised redirect then there's simply not enough information here to perform the redirect in .htaccess. For instance, how do you get from post-name-with to post-name-without-id-and-changed - specifically with regards to the "and-changed" bit?

Any redirect you perform in .htaccess can only look at elements of the original request. If the information is not there to begin with (in some form) then you can't magically use it in the target of the redirect without hardcoding it. (If you have access to the server-config then you can configure RewriteMaps - essentially a "lookup-table" to help with the redirect. But otherwise, .htaccess alone does not have this ability.)

If you have many redirects of this nature then you are better off performing the redirect in your server-side code (application logic), instead of .htaccess.

UPDATE: From your second example: /posts/onpage/374-fünf-strategien.html to /onpage/fuenf-strategien. Again, there's no logical process to get from fünf to fuenf without hardcoding the replacement.

If there is a finite series of replacements, eg. öäü to oeaeue and fünf to fuenf then you could apply these in .htaccess before removing the .html extension, ID, and changing the URL-path, etc. However, if you are adding arbitray text on a per URL basis (eg. the and-changed bit above) then you are back to doing this one URL at a time.


问:
Vim - add one line above the fold to the folding
When I am coding in vim, I use set foldmethod=syntax which folds my code.
It looks something like this then:

How can I add the line above the { to the fold? So that it would look something like this:

So the idea is that it (always) takes the line above the fold into the fold.
How can I make this happen?

答:
This needs a custom fold expression (h fold-expr) indenpendently from:

foldtext <-  you want to fold one more line

foldignore <- you still want to fold { and } whatever the indent

In your vimrc:

```<code>" Callback: Fold level <- next line indent
function! FoldMethod(lnum)
    let l:indent = max([indent(a:lnum+1), indent(a:lnum)])
    return l:indent / &shiftwidth
endfunction

set foldmethod=expr
set foldexpr=FoldMethod(v:lnum)
</code>```

Body:
This needs a custom fold expression (h fold-expr) indenpendently from:

foldtext <-  you want to fold one more line

foldignore <- you still want to fold { and } whatever the indent

In your vimrc:

" Callback: Fold level <- next line indent
function! FoldMethod(lnum)
    let l:indent = max([indent(a:lnum+1), indent(a:lnum)])
    return l:indent / &shiftwidth
endfunction

set foldmethod=expr
set foldexpr=FoldMethod(v:lnum)


问:
Make a simple search algorithm more elegant
```<code>// temp data
var array = [1,2,function() { }, 3, function() { }];
var cb = function() { console.log("foo"); }

var found = false;
console.log(_.map(array, function(val) {
    if (_.isFunction(val) && !found) {
        return found = true, _.compose(cb, val);
    }
    return val;
}));
</code>```

This loops through the array and turns the first function it finds into a composed function.

I hate that found = false variable / counter. How do I get rid of it?

As an algorithm.

```<code>let found be 0
map value in array
    if value satisfies condition and found is 0
        let found be 1
        return mutate(value)
    else
        return value
</code>```

Update

Using a for loop

```<code>for (var i = 0; i < array.length; i++) {
    if (_.isFunction(array[i])) {
        array[i] = _.compose(cb, array[i]);
        break;
    }
}
</code>```

_.map, _, _.isFunction, _.compose

答:
I don't know if this answers your need for elegance, but it seems to me like _.each() or forEach is wasting extra loops after the item has been found. With a traditional for or while loop, you could call break at that point. Not a big deal with a small array, but it could become an issue for a larger array or a complex condition check. If you want to avoid the constant array[x] references, you could get a little fancier than the obvious option:

```<code>for (var val, x=0; x<array.length; val=array[++x]) {
    if (_.isFunction(val)) {
        array[x] = _.compose(cb, val);
        break;
    }
}
</code>```

Body:
// temp data
var array = [1,2,function() { }, 3, function() { }];
var cb = function() { console.log("foo"); }

var found = false;
console.log(_.map(array, function(val) {
    if (_.isFunction(val) && !found) {
        return found = true, _.compose(cb, val);
    }
    return val;
}));

This loops through the array and turns the first function it finds into a composed function.

I hate that found = false variable / counter. How do I get rid of it?

As an algorithm.

let found be 0
map value in array
    if value satisfies condition and found is 0
        let found be 1
        return mutate(value)
    else
        return value

Update

Using a for loop

for (var i = 0; i < array.length; i++) {
    if (_.isFunction(array[i])) {
        array[i] = _.compose(cb, array[i]);
        break;
    }
}

_.map, _, _.isFunction, _.compose

Body:
I don't know if this answers your need for elegance, but it seems to me like _.each() or forEach is wasting extra loops after the item has been found. With a traditional for or while loop, you could call break at that point. Not a big deal with a small array, but it could become an issue for a larger array or a complex condition check. If you want to avoid the constant array[x] references, you could get a little fancier than the obvious option:

for (var val, x=0; x<array.length; val=array[++x]) {
    if (_.isFunction(val)) {
        array[x] = _.compose(cb, val);
        break;
    }
}


问:
PySpark error: AttributeError: 'NoneType' object has no attribute '_jvm'
I have timestamp dataset which is in format of

And I have written a udf in pyspark to process this dataset and return as Map of key values. But am getting below error message.

Dataset:df_ts_list

```<code>+--------------------+
|             ts_list|
+--------------------+
|[1477411200, 1477...|
|[1477238400, 1477...|
|[1477022400, 1477...|
|[1477224000, 1477...|
|[1477256400, 1477...|
|[1477346400, 1476...|
|[1476986400, 1477...|
|[1477321200, 1477...|
|[1477306800, 1477...|
|[1477062000, 1477...|
|[1477249200, 1477...|
|[1477040400, 1477...|
|[1477090800, 1477...|
+--------------------+
</code>```

Pyspark UDF:

```<code>>>> def on_time(ts_list):
...     import sys
...     import os
...     sys.path.append('/usr/lib/python2.7/dist-packages')
...     os.system("sudo apt-get install python-numpy -y")
...     import numpy as np
...     import datetime
...     import time
...     from datetime import timedelta
...     ts = np.array(ts_list)
...     if ts.size == 0:
...             count = 0
...             duration = 0
...             st = time.mktime(datetime.now())
...             ymd = str(datetime.fromtimestamp(st).date())
...     else:
...             ts.sort()
...             one_tag = []
...             start = float(ts[0])
...             for i in range(len(ts)):
...                     if i == (len(ts)) - 1:
...                             end = float(ts[i])
...                             a_round = [start, end]
...                             one_tag.append(a_round)
...                     else:
...                             diff = (datetime.datetime.fromtimestamp(float(ts[i+1])) - datetime.datetime.fromtimestamp(float(ts[i])))
...                             if abs(diff.total_seconds()) > 3600:
...                                     end = float(ts[i])
...                                     a_round = [start, end]
...                                     one_tag.append(a_round)
...                                     start = float(ts[i+1])
...             one_tag = [u for u in one_tag if u[1] - u[0] > 300]
...             count = int(len(one_tag))
...             duration = int(np.diff(one_tag).sum())
...             ymd = str(datetime.datetime.fromtimestamp(time.time()).date())
...     return {'count':count,'duration':duration, 'ymd':ymd}
</code>```

Pyspark code:

```<code>>>> on_time=udf(on_time, MapType(StringType(),StringType()))
>>> df_ts_list.withColumn("one_tag", on_time("ts_list")).select("one_tag").show()
</code>```

Error:

```<code>Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/lib/spark/python/pyspark/worker.py", line 172, in main
    process()
  File "/usr/lib/spark/python/pyspark/worker.py", line 167, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/lib/spark/python/pyspark/worker.py", line 106, in <lambda>
    func = lambda _, it: map(mapper, it)
  File "/usr/lib/spark/python/pyspark/worker.py", line 92, in <lambda>
    mapper = lambda a: udf(*a)
  File "/usr/lib/spark/python/pyspark/worker.py", line 70, in <lambda>
    return lambda *a: f(*a)
  File "<stdin>", line 27, in on_time
  File "/usr/lib/spark/python/pyspark/sql/functions.py", line 39, in _
    jc = getattr(sc._jvm.functions, name)(col._jc if isinstance(col, Column) else col)
AttributeError: 'NoneType' object has no attribute '_jvm'
</code>```

Any help would be appreciated!

答:
Just to be clear the problem a lot of guys are having is stemming from a single bad programming style. That is from blah import *

When you guys do

from pyspark.sql.functions import *
```

<p>you overwrite <em><strong>a lot</strong></em> of python builtins functions. I strongly recommending importing functions like</p>

<pre class="lang-py prettyprint-override"><code>import pyspark.sql.functions as f
# or
import pyspark.sql.functions as pyf
</code>```

Body:
I have timestamp dataset which is in format of

And I have written a udf in pyspark to process this dataset and return as Map of key values. But am getting below error message.

Dataset:df_ts_list

+--------------------+
|             ts_list|
+--------------------+
|[1477411200, 1477...|
|[1477238400, 1477...|
|[1477022400, 1477...|
|[1477224000, 1477...|
|[1477256400, 1477...|
|[1477346400, 1476...|
|[1476986400, 1477...|
|[1477321200, 1477...|
|[1477306800, 1477...|
|[1477062000, 1477...|
|[1477249200, 1477...|
|[1477040400, 1477...|
|[1477090800, 1477...|
+--------------------+

Pyspark UDF:

>>> def on_time(ts_list):
...     import sys
...     import os
...     sys.path.append('/usr/lib/python2.7/dist-packages')
...     os.system("sudo apt-get install python-numpy -y")
...     import numpy as np
...     import datetime
...     import time
...     from datetime import timedelta
...     ts = np.array(ts_list)
...     if ts.size == 0:
...             count = 0
...             duration = 0
...             st = time.mktime(datetime.now())
...             ymd = str(datetime.fromtimestamp(st).date())
...     else:
...             ts.sort()
...             one_tag = []
...             start = float(ts[0])
...             for i in range(len(ts)):
...                     if i == (len(ts)) - 1:
...                             end = float(ts[i])
...                             a_round = [start, end]
...                             one_tag.append(a_round)
...                     else:
...                             diff = (datetime.datetime.fromtimestamp(float(ts[i+1])) - datetime.datetime.fromtimestamp(float(ts[i])))
...                             if abs(diff.total_seconds()) > 3600:
...                                     end = float(ts[i])
...                                     a_round = [start, end]
...                                     one_tag.append(a_round)
...                                     start = float(ts[i+1])
...             one_tag = [u for u in one_tag if u[1] - u[0] > 300]
...             count = int(len(one_tag))
...             duration = int(np.diff(one_tag).sum())
...             ymd = str(datetime.datetime.fromtimestamp(time.time()).date())
...     return {'count':count,'duration':duration, 'ymd':ymd}

Pyspark code:

>>> on_time=udf(on_time, MapType(StringType(),StringType()))
>>> df_ts_list.withColumn("one_tag", on_time("ts_list")).select("one_tag").show()

Error:

Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/lib/spark/python/pyspark/worker.py", line 172, in main
    process()
  File "/usr/lib/spark/python/pyspark/worker.py", line 167, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/usr/lib/spark/python/pyspark/worker.py", line 106, in <lambda>
    func = lambda _, it: map(mapper, it)
  File "/usr/lib/spark/python/pyspark/worker.py", line 92, in <lambda>
    mapper = lambda a: udf(*a)
  File "/usr/lib/spark/python/pyspark/worker.py", line 70, in <lambda>
    return lambda *a: f(*a)
  File "<stdin>", line 27, in on_time
  File "/usr/lib/spark/python/pyspark/sql/functions.py", line 39, in _
    jc = getattr(sc._jvm.functions, name)(col._jc if isinstance(col, Column) else col)
AttributeError: 'NoneType' object has no attribute '_jvm'

Any help would be appreciated!

Body:
Just to be clear the problem a lot of guys are having is stemming from a single bad programming style. That is from blah import *

When you guys do

from pyspark.sql.functions import *

you overwrite a lot of python builtins functions. I strongly recommending importing functions like

import pyspark.sql.functions as f
# or
import pyspark.sql.functions as pyf


问:
Debounce event/command in MVVM pattern
I am in the process of building a universal windows application using Caliburn.Micro, unfortunately due to certain hardware limitations we are needing to target Windows 10 1607 so cannot implement any packages with dependencies on .NET Standard / UWP 16299, this includes ReactiveUI.

In this particular scenario, I have a view-model first approach which generates a map (and some other resources), these are then bound to a mapview in the XAML view. Ideally, I want to trigger a process when the map is moved via the ViewpointChanged event.

View Model

```<code>public class ExampleViewModel : Screen
{
    public ExampleViewModel()
    {
        Map = new Map();
    }

    public Map Map { get; set; }
    public BindableCollection<MapItems> MapItems { get; set; }

    private UpdateMapItems(Envelope visibleArea)
    {
        // The visibleArea param will include the current viewpoint of the map view
        // This method will effectively generate the appropriate map items based on the current coordinates
    }
}
</code>```

View

```<code>...
<MapView x:Name="MapView" Map="{Binding Map}" cal:Message.Attach="[Event ViewpointChanged] = [Action UpdateMapItems(MapView.VisibleArea.Extent)]" />
...
</code>```

Now this technically works but has a major flaw in that each movement of the map fires the ViewpointChanged event several times (similar effect to that of OnMouseMove for example).

Ideally I'd like to be able to throttle/debounce this event so that the map items are only processed when the view hasn't been moved for say 300ms.

I found an article that involved implementing a DispatcherTimer however elements of this code such as the DispatcherPriority and Dispatcher don't seem to be available in UWP so unless alternatives exist, I don't think this will work.

I have had a look at System.Reactive but this seemed exceptionally complicated for what I'm looking to achieve.

Any pointers would be very appreciated!

答:
You could do this in a couple of ways.

Reactive Extensions

The desired behavior can be achieved using the Throttle operator.

Observable
.FromEventPattern<EventArgs>(MapView, nameof(ViewpointChanged));
.Throttle(TimeSpan.FromMilliSeconds(300));
.Subscribe(eventPattern => vm.UpdateMapItems(eventPattern.Sender.VisibleArea.Extent));
```

<p>When using <code>FromEventPattern</code> we're mapping events to instances of EventPattern, which includes the <code>Sender</code> (source) of the event.</p>

<p>I tested by subscribing to a <code>UIElement</code>'s <code>PointerMoved</code> event. Which triggers <code>HandleEvent</code> multiple times if we keep moving. With <code>Throttle</code>, however, the event handler is executed only once. This is when the interval has passed <em>after</em> we stop moving.</p>

<p>MainPage.xaml</p>

<pre class="lang-xml prettyprint-override"><code><Page
    x:Class="..."
    ...
    >
    <Grid>
        <Button x:Name="MyUIElement" Content="Throttle Surface"
                Height="250" Width="250" HorizontalAlignment="Center"/>
    </Grid>
</Page>
</code>```

MainPage.xaml.cs

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

        Observable
            .FromEventPattern<PointerRoutedEventArgs>(MyUIElement, nameof(UIElement.PointerMoved))
            .Throttle(TimeSpan.FromMilliseconds(300))
            .Subscribe(eventPattern => HandleEvent(eventPattern.Sender, eventPattern.EventArgs));
    }

    private void HandleEvent(object source, PointerRoutedEventArgs args)
    {
        Debug.WriteLine("Pointer Moved");
    }
}
```

<ol start="2">
<li>Something custom</li>
</ol>

<p>Our custom <code>Throttle</code> class keeps track of the last <code>sender</code> and <code>args</code> that have been processed. Processed as in "passed to <code>Throttle</code> for processing". Only when the timer elapses, and no other events have occurred, is the <code>eventHandler</code> (passed as a constructor argument) actually executed.</p>

<pre class="lang-cs prettyprint-override"><code>public class Throttle<TEventArgs>
{
    private readonly DispatcherTimer _timer;
    private object _lastSender;
    private TEventArgs _lastEventArgs;

    public Throttle(EventHandler<TEventArgs> eventHandler, TimeSpan interval)
    {
        _timer = new DispatcherTimer
        {
            Interval = interval
        };
        _timer.Tick += (s, e) =>
        {
            _timer.Stop();
            eventHandler(_lastSender, _lastEventArgs);
        };
    }

    public void ProcessEvent(object sender, TEventArgs args)
    {
        _timer.Stop();
        _timer.Start();

        _lastSender = sender;
        _lastEventArgs = args;
    }
}
</code>```

MainPage.xaml.cs

public sealed partial class MainPage : Page
{
    private readonly Throttle<PointerRoutedEventArgs> _throttle;

    public MainPage()
    {
        this.InitializeComponent();

        var interval = TimeSpan.FromMilliseconds(300);
        _throttle = new Throttle<PointerRoutedEventArgs>(HandleEvent, interval);
        MyUIElement.PointerMoved += (sender, e) => _throttle.ProcessEvent(sender, e);
    }

    private void HandleEvent(object sender, PointerRoutedEventArgs e)
    {
        Debug.WriteLine("Pointer Moved");
    }
}
```

Update

I'm struggling to work out how everything fits together in an MVVM environment. The logic that needs to be triggered by the event is contained within the ViewModel but the View and ViewModel should be entirely separate.

There's a couple things I'd like to mention:

You're right about the need for separation of concerns, but a lot of devs are unclear of what that exactly entails. The view model should be completely unaware of who's listening, there's no doubt about that. But the view is dependent on the view model to get its data, so it's okay for the view to know about the view model. The problem is more about doing so in a loosely coupled way, ie. using bindings and contracts instead of directly accessing view model members.

That's why I'm not particularly fond of Caliburn's Actions. With cal:Message.Attach there's no contract (eg. ICommand) to decouple view syntax from the view model's. Of course, there are bindings in play, so you still get decoupled MVVM layers.

Long story short, there's a reason people choose ReactiveUI over Rx.NET for WPF development.
From the view's code behind (_.xaml.cs) it gives you access to:

The backing ViewModel

A binding system to keep it all loosely coupled

And, of course, ReactiveCommands, which would also come in handy in your use case.

Final thoughts, if your view has the same lifetime as your view model (ie. they get disposed together), you could be pragmatic about it and get the view model through the DataContext of your view.

Title: Debounce event/command in MVVM pattern

Body:
I am in the process of building a universal windows application using Caliburn.Micro, unfortunately due to certain hardware limitations we are needing to target Windows 10 1607 so cannot implement any packages with dependencies on .NET Standard / UWP 16299, this includes ReactiveUI.

In this particular scenario, I have a view-model first approach which generates a map (and some other resources), these are then bound to a mapview in the XAML view. Ideally, I want to trigger a process when the map is moved via the ViewpointChanged event.

View Model

public class ExampleViewModel : Screen
{
    public ExampleViewModel()
    {
        Map = new Map();
    }

    public Map Map { get; set; }
    public BindableCollection<MapItems> MapItems { get; set; }

    private UpdateMapItems(Envelope visibleArea)
    {
        // The visibleArea param will include the current viewpoint of the map view
        // This method will effectively generate the appropriate map items based on the current coordinates
    }
}

View

...
<MapView x:Name="MapView" Map="{Binding Map}" cal:Message.Attach="[Event ViewpointChanged] = [Action UpdateMapItems(MapView.VisibleArea.Extent)]" />
...

Now this technically works but has a major flaw in that each movement of the map fires the ViewpointChanged event several times (similar effect to that of OnMouseMove for example).

Ideally I'd like to be able to throttle/debounce this event so that the map items are only processed when the view hasn't been moved for say 300ms.

I found an article that involved implementing a DispatcherTimer however elements of this code such as the DispatcherPriority and Dispatcher don't seem to be available in UWP so unless alternatives exist, I don't think this will work.

I have had a look at System.Reactive but this seemed exceptionally complicated for what I'm looking to achieve.

Any pointers would be very appreciated!

Body:
You could do this in a couple of ways.

Reactive Extensions

The desired behavior can be achieved using the Throttle operator.

Observable
.FromEventPattern<EventArgs>(MapView, nameof(ViewpointChanged));
.Throttle(TimeSpan.FromMilliSeconds(300));
.Subscribe(eventPattern => vm.UpdateMapItems(eventPattern.Sender.VisibleArea.Extent));

When using FromEventPattern we're mapping events to instances of EventPattern, which includes the Sender (source) of the event.

I tested by subscribing to a UIElement's PointerMoved event. Which triggers HandleEvent multiple times if we keep moving. With Throttle, however, the event handler is executed only once. This is when the interval has passed after we stop moving.

MainPage.xaml

<Page
    x:Class="..."
    ...
    >
    <Grid>
        <Button x:Name="MyUIElement" Content="Throttle Surface"
                Height="250" Width="250" HorizontalAlignment="Center"/>
    </Grid>
</Page>

MainPage.xaml.cs

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

        Observable
            .FromEventPattern<PointerRoutedEventArgs>(MyUIElement, nameof(UIElement.PointerMoved))
            .Throttle(TimeSpan.FromMilliseconds(300))
            .Subscribe(eventPattern => HandleEvent(eventPattern.Sender, eventPattern.EventArgs));
    }

    private void HandleEvent(object source, PointerRoutedEventArgs args)
    {
        Debug.WriteLine("Pointer Moved");
    }
}

Something custom

Our custom Throttle class keeps track of the last sender and args that have been processed. Processed as in "passed to Throttle for processing". Only when the timer elapses, and no other events have occurred, is the eventHandler (passed as a constructor argument) actually executed.

public class Throttle<TEventArgs>
{
    private readonly DispatcherTimer _timer;
    private object _lastSender;
    private TEventArgs _lastEventArgs;

    public Throttle(EventHandler<TEventArgs> eventHandler, TimeSpan interval)
    {
        _timer = new DispatcherTimer
        {
            Interval = interval
        };
        _timer.Tick += (s, e) =>
        {
            _timer.Stop();
            eventHandler(_lastSender, _lastEventArgs);
        };
    }

    public void ProcessEvent(object sender, TEventArgs args)
    {
        _timer.Stop();
        _timer.Start();

        _lastSender = sender;
        _lastEventArgs = args;
    }
}

MainPage.xaml.cs

public sealed partial class MainPage : Page
{
    private readonly Throttle<PointerRoutedEventArgs> _throttle;

    public MainPage()
    {
        this.InitializeComponent();

        var interval = TimeSpan.FromMilliseconds(300);
        _throttle = new Throttle<PointerRoutedEventArgs>(HandleEvent, interval);
        MyUIElement.PointerMoved += (sender, e) => _throttle.ProcessEvent(sender, e);
    }

    private void HandleEvent(object sender, PointerRoutedEventArgs e)
    {
        Debug.WriteLine("Pointer Moved");
    }
}

Update

I'm struggling to work out how everything fits together in an MVVM environment. The logic that needs to be triggered by the event is contained within the ViewModel but the View and ViewModel should be entirely separate.

There's a couple things I'd like to mention:

You're right about the need for separation of concerns, but a lot of devs are unclear of what that exactly entails. The view model should be completely unaware of who's listening, there's no doubt about that. But the view is dependent on the view model to get its data, so it's okay for the view to know about the view model. The problem is more about doing so in a loosely coupled way, ie. using bindings and contracts instead of directly accessing view model members.

That's why I'm not particularly fond of Caliburn's Actions. With cal:Message.Attach there's no contract (eg. ICommand) to decouple view syntax from the view model's. Of course, there are bindings in play, so you still get decoupled MVVM layers.

Long story short, there's a reason people choose ReactiveUI over Rx.NET for WPF development.
From the view's code behind (_.xaml.cs) it gives you access to:

The backing ViewModel

A binding system to keep it all loosely coupled

And, of course, ReactiveCommands, which would also come in handy in your use case.

Final thoughts, if your view has the same lifetime as your view model (ie. they get disposed together), you could be pragmatic about it and get the view model through the DataContext of your view.


问:
How to create a new list item with FLOWR and XQuery?
I'm looking to select non-numerical data from an XML file towards shredding it into database columns, or at least an xmltable-like structure.  This FLWOR gives a somewhat useful result:

```<code>xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

<ul>
{
for $foo  in db:open("foo")
return <li>{$foo//text()[not(matches(., '[0-9]'))]}</li>

}
</ul>
</code>```

However, it outputs all results into a single li tag, like:

 a b c d

Preferred output would be of the form:

a

b

Most likely the data is problematic in some way, because a slightly different FLOWR:

```<code>xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

for $foo in db:open("foo")
return $foo//text()[not(matches(., '[0-9]'))]
</code>```

certainly outputs each non-numerical string on a new line.  How can I output this into a list?

An excerpt of the data:

```<code> <table:table-column table:style-name="co1" table:default-cell-style-name="ce17"/>
  <table:table-row table:style-name="ro1">
    <table:table-cell table:style-name="ce15" office:value-type="string" calcext:value-type="string">
      <text:p>John Smith</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro2">
    <table:table-cell table:style-name="ce16" office:value-type="string" calcext:value-type="string">
      <text:p>(123) 456-7890</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro2">
    <table:table-cell office:value-type="string" calcext:value-type="string">
      <text:p>123 Main Street</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro2">
    <table:table-cell office:value-type="string" calcext:value-type="string">
      <text:p>Anywhere, ZZ 12345-6789</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro1">
    <table:table-cell table:style-name="ce15" office:value-type="string" calcext:value-type="string">
      <text:p>Jane Doe</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro2">
    <table:table-cell table:style-name="ce16" office:value-type="string" calcext:value-type="string">
      <text:p>(234) 567-8901</text:p>
</code>```

答:
Only for completeness:

output:

people

joe

phone1

phone2

phone3

sue

cell4

home5

alice

atrib6

x7

y9

z10

query:

```<code>xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

<ul>
{
for $line in db:open("people")//text()
return
      if (matches($line, "[0-9]"))
      then <ul>{$line}</ul>
      else <li>{$line}</li>
}
</ul>
</code>```

Should this benefit anyone else.

Body:
I'm looking to select non-numerical data from an XML file towards shredding it into database columns, or at least an xmltable-like structure.  This FLWOR gives a somewhat useful result:

xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

{
for $foo  in db:open("foo")
return
{$foo//text()[not(matches(., '[0-9]'))]}

}

However, it outputs all results into a single li tag, like:

 a b c d

Preferred output would be of the form:

a

b

Most likely the data is problematic in some way, because a slightly different FLOWR:

xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

for $foo in db:open("foo")
return $foo//text()[not(matches(., '[0-9]'))]

certainly outputs each non-numerical string on a new line.  How can I output this into a list?

An excerpt of the data:

      <text:p>John Smith</text:p>

      <text:p>(123) 456-7890</text:p>

      <text:p>123 Main Street</text:p>

      <text:p>Anywhere, ZZ 12345-6789</text:p>

      <text:p>Jane Doe</text:p>

      <text:p>(234) 567-8901</text:p>

Body:
Only for completeness:

output:

people

joe

phone1

phone2

phone3

sue

cell4

home5

alice

atrib6

x7

y9

z10

query:

xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

<ul>
{
for $line in db:open("people")//text()
return
      if (matches($line, "[0-9]"))
      then <ul>{$line}</ul>
      else <li>{$line}</li>
}
</ul>

Should this benefit anyone else.


问:
getting data from json in order to fill a datatable
Good day developers ... I'm trying to fill a data table dynamically using information already fetched through a fetch and previously stored in a variable in my vuex instance and now called as computed property in my applets say I have this:

```<code><script>
import { mapActions, mapGetters } from "vuex";
export default {
  name: "Games",
  data() {
    return {
      search: "",
      headers:[
             {text:'Game#', value:'Game#'},
             {text:'Players in Game',value:'Players inGame'},
             {text:'Permissions',value:'Permissions'},
             {text:'Results',value:'Results'},

      ],

    };
  },
  components: {
  },
  props: ["gameid"],
  methods: {
    ...mapActions(["fetchingJsonEvents", "joinToGame","logOut", "createGame"]),

  },
  computed: {
    ...mapGetters(["getGamesAll", "getUserLogged"]),
    getGamesAll(){
       return this.$store.getters.getGamesAll.games-------->here is where the json is stored
    }
  },
  created() {
    this.fetchingJsonEvents();
  }
};
</script>
</code>```

and my html tag calling this computed and all else is like this:

```<code><v-data-table :search="search" :headers="headers" v-bind:items="getGamesAll">
    <template>
          <tbody>
            <tr v-for="(general, index) in getGamesAll.games" v-bind:key="index">
              <td>Game {{general.id}}:</td>

              <td>xxxxxxxx</td>
              <td>xxxxxxxx</td>
          </tbody>
     </template>
 </v-data-table>
</code>```

but the table doesn't show any result , it worked with  a v-simple-table, but once i try to do it in this way it doesn't....
Any advice .....thanks in advance

答:
this is unnecessary:

```<code>getGamesAll(){
 return this.$store.getters.getGamesAll.games
}
</code>```

because you already have it using mapGetters:

```<code>...mapGetters(["getGamesAll", "getUserLogged"]),
</code>```

if your getter getGamesAll have data then this should simply work:

```<code><tr v-for="(general, index) in getGamesAll.games" v-bind:key="index">
</code>```

Body:
Good day developers ... I'm trying to fill a data table dynamically using information already fetched through a fetch and previously stored in a variable in my vuex instance and now called as computed property in my applets say I have this:

and my html tag calling this computed and all else is like this:

<v-data-table :search="search" :headers="headers" v-bind:items="getGamesAll">
    <template>

              Game {{general.id}}:

              xxxxxxxx
              xxxxxxxx

     </template>
 </v-data-table>

but the table doesn't show any result , it worked with  a v-simple-table, but once i try to do it in this way it doesn't....
Any advice .....thanks in advance

Body:
this is unnecessary:

getGamesAll(){
 return this.$store.getters.getGamesAll.games
}

because you already have it using mapGetters:

...mapGetters(["getGamesAll", "getUserLogged"]),

if your getter getGamesAll have data then this should simply work:

<tr v-for="(general, index) in getGamesAll.games" v-bind:key="index">


问:
Pulling random files out of a folder for sampling
I needed a way to pull 10% of the files in a folder, at random, for sampling after every "run." Luckily, my current files are numbered numerically, and sequentially. So my current method is to list file names, parse the numerical portion, pull max and min values, count the number of files and multiply by .1, then use random.sample to get a "random [10%] sample." I also write these names to a .txt then use shutil.copy to move the actual files.

Obviously, this does not work if I have an outlier, i.e. if I have a file 345.txt among other files from 513.txt - 678.txt. I was wondering if there was a direct way to simply pull a number of files from a folder, randomly? I have looked it up and cannot find a better method.

Thanks.

答:
Based on Karl's solution (which did not work for me under Win 10, Python 3.x), I came up with this:</p>

```<code>import numpy as np
import os

# List all files in dir
files = os.listdir("C:/Users/.../Myfiles")

# Select 0.5 of the files randomly
random_files = np.random.choice(files, int(len(files)*.5))

# Get the remaining files
other_files = [x for x in files if x not in random_files]

# Do something with the files
for x in random_files:
    print(x)
</code>```

Body:
Based on Karl's solution (which did not work for me under Win 10, Python 3.x), I came up with this:

import numpy as np
import os

# List all files in dir
files = os.listdir("C:/Users/.../Myfiles")

# Select 0.5 of the files randomly
random_files = np.random.choice(files, int(len(files)*.5))

# Get the remaining files
other_files = [x for x in files if x not in random_files]

# Do something with the files
for x in random_files:
    print(x)