问:
Compiler for RISC-V vector code generation
Is there a compiler available which generates the vector instructions according to the new vector extension proposed in RISC-V ISA specification v2.2?</p>

答:
As of early 2020, there are binutil/gcc branches that support the current RISC-V Vector Extension "V" 0.8 draft.

That means with that experimental toolchain, you can use vector instruction in assembly code and in inline assembler constructs.

It's unclear if that GCC RISC-V "V" support already extends to auto-vectorization.

Vector intrinsics also aren't available, yet.


来源: stackexchange

问:
How to add rows in R that subtract 2 other rows based on common variables?
I have a data frame that is structured like the sample below. Each combination of date, market, gender, and age has 3 observations of type, "New", "Reac" and "Active". For each of these groups, I'd like to add a 4th row, which maintains the same date, market, gender, and age variables, but has a different type, and the cust and orders columns are generated by subtracting the type=New cust and orders values from the type=Active cust and order values.

For example, I would like to go from this:

```<code>date    market    gender    type    age    cust     orders

Apr-18  UK        Female    New     U20    1000     1500
Apr-18  UK        Female    Reac    U20    1000     1750
Apr-18  UK        Female    Active  U20    3000     7000
</code>```

To this:

```<code>date    market    gender    type    age    cust     orders

Apr-18  UK        Female    New     U20    1000     1500
Apr-18  UK        Female    Reac    U20    1000     1750
Apr-18  UK        Female    Active  U20    3000     7000
Apr-18  UK        Female    Old     U20    2000     5500
</code>```

So I have subtracted the type=New row from the type=Active row and stored the new cust and orders numbers in a 4th row, which has type=Old.

Thanks!

答:
We can group_by date, market, gender and age, subtract cust and orders and add type = 'old'. We can bind these new rows to the original dataset.

```<code>library(dplyr)

df %>%
  group_by(date, market, gender, age) %>%
  summarise(cust = cust[type=='Active'] - cust[type=='New'],
            orders = orders[type=='Active'] - orders[type=='New'],
            type = 'old') %>%
  bind_rows(df)

#  date   market gender age    cust orders type
#  <fct>  <fct>  <fct>  <fct> <int>  <int> <chr>
#1 Apr-18 UK     Female U20    2000   5500 old
#2 Apr-18 UK     Female U20    1000   1500 New
#3 Apr-18 UK     Female U20    1000   1750 Reac
#4 Apr-18 UK     Female U20    3000   7000 Active
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame that is structured like the sample below. Each combination of date, market, gender, and age has 3 observations of type, "New", "Reac" and "Active". For each of these groups, I'd like to add a 4th row, which maintains the same date, market, gender, and age variables, but has a different type, and the cust and orders columns are generated by subtracting the type=New cust and orders values from the type=Active cust and order values.

For example, I would like to go from this:

date    market    gender    type    age    cust     orders

Apr-18  UK        Female    New     U20    1000     1500
Apr-18  UK        Female    Reac    U20    1000     1750
Apr-18  UK        Female    Active  U20    3000     7000

To this:

date    market    gender    type    age    cust     orders

Apr-18  UK        Female    New     U20    1000     1500
Apr-18  UK        Female    Reac    U20    1000     1750
Apr-18  UK        Female    Active  U20    3000     7000
Apr-18  UK        Female    Old     U20    2000     5500

So I have subtracted the type=New row from the type=Active row and stored the new cust and orders numbers in a 4th row, which has type=Old.

Thanks!

Body:
We can group_by date, market, gender and age, subtract cust and orders and add type = 'old'. We can bind these new rows to the original dataset.

library(dplyr)

df %>%
  group_by(date, market, gender, age) %>%
  summarise(cust = cust[type=='Active'] - cust[type=='New'],
            orders = orders[type=='Active'] - orders[type=='New'],
            type = 'old') %>%
  bind_rows(df)

#  date   market gender age    cust orders type
#  <fct>  <fct>  <fct>  <fct> <int>  <int> <chr>
#1 Apr-18 UK     Female U20    2000   5500 old
#2 Apr-18 UK     Female U20    1000   1500 New
#3 Apr-18 UK     Female U20    1000   1750 Reac
#4 Apr-18 UK     Female U20    3000   7000 Active


问:
Automate the Boring Stuff With Python, Chapter 4 Exercise
I'm newbie and doing Al Sweigar's book at the moment. In chapter 4's exercise, he asks the following,

Say you have a list of lists where each value in the inner lists is a one-character string, like this:

```<code> grid = [['.', '.', '.', '.', '.', '.'],
         ['.', 'O', 'O', '.', '.', '.'],
         ['O', 'O', 'O', 'O', '.', '.'],
         ['O', 'O', 'O', 'O', 'O', '.'],
         ['.', 'O', 'O', 'O', 'O', 'O'],
         ['O', 'O', 'O', 'O', 'O', '.'],
         ['O', 'O', 'O', 'O', '.', '.'],
         ['.', 'O', 'O', '.', '.', '.'],
         ['.', '.', '.', '.', '.', '.']]
</code>```

You can think of grid[x][y] as being the character at the x- and y-coordinates of a “picture” drawn
     with text characters. The (0, 0) origin will be in the upper-left
     corner, the x-coordinates increase going right, and w the
     y-coordinates increase going down. Copy the previous grid value, and
     write code that uses it to print the image.

```<code>..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
</code>```

So I have written the code and it does what he asks for but I think its very poorly written and I wanted to ask you how can I improve it. My code,

```<code>grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

newString = ''

for i in range(len(grid)):
    newString += str(grid[i][0])

newString1 = '\n'
for i in range(len(grid)):
    newString1 += str(grid[i][1])

newString2 = '\n'
for i in range(len(grid)):
    newString2 += str(grid[i][2])

newString3 = '\n'
for i in range(len(grid)):
    newString3 += str(grid[i][3])

newString4 = '\n'
for i in range(len(grid)):
    newString4 += str(grid[i][4])

newString5 = '\n'
for i in range(len(grid)):
    newString5 += str(grid[i][5])

print(newString+newString1+newString2+newString3+newString4+newString5)
</code>```

Output of program:

```<code>..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm newbie and doing Al Sweigar's book at the moment. In chapter 4's exercise, he asks the following,

Say you have a list of lists where each value in the inner lists is a one-character string, like this:

 grid = [['.', '.', '.', '.', '.', '.'],
         ['.', 'O', 'O', '.', '.', '.'],
         ['O', 'O', 'O', 'O', '.', '.'],
         ['O', 'O', 'O', 'O', 'O', '.'],
         ['.', 'O', 'O', 'O', 'O', 'O'],
         ['O', 'O', 'O', 'O', 'O', '.'],
         ['O', 'O', 'O', 'O', '.', '.'],
         ['.', 'O', 'O', '.', '.', '.'],
         ['.', '.', '.', '.', '.', '.']]

You can think of grid[x][y] as being the character at the x- and y-coordinates of a “picture” drawn
     with text characters. The (0, 0) origin will be in the upper-left
     corner, the x-coordinates increase going right, and w the
     y-coordinates increase going down. Copy the previous grid value, and
     write code that uses it to print the image.

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

So I have written the code and it does what he asks for but I think its very poorly written and I wanted to ask you how can I improve it. My code,

grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

newString = ''

for i in range(len(grid)):
    newString += str(grid[i][0])

newString1 = '\n'
for i in range(len(grid)):
    newString1 += str(grid[i][1])

newString2 = '\n'
for i in range(len(grid)):
    newString2 += str(grid[i][2])

newString3 = '\n'
for i in range(len(grid)):
    newString3 += str(grid[i][3])

newString4 = '\n'
for i in range(len(grid)):
    newString4 += str(grid[i][4])

newString5 = '\n'
for i in range(len(grid)):
    newString5 += str(grid[i][5])

print(newString+newString1+newString2+newString3+newString4+newString5)

Output of program:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

Body:
I just started reading the book and here is what I came up with, seems pretty simple.

grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

def final(grid_solve, count):
    empty = ""
    for i in grid_solve:
        empty += i[count]

    return empty

total = 0

while total != len(grid[0]):
    print(final(grid, total))
    total += 1

Output:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....


问:
Private messaging in Django
I'm looking for a preexisting Django app providing user to user private messaging. I've seen django-pm and django-messages, neither of which appear to be in particularly active development. Is there really nothing out there? </p>

答:
I know this question is a bit old, but this looks promising django-postman.  I'm about to try it out for a project I'm working on.

I found it here:

http://djangopackages.com/grids/g/messaging/

If you haven't seen it before Django Packages is a great site for finding django apps that do all sorts of stuff.

ContentLicense: CC BY-SA 2.5

Title: Private messaging in Django


问:
How can i write an JSON file with PHP which looks like this?
```<code>{
    "general": {
        "knx_Gateway": "te",
        "knx_Port": "gas",
        "knx_Medium": "TP1",
        "knx_timezone": "+3"
    },
    "devices":[
      {
        "id": "0",
        "knx_dn": "testing",
        "knx_ga": "2",
        "knx_dt": "Bit"
      },
      {
        "id": "1",
        "knx_dn": "0",
        "knx_ga": "0",
        "knx_dt": "Bit"
      },
      {
        "id": "2",
        "knx_dn": "0",
        "knx_ga": "5",
        "knx_dt": "Byte"
      },
      {
        "id": "3",
        "knx_dn": "0",
        "knx_ga": "0",
        "knx_dt": "Byte"
      },
      {
        "id": "4",
        "knx_dn": "0",
        "knx_ga": "0",
        "knx_dt": "Byte"
      }
  ]
}

</code>```

This is what i tried so far:

```<code>//getting the data from the HTML page into an JSON format
$knxGenSet->general->knx_Gateway = $_POST["ipgate"];
$knxGenSet->general->knx_Port = $_POST["ipport"];
$knxGenSet->general->knx_Medium = $_POST["ipmedium"];
$knxGenSet->general->knx_timezone = $_POST["iptimezone"];

for($i=0; $i<5; $i++){
    echo "The number is " . $i . "<br>";

    $knxGenSet->devices->id = $i;
    $knxGenSet->devices->knx_ga = $_POST["dn" + $i];
    $knxGenSet->devices->knx_dn = $_POST["ga" + $i];
    $knxGenSet->devices->knx_dt = $_POST["dt" + $i];
}
</code>```

I cant get the other part with devices right it seems that I am doing something wrong here btw i can allready read this json format .. the reading part works perfectly! :)

Thanks in advance (kind of newb on json territory! :()

答:
The format can be specified with an object:

```<code><?php
$_POST = [
    "ipgate" => "testing",
    "ipport" => "testing",
    "ipmedium" => "testing",
    "iptimezone" => "testing",
    "dn0" => "test_1",
    "ga0" => "test_1",
    "dt0" => "test_1",
    "dn1" => "test_2",
    "ga1" => "test_2",
    "dt1" => "test_2",
];

$knxGenSet = (object) [
    'general' => (object) [],
    'devices' => []
];

$knxGenSet->general->knx_Gateway = $_POST["ipgate"];
$knxGenSet->general->knx_Port = $_POST["ipport"];
$knxGenSet->general->knx_Medium = $_POST["ipmedium"];
$knxGenSet->general->knx_timezone = $_POST["iptimezone"];

for($i=0; $i<2; $i++){
  //  echo "The number is " . $i . "<br>";

    $knxGenSet->devices[] = (object) [
        'id' => $i,
        'knx_ga' => $_POST["dn" . $i],
        'knx_dn' => $_POST["ga" . $i],
        'knx_dt' => $_POST["dt" . $i]
    ];
}

echo json_encode($knxGenSet);

</code>```

result:

```<code>{
  "general": {
    "knx_Gateway": "testing",
    "knx_Port": "testing",
    "knx_Medium": "testing",
    "knx_timezone": "testing"
  },
  "devices": [
    {
      "id": 0,
      "knx_ga": "test_1",
      "knx_dn": "test_1",
      "knx_dt": "test_1"
    },
    {
      "id": 1,
      "knx_ga": "test_2",
      "knx_dn": "test_2",
      "knx_dt": "test_2"
    }
  ]
}

</code>```

Body:
{
    "general": {
        "knx_Gateway": "te",
        "knx_Port": "gas",
        "knx_Medium": "TP1",
        "knx_timezone": "+3"
    },
    "devices":[
      {
        "id": "0",
        "knx_dn": "testing",
        "knx_ga": "2",
        "knx_dt": "Bit"
      },
      {
        "id": "1",
        "knx_dn": "0",
        "knx_ga": "0",
        "knx_dt": "Bit"
      },
      {
        "id": "2",
        "knx_dn": "0",
        "knx_ga": "5",
        "knx_dt": "Byte"
      },
      {
        "id": "3",
        "knx_dn": "0",
        "knx_ga": "0",
        "knx_dt": "Byte"
      },
      {
        "id": "4",
        "knx_dn": "0",
        "knx_ga": "0",
        "knx_dt": "Byte"
      }
  ]
}

This is what i tried so far:

//getting the data from the HTML page into an JSON format
$knxGenSet->general->knx_Gateway = $_POST["ipgate"];
$knxGenSet->general->knx_Port = $_POST["ipport"];
$knxGenSet->general->knx_Medium = $_POST["ipmedium"];
$knxGenSet->general->knx_timezone = $_POST["iptimezone"];

for($i=0; $i<5; $i++){
    echo "The number is " . $i . "
";

    $knxGenSet->devices->id = $i;
    $knxGenSet->devices->knx_ga = $_POST["dn" + $i];
    $knxGenSet->devices->knx_dn = $_POST["ga" + $i];
    $knxGenSet->devices->knx_dt = $_POST["dt" + $i];
}

I cant get the other part with devices right it seems that I am doing something wrong here btw i can allready read this json format .. the reading part works perfectly! :)

Thanks in advance (kind of newb on json territory! :()

Body:
The format can be specified with an object:

<?php
$_POST = [
    "ipgate" => "testing",
    "ipport" => "testing",
    "ipmedium" => "testing",
    "iptimezone" => "testing",
    "dn0" => "test_1",
    "ga0" => "test_1",
    "dt0" => "test_1",
    "dn1" => "test_2",
    "ga1" => "test_2",
    "dt1" => "test_2",
];

$knxGenSet = (object) [
    'general' => (object) [],
    'devices' => []
];

$knxGenSet->general->knx_Gateway = $_POST["ipgate"];
$knxGenSet->general->knx_Port = $_POST["ipport"];
$knxGenSet->general->knx_Medium = $_POST["ipmedium"];
$knxGenSet->general->knx_timezone = $_POST["iptimezone"];

for($i=0; $i<2; $i++){
  //  echo "The number is " . $i . "<br>";

    $knxGenSet->devices[] = (object) [
        'id' => $i,
        'knx_ga' => $_POST["dn" . $i],
        'knx_dn' => $_POST["ga" . $i],
        'knx_dt' => $_POST["dt" . $i]
    ];
}

echo json_encode($knxGenSet);

result:

{
  "general": {
    "knx_Gateway": "testing",
    "knx_Port": "testing",
    "knx_Medium": "testing",
    "knx_timezone": "testing"
  },
  "devices": [
    {
      "id": 0,
      "knx_ga": "test_1",
      "knx_dn": "test_1",
      "knx_dt": "test_1"
    },
    {
      "id": 1,
      "knx_ga": "test_2",
      "knx_dn": "test_2",
      "knx_dt": "test_2"
    }
  ]
}


问:
What is the meaning of environment of Anaconda
I have 3 questions:
1. What is the meaning of environment of Anaconda? What is the difference between the usage of enviroment and normal python?
2. When I use pip install xxx, can I import xxx under a conda environment? When I use conda install xxx, can I import xxx under the normal python interpreter?
3. If I use conda install xxx in env A, can I import xxx when I programme in env B?</p>

答: Anaconda helps you with your virtual environment, makes it easier to use. There is no big differnce between vanila python. But you can use only Anacoda without vanila python installed on your computer and by using virtual environment, you avoid trash files that can interrupt your future programms.</p>


问:
How to prevent a file from direct URL Access?
I'm using Apache and I have a sample web folder on my Local Host, like:

```<code>      http://localhost/test/
</code>```

Files in the test folder:

```<code>     index.html
     sample.jpg
     .htaccess
</code>```

Sample source of index.html:

```<code><html>
  <body>
    <img src="sample.jpg" />
  </body>
</html>
</code>```

When I run the website at http://localhost/test/, it will simply show the image `sample.jpg' on the page.

Problem:

I want to prevent the image showing as http://localhost/test/sample.jpg directly in the url bar.

Note: I found that the solutions below work when tested on every browser except Firefox.

答:
```<code>RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
RewriteCond %{REQUEST_URI} !^http://(www\.)?localhost/(.*)\.(gif|jpg|png|jpeg|mp4)$ [NC]
RewriteRule . - [F]
</code>```

Body:
I'm using Apache and I have a sample web folder on my Local Host, like:

      http://localhost/test/

Files in the test folder:

     index.html
     sample.jpg
     .htaccess

Sample source of index.html:

When I run the website at http://localhost/test/, it will simply show the image `sample.jpg' on the page.

Problem:

I want to prevent the image showing as http://localhost/test/sample.jpg directly in the url bar.

Note: I found that the solutions below work when tested on every browser except Firefox.


问:
run script when postfix/dovecot get new mail
I have:

```<code>postfix->dovecot-> new mail go to [aaaa@11111.xemple.com] mailbox
postfix->dovecot-> new mail go to [aaaa@22222.xemple.com] mailbox
postfix->dovecot-> new mail go to [aaaa@33333.xemple.com] mailbox
</code>```

I need run script when incoming mail comes and be saved by dovecot for domain 22222.xemple.com

how to make when the new email comes to aaaa@22222.xemple.com dovecot run script:
sh /my/script/run/after/new/email/in/22222_xemple_com/run.sh

答:
With dovecot you can use pigeonhole.

Here is the official link for dovecot:
https://wiki2.dovecot.org/Pigeonhole/Sieve/Plugins/Extprograms

it works together with the sieve server for filtering the mails so you can easily select which mails should be sent to your script.

Have fun
Wim

Body:
I have:

postfix->dovecot-> new mail go to [aaaa@11111.xemple.com] mailbox
postfix->dovecot-> new mail go to [aaaa@22222.xemple.com] mailbox
postfix->dovecot-> new mail go to [aaaa@33333.xemple.com] mailbox

I need run script when incoming mail comes and be saved by dovecot for domain 22222.xemple.com

how to make when the new email comes to aaaa@22222.xemple.com dovecot run script:
sh /my/script/run/after/new/email/in/22222_xemple_com/run.sh


问:
Are the properties in {...rest} being passed down to {routeProps} when passing props in react-router?
I was going through this example of passing our own props given on the React Router website:

https://reacttraining.com/react-router/core/api/Route/render-func

```<code>function FadingRoute({ component: Component, ...rest }) {
  return (
    <Route
      {...rest}
      render={routeProps => (
        <FadeIn>
          <Component {...routeProps} />
        </FadeIn>
      )}
    />
  );
}
</code>```

Q: is the {...rest} being passed down to  in order to pass the ...rest object to routeProps?

Thanx.
A.

答:
Unfortunately, rest won't be passed to routeProps so you need to merge them yourself when passing down to the Component:

```<code><Component {...routeProps} {...rest} />
</code>```

:)

Body:
I was going through this example of passing our own props given on the React Router website:

https://reacttraining.com/react-router/core/api/Route/render-func

function FadingRoute({ component: Component, ...rest }) {
  return (
    <Route
      {...rest}
      render={routeProps => (
        <FadeIn>
          <Component {...routeProps} />
        </FadeIn>
      )}
    />
  );
}

Q: is the {...rest} being passed down to  in order to pass the ...rest object to routeProps?

Thanx.
A.

Body:
Unfortunately, rest won't be passed to routeProps so you need to merge them yourself when passing down to the Component:

<Component {...routeProps} {...rest} />

:)


问:
Mysql Query structure for searching two tables
I have two tables sturctured like so:

```<code>Posts Table
id
content

Meta Table
id
post_id
content
name
</code>```

The posts table is the main parent that can have data from the meta table joined with it

```<code>Post Table
id   content
1    My first row

Meta Table
id   post_id  content   name
4    1        2011-5-5    date
5    1        My Heading  heading
6    2        2012-3-3    date
7    2        My Title    heading
</code>```

How would I write a query to search for an entry in the posts table that contains meta data content of 2011-5-5 with a name of date and My Heading with a name of heading

I can get them individually

```<code>Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
</code>```

But as soon as I add a second criteria, it returns zero results, becuase we are asking the name field to be two different things

```<code>Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
   AND (name='heading' AND content='My Heading')
</code>```

Any help would be greatly appreciated, Thanks!

答:
You'll need to join to the table twice:</p>

```<code>SELECT *
FROM posts, meta m1, meta m2
WHERE posts.id=m1.post_id
AND posts.id=m2.post_id
AND m1.name="date" AND m1.content="2011-5-5"
AND m2.name="heading" AND m2.content="My Heading"
</code>```

Body:
I have two tables sturctured like so:

Posts Table
id
content

Meta Table
id
post_id
content
name

The posts table is the main parent that can have data from the meta table joined with it

Post Table
id   content
1    My first row

Meta Table
id   post_id  content   name
4    1        2011-5-5    date
5    1        My Heading  heading
6    2        2012-3-3    date
7    2        My Title    heading

How would I write a query to search for an entry in the posts table that contains meta data content of 2011-5-5 with a name of date and My Heading with a name of heading

I can get them individually

Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')

But as soon as I add a second criteria, it returns zero results, becuase we are asking the name field to be two different things

Select *
from posts, meta
WHERE post_id = posts.id
   AND (name='date' AND content='2011-5-5')
   AND (name='heading' AND content='My Heading')

Any help would be greatly appreciated, Thanks!

Body:
You'll need to join to the table twice:

SELECT *
FROM posts, meta m1, meta m2
WHERE posts.id=m1.post_id
AND posts.id=m2.post_id
AND m1.name="date" AND m1.content="2011-5-5"
AND m2.name="heading" AND m2.content="My Heading"


问:
How to use NSPredicate with Date type
I am trying to make NSPredicate based on a date... I have tried this:

```<code>let datePredicate = NSPredicate(format: "due_date < %@", Date())
</code>```

I am not sure, but iirc, this worked before?

Now I get this error:

Argument type 'Date' does not conform to expected type 'CVarArg'

I tried smth like this

... Date() as NSDate,
but that failed too.

How to solve this?

答:
you have to cast the overlay type Date back to its Foundation counterpart NSDate:

```<code>let dueDate = Date()
let pred1 = NSPredicate(format: "due_date < %@", dueDate as NSDate)
</code>```

check this reference
https://stackoverflow.com/a/39587771/10168919

Title: How to use NSPredicate with Date type

Body:
I am trying to make NSPredicate based on a date... I have tried this:

let datePredicate = NSPredicate(format: "due_date < %@", Date())

I am not sure, but iirc, this worked before?

Now I get this error:

Argument type 'Date' does not conform to expected type 'CVarArg'

I tried smth like this

... Date() as NSDate,
but that failed too.

How to solve this?

Body:
you have to cast the overlay type Date back to its Foundation counterpart NSDate:

let dueDate = Date()
let pred1 = NSPredicate(format: "due_date < %@", dueDate as NSDate)

check this reference
https://stackoverflow.com/a/39587771/10168919


问:
Get repeating pairs, triples, quadruples and so on from an SQL database table?
I have a table from Poland Lotto Multi Multi 20/80 drawings history. So, each row contain 20 columns with numbers ranging from 1 to 80, no repeating numbers inside the row.

There are a few draws where 80 and 77 pair appears together in the last draws (check image link) but on the SQL result it seems that there isn't any 80 or even 77 number, the biggest being just 63 on nr2 column (check image link for details).
I am trying this piece of SQL query code and it seems that somehow it doesn't "catch" the all columns and it check at the maximum column number 10 (where the maximum number is 63 in this case) and it doesn't go further to the column number 20 (where the maximum possible number stored is 80).

This is the full SQL query code I used:

```<code>CREATE TABLE IF NOT EXISTS unpivot AS
SELECT *
FROM (
        SELECT DrawId, N1 as n_value FROM draws union all
        SELECT DrawId, N2 as n_value FROM draws union all
        SELECT DrawId, N3 as n_value FROM draws union all
        SELECT DrawId, N4 as n_value FROM draws union all
        SELECT DrawId, N5 as n_value FROM draws union all
        SELECT DrawId, N6 as n_value FROM draws union all
        SELECT DrawId, N7 as n_value FROM draws union all
        SELECT DrawId, N8 as n_value FROM draws union all
        SELECT DrawId, N9 as n_value FROM draws union all
        SELECT DrawId, N10 as n_value FROM draws union all
        SELECT DrawId, N11 as n_value FROM draws union all
        SELECT DrawId, N12 as n_value FROM draws union all
        SELECT DrawId, N13 as n_value FROM draws union all
        SELECT DrawId, N14 as n_value FROM draws union all
        SELECT DrawId, N15 as n_value FROM draws union all
        SELECT DrawId, N16 as n_value FROM draws union all
        SELECT DrawId, N17 as n_value FROM draws union all
        SELECT DrawId, N18 as n_value FROM draws union all
        SELECT DrawId, N19 as n_value FROM draws union all
        SELECT DrawId, N20 as n_value FROM draws
     ) as T;

SELECT nr1, nr2, count(*) as total
FROM
    (
    SELECT up1.n_value as nr1, up2.n_value as nr2
    FROM unpivot up1
    JOIN unpivot up2
      ON up1.DrawId = up2.DrawId
     AND up1.n_value < up2.n_value
   ) T
GROUP BY nr1, nr2
ORDER BY nr2 desc;
-- LIMIT 300;
</code>```

Repeating pairs into the database

Query results

答:
I suspect the problem is:

```<code> CREATE TABLE IF NOT EXISTS unpivot AS . . .
</code>```

That is, you have an older version of the table and the new version is not being created.

Instead, do:

```<code>DROP TABLE IF EXISTS unpivot;
</code>```

Then:

```<code>CREATE TABLE unpivot AS . . .
</code>```

Body:
I have a table from Poland Lotto Multi Multi 20/80 drawings history. So, each row contain 20 columns with numbers ranging from 1 to 80, no repeating numbers inside the row.

There are a few draws where 80 and 77 pair appears together in the last draws (check image link) but on the SQL result it seems that there isn't any 80 or even 77 number, the biggest being just 63 on nr2 column (check image link for details).
I am trying this piece of SQL query code and it seems that somehow it doesn't "catch" the all columns and it check at the maximum column number 10 (where the maximum number is 63 in this case) and it doesn't go further to the column number 20 (where the maximum possible number stored is 80).

This is the full SQL query code I used:

CREATE TABLE IF NOT EXISTS unpivot AS
SELECT *
FROM (
        SELECT DrawId, N1 as n_value FROM draws union all
        SELECT DrawId, N2 as n_value FROM draws union all
        SELECT DrawId, N3 as n_value FROM draws union all
        SELECT DrawId, N4 as n_value FROM draws union all
        SELECT DrawId, N5 as n_value FROM draws union all
        SELECT DrawId, N6 as n_value FROM draws union all
        SELECT DrawId, N7 as n_value FROM draws union all
        SELECT DrawId, N8 as n_value FROM draws union all
        SELECT DrawId, N9 as n_value FROM draws union all
        SELECT DrawId, N10 as n_value FROM draws union all
        SELECT DrawId, N11 as n_value FROM draws union all
        SELECT DrawId, N12 as n_value FROM draws union all
        SELECT DrawId, N13 as n_value FROM draws union all
        SELECT DrawId, N14 as n_value FROM draws union all
        SELECT DrawId, N15 as n_value FROM draws union all
        SELECT DrawId, N16 as n_value FROM draws union all
        SELECT DrawId, N17 as n_value FROM draws union all
        SELECT DrawId, N18 as n_value FROM draws union all
        SELECT DrawId, N19 as n_value FROM draws union all
        SELECT DrawId, N20 as n_value FROM draws
     ) as T;

SELECT nr1, nr2, count(*) as total
FROM
    (
    SELECT up1.n_value as nr1, up2.n_value as nr2
    FROM unpivot up1
    JOIN unpivot up2
      ON up1.DrawId = up2.DrawId
     AND up1.n_value < up2.n_value
   ) T
GROUP BY nr1, nr2
ORDER BY nr2 desc;
-- LIMIT 300;

Repeating pairs into the database

Query results

Body:
I suspect the problem is:

 CREATE TABLE IF NOT EXISTS unpivot AS . . .

That is, you have an older version of the table and the new version is not being created.

Instead, do:

DROP TABLE IF EXISTS unpivot;

Then:

CREATE TABLE unpivot AS . . .


问:
setValue not moving UISlider
i have added a slider to my storyboard and connected it. the result is this code inside my "Viewcontroller.swift":

```<code>@IBOutlet var control1: UISlider!
</code>```

when i try to change the value with this command:

```<code>control1.setValue(resultAvPitch, animated: false)
</code>```

the app is crashing:
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value 2020-02-15 13:55:54.045989+0100 UIGrid[8695:898849] Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value (lldb) –

i found somewhere a small code snippet and put it above this function:

```<code>let control1 = UISlider()
</code>```

like that its not crashing anymore but it doesnt make the slider move.. what am i doing wrong?. is there an option that i need to click somewhere in the storyboard?

note: i placed the slider inside a view and another view like that:

答: what helped in the end was removing all sliders, drag and connect them again. i have checked muliple times what the differences were but i didnt find anything. </p>

Title: setValue not moving UISlider

Body:
i have added a slider to my storyboard and connected it. the result is this code inside my "Viewcontroller.swift":

@IBOutlet var control1: UISlider!

when i try to change the value with this command:

control1.setValue(resultAvPitch, animated: false)

the app is crashing:
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value 2020-02-15 13:55:54.045989+0100 UIGrid[8695:898849] Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value (lldb) –

i found somewhere a small code snippet and put it above this function:

let control1 = UISlider()

like that its not crashing anymore but it doesnt make the slider move.. what am i doing wrong?. is there an option that i need to click somewhere in the storyboard?

note: i placed the slider inside a view and another view like that:


问:
IndexOutOfBoundsException setSpan (10 … 10) ends beyond length 3
Some times this error "IndexOutOfBoundsException setSpan (10 … 10) ends beyond length 3"
occurs in editText.setSelection() i.e when i want to focus back on that editText previous value from editText.getText.toString().length().

For Example:
editText.setSelection(editText.getText.toString().length());

Any ideas why it happen? And how to fix this??

答:
Use ClearSpans() on edit text
Example :
      editText.getText.clearSpans();

You can Handle this using Xml by puting
          '<'requestFocus/ >


问:
CallLog.Calls.NEW? What does it mean?
I am currently trying to figure out what

```<code>CallLog.Calls.NEW
</code>```

means.

The documentation says:

Whether or not the call has been
  acknowledged

( http://developer.android.com/reference/android/provider/CallLog.Calls.html#NEW ). I tried to reproduce this.

I made a call to another phone and hung up once it started ringing. What would I expect? An entry with TYPE = OUTGOING_TYPE and NEW = 0, right? But NEW is 1. That really doesn't make any sense to me...

Any ideas?

答: I don't know for sure but my guess would be that in your test scenario the phone you called would have TYPE = INCOMING_TYPE and NEW = 0 because the call has not yet been acknowledged on that phone. On that phone you would see the little "missed call" icon in the Notification bar. That call would be considered NEW.

Title: CallLog.Calls.NEW? What does it mean?

Body:
I am currently trying to figure out what

CallLog.Calls.NEW

means.

The documentation says:

Whether or not the call has been
  acknowledged

( http://developer.android.com/reference/android/provider/CallLog.Calls.html#NEW ). I tried to reproduce this.

I made a call to another phone and hung up once it started ringing. What would I expect? An entry with TYPE = OUTGOING_TYPE and NEW = 0, right? But NEW is 1. That really doesn't make any sense to me...

Any ideas?


问:
Multiple Table Filters
I want to filter more than once in this table at the same time. It happens when I enter the $table.find('tbody tr:visible'); code, but it gets corrupted when I use the backspace in the filtering part because it only searches within the visible TR. (Original: $table.find('tbody tr');)

How can I solve this problem?

$(document).ready(function() {
  $('.filterable .btn-filter').click(function() {
    var $panel = $(this).parents('.filterable'),
      $filters = $panel.find('.filters input'),
      $tbody = $panel.find('.table tbody');
    if ($filters.prop('disabled') == true) {
      $filters.prop('disabled', false);
      $filters.first().focus();
    } else {
      $filters.val('').prop('disabled', true);
      $tbody.find('.no-result').remove();
      $tbody.find('tr').show();
    }
  });

  $('.filterable .filters input').keyup(function(e) {
    /* Ignore tab key */
    var code = e.keyCode || e.which;
    if (code == '9') return;
    /* Useful DOM data and selectors */
    var $input = $(this),
      inputContent = $input.val().toLowerCase(),
      $panel = $input.parents('.filterable'),
      column = $panel.find('.filters th').index($input.parents('th')),
      $table = $panel.find('.table'),
      $rows = $table.find('tbody tr');
    /* Dirtiest filter function ever ;) */
    var $filteredRows = $rows.filter(function() {
      var value = $(this).find('td').eq(column).text().toLowerCase();
      return value.indexOf(inputContent) === -1;
    });
    /* Clean previous no-result if exist */
    $table.find('tbody .no-result').remove();
    /* Show all rows, hide filtered ones (never do that outside of a demo ! xD) */
    $rows.show();
    $filteredRows.hide();
    /* Prepend no-result row if all rows are filtered */
    if ($filteredRows.length === $rows.length) {
      $table.find('tbody').prepend($('
No result found
'));
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container">
  <h3>The columns titles are merged with the filters inputs thanks to the placeholders attributes</h3>
  <hr>
  <p>Inspired by this snippet</p>
  <div class="row">
    <div class="panel panel-primary filterable">
      <div class="panel-heading">
        <h3 class="panel-title">Users</h3>
        <div class="pull-right">
          <button class="btn btn-default btn-xs btn-filter"><span class="glyphicon glyphicon-filter"></span> Filter</button>
        </div>
      </div>
      <table class="table">
        <thead>
          <tr class="filters">
            <th><input type="text" class="form-control" placeholder="#" disabled></th>
            <th><input type="text" class="form-control" placeholder="First Name" disabled></th>
            <th><input type="text" class="form-control" placeholder="Last Name" disabled></th>
            <th><input type="text" class="form-control" placeholder="Username" disabled></th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>Markos</td>
            <td>Ottoass</td>
            <td>@mdo</td>
          </tr>
          <tr>
            <td>2</td>
            <td>Jacobos</td>
            <td>Thorntonass</td>
            <td>@fat</td>
          </tr>
          <tr>
            <td>3</td>
            <td>Larry</td>
            <td>the Bird</td>
            <td>@twitter</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div></code>```

https://jsfiddle.net/b0vj6p4n/

答:
jquery.Datatables could be used,  it has various features related to searching, sorting and loading data.

The site has quite a few examples to get started with loading data and setting up a table:
https://datatables.net/examples/basic_init/zero_configuration.html

The following snippet could be used to configure a table as datatable:

```<code>$(document).ready(function() {
    $('#example').DataTable();
} );
</code>```

Title: Multiple Table Filters

Body:
I want to filter more than once in this table at the same time. It happens when I enter the $table.find('tbody tr:visible'); code, but it gets corrupted when I use the backspace in the filtering part because it only searches within the visible TR. (Original: $table.find('tbody tr');)

How can I solve this problem?

$(document).ready(function() {
  $('.filterable .btn-filter').click(function() {
    var $panel = $(this).parents('.filterable'),
      $filters = $panel.find('.filters input'),
      $tbody = $panel.find('.table tbody');
    if ($filters.prop('disabled') == true) {
      $filters.prop('disabled', false);
      $filters.first().focus();
    } else {
      $filters.val('').prop('disabled', true);
      $tbody.find('.no-result').remove();
      $tbody.find('tr').show();
    }
  });

  $('.filterable .filters input').keyup(function(e) {
    /* Ignore tab key */
    var code = e.keyCode || e.which;
    if (code == '9') return;
    /* Useful DOM data and selectors */
    var $input = $(this),
      inputContent = $input.val().toLowerCase(),
      $panel = $input.parents('.filterable'),
      column = $panel.find('.filters th').index($input.parents('th')),
      $table = $panel.find('.table'),
      $rows = $table.find('tbody tr');
    /* Dirtiest filter function ever ;) */
    var $filteredRows = $rows.filter(function() {
      var value = $(this).find('td').eq(column).text().toLowerCase();
      return value.indexOf(inputContent) === -1;
    });
    /* Clean previous no-result if exist */
    $table.find('tbody .no-result').remove();
    /* Show all rows, hide filtered ones (never do that outside of a demo ! xD) */
    $rows.show();
    $filteredRows.hide();
    /* Prepend no-result row if all rows are filtered */
    if ($filteredRows.length === $rows.length) {
      $table.find('tbody').prepend($('
No result found
'));
    }
  });
});

<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

The columns titles are merged with the filters inputs thanks to the placeholders attributes

Inspired by this snippet

Users

          <button class="btn btn-default btn-xs btn-filter"> Filter</button>

            <input type="text" class="form-control" placeholder="#" disabled>
            <input type="text" class="form-control" placeholder="First Name" disabled>
            <input type="text" class="form-control" placeholder="Last Name" disabled>
            <input type="text" class="form-control" placeholder="Username" disabled>

            1
            Markos
            Ottoass
            @mdo

            2
            Jacobos
            Thorntonass
            @fat

            3
            Larry
            the Bird
            @twitter

https://jsfiddle.net/b0vj6p4n/

Body:
jquery.Datatables could be used,  it has various features related to searching, sorting and loading data.

The site has quite a few examples to get started with loading data and setting up a table:
https://datatables.net/examples/basic_init/zero_configuration.html

The following snippet could be used to configure a table as datatable:

$(document).ready(function() {
    $('#example').DataTable();
} );


问:
Buttons in seleium
I'm trying to automate this website where you can take quizzes. I tried to automate to press a button, but I can't.

    <button class="tasso-button__green" _ngcontent-tasso-universal-c22>Go!</button>

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

```from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome(executable_path=r"C:\Users\User\Desktop\Programming language\Python\chromedriver.exe")
browser.get("http://www.tassomai.com/")

login = browser.find_element_by_link_text("Sign in")
login.click()

e = browser.find_element_by_name("email")
e.send_keys("***********@mayfieldschool.net")

p = browser.find_element_by_name("password")
p.send_keys("*******")
p.submit()

button = browser.find_element_by_class_name("tasso-button__green")
button.click()
```

I tried this code in python, but it does not work: it sometimes logs me in, however, it doesn't let press the button.

How do I press this button with selenium?

答:
You can first wait for the element to be clickable and then click on it.

You can do it like:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Go!']"))).click()
</code>```

Note: You have to add the following imports:

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Title: Buttons in seleium

Body:
I'm trying to automate this website where you can take quizzes. I tried to automate to press a button, but I can't.

    <button class="tasso-button__green" _ngcontent-tasso-universal-c22>Go!</button>

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome(executable_path=r"C:\Users\User\Desktop\Programming language\Python\chromedriver.exe")
browser.get("http://www.tassomai.com/")

login = browser.find_element_by_link_text("Sign in")
login.click()

e = browser.find_element_by_name("email")
e.send_keys("***********@mayfieldschool.net")

p = browser.find_element_by_name("password")
p.send_keys("*******")
p.submit()

button = browser.find_element_by_class_name("tasso-button__green")
button.click()

I tried this code in python, but it does not work: it sometimes logs me in, however, it doesn't let press the button.

How do I press this button with selenium?

Body:
You can first wait for the element to be clickable and then click on it.

You can do it like:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Go!']"))).click()

Note: You have to add the following imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Excel Formula to apply one formula to reference call and cells above and another formula to cells below
I'm not sure if this is possible via formula but I am trying to setup a formula that can be applied to a range of cells that will find the middle cell then apply one formula to all cells above it, another formula to the center cell and a different formula to all cells below. I figured out how to find that center cell but when I use an If neither of the conditions seem to be applied.
Here is what I have now...</p>

```<code>    =IF(INDEX($H$4:$H$204,MATCH((INDIRECT(ADDRESS(((COUNTA($H$4:$H$204))/2)+4,9))),$H$4:$H$204,0)+1,1),0,1)
</code>```

答:
Welcome to SO. Let me know if this is what you're looking for:

```<code>=IF(ROW(A1)<ROUNDDOWN(COUNTA(A:A)/2,0),"formula 1",IF(ROW(A1)>ROUNDUP(COUNTA(A:A)/2,0),"formula 2","formula 3"))
</code>```

The formula will work with both odd and even count of cells.

Body:
I'm not sure if this is possible via formula but I am trying to setup a formula that can be applied to a range of cells that will find the middle cell then apply one formula to all cells above it, another formula to the center cell and a different formula to all cells below. I figured out how to find that center cell but when I use an If neither of the conditions seem to be applied.
Here is what I have now...

    =IF(INDEX($H$4:$H$204,MATCH((INDIRECT(ADDRESS(((COUNTA($H$4:$H$204))/2)+4,9))),$H$4:$H$204,0)+1,1),0,1)

Body:
Welcome to SO. Let me know if this is what you're looking for:

=IF(ROW(A1)<ROUNDDOWN(COUNTA(A:A)/2,0),"formula 1",IF(ROW(A1)>ROUNDUP(COUNTA(A:A)/2,0),"formula 2","formula 3"))

The formula will work with both odd and even count of cells.


问:
Change source image for image view when pressed
I have a scroll view with lots of image buttons. I want to change the image for an image button when it's pressed. The thing is that I want the image to remain until another image button is pressed. That's why I couldn't use a selector. What is the best practice to achieve this?</p>

答:
state_pressed or state_activated did not work for me.

However, I succeeded with state_enabled

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:drawable="@drawable/checkbox_on" />
    <item android:state_enabled="false" android:drawable="@drawable/checkbox_off" />
</selector>
</code>```

Your xml should declare it as src:

```<code> <ImageView
        android:id="@+id/img_checkmark"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/checkbox_selector_filter"/>
</code>```

Then in code, ensure you enable or disable it based on event/state:

imageCheckBox.isEnabled = true

This was easiest and cleanest for me

Body:
state_pressed or state_activated did not work for me.

However, I succeeded with state_enabled

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:drawable="@drawable/checkbox_on" />
    <item android:state_enabled="false" android:drawable="@drawable/checkbox_off" />
</selector>

Your xml should declare it as src:

 <ImageView
        android:id="@+id/img_checkmark"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/checkbox_selector_filter"/>

Then in code, ensure you enable or disable it based on event/state:

imageCheckBox.isEnabled = true

This was easiest and cleanest for me


问:
Passing data from python to html view in django framework
I have an application where users can enter the news they heard. The entered 'news headline', 'news', and 'time' are stored in elasticsearch NoSQL database. The entered news items are first analyzed with NLP techniques to detect and remove unethical words and again stored in elasticsearch database. After that, I want to show them on a web page in order. I completed the processing NLP task but still, I cannot display all the news items on the web page. for that, I'm using the Django framework.

what I was trying to do was extract the news items from elasticsearch using a for loop and store each news item=[news headline, news, time] as a collection of lists inside a list [[],[],[]] and pass them to the HTML template.

python code:

```<code>def news_items(request):
newsData = []

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

for x in range(1, 101):
    results = es.get(index='reporter', doc_type='news', id=x)

    pyData1 = json.dumps(results)
    pyData2 = json.loads(pyData1)

    newsData = pyData2['_source']

    pyNewsData1 = json.dumps(newsData)
    pyNewsData2 = json.loads(pyNewsData1)

    id = pyData2['_id']

    headline = pyNewsData2['newsHeadline']

    newsText = pyNewsData2['newsText']

    date = pyNewsData2['date']

    list = [id, headline, newsText, date]

    newsData.append(list)

template = 'AppOne/news.html'
return render(request, template, {'nd': newsData})
</code>```

template code to access that data

```<code><ul>
{% for a,b,c,d in nd %}
    <li>{{a}}</li>
    <li>{{b}}</li>
    <li>{{a}}</li>
    <li>{{b}}</li>
{% endfor %}
</code>```

but it gives an error:

AttributeError: 'dict' object has no attribute 'append'

I tried many ways and each time it was unsuccessful.I'm new to the Django framework. Please, someone, suggest a way to display them on the template web page.

答:
the problem is that you are replacing your output list with the json dump output. you should use some other variable like TempNewsData as I used here (this is just your for-loop):

```<code>TempNewsData = pyData2['_source']

pyNewsData1 = json.dumps(TempNewsData)
pyNewsData2 = json.loads(pyNewsData1)

id = pyData2['_id']

headline = pyNewsData2['newsHeadline']

newsText = pyNewsData2['newsText']

date = pyNewsData2['date']

list = [id, headline, newsText, date]

newsData.append(list)
</code>```

Body:
I have an application where users can enter the news they heard. The entered 'news headline', 'news', and 'time' are stored in elasticsearch NoSQL database. The entered news items are first analyzed with NLP techniques to detect and remove unethical words and again stored in elasticsearch database. After that, I want to show them on a web page in order. I completed the processing NLP task but still, I cannot display all the news items on the web page. for that, I'm using the Django framework.

what I was trying to do was extract the news items from elasticsearch using a for loop and store each news item=[news headline, news, time] as a collection of lists inside a list [[],[],[]] and pass them to the HTML template.

python code:

def news_items(request):
newsData = []

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

for x in range(1, 101):
    results = es.get(index='reporter', doc_type='news', id=x)

    pyData1 = json.dumps(results)
    pyData2 = json.loads(pyData1)

    newsData = pyData2['_source']

    pyNewsData1 = json.dumps(newsData)
    pyNewsData2 = json.loads(pyNewsData1)

    id = pyData2['_id']

    headline = pyNewsData2['newsHeadline']

    newsText = pyNewsData2['newsText']

    date = pyNewsData2['date']

    list = [id, headline, newsText, date]

    newsData.append(list)

template = 'AppOne/news.html'
return render(request, template, {'nd': newsData})

template code to access that data

{% for a,b,c,d in nd %}

{{a}}

{{b}}

{{a}}

{{b}}

{% endfor %}

but it gives an error:

AttributeError: 'dict' object has no attribute 'append'

I tried many ways and each time it was unsuccessful.I'm new to the Django framework. Please, someone, suggest a way to display them on the template web page.

Body:
the problem is that you are replacing your output list with the json dump output. you should use some other variable like TempNewsData as I used here (this is just your for-loop):

TempNewsData = pyData2['_source']

pyNewsData1 = json.dumps(TempNewsData)
pyNewsData2 = json.loads(pyNewsData1)

id = pyData2['_id']

headline = pyNewsData2['newsHeadline']

newsText = pyNewsData2['newsText']

date = pyNewsData2['date']

list = [id, headline, newsText, date]

newsData.append(list)


答:
Although arg0naut91 has provided a great answer, I'd like to share my own implementation which is using lag:

```<code>group_stats %>%
  mutate(delta_fev = lag(mean) - mean, delta_se = sqrt(se^2 + lag(se)^2)) %>%
  tail(1) %>%
  select(delta_fev, delta_se)
</code>```

Title: How do I perform calculations after summarising with dplyr?

Body:
I have performed group-wise calculations on two groups the following way:

group_stats <- fev %>%
  group_by(smoking) %>%
  summarize(mean = mean(fev), n = n(), sd = sd(fev), se = sd / sqrt(n))

Which produces data frame with 2 rows. Now I want to calculate the following:

The difference in means between two rows

The new se value like se[row_1] ^ 2 + se[row_2] ^ 2.

Is there a tidyverse way of doing it?

dput output:

structure(list(age = c(8, 13, 8, 11, 8, 8, 9, 11, 15, 8, 6, 8,
12, 8, 7, 9, 10, 8, 12, 13, 11, 12, 9, 7, 11, 14, 12, 9, 10,
8, 10, 11, 6, 9, 11, 14, 11, 10, 9, 11, 11, 11, 8, 15, 7, 9,
11, 11, 8, 8, 9, 11, 8, 11, 8, 8, 9, 14, 9, 10, 16, 13, 16, 10,
8, 12, 9, 11, 8, 8, 12, 7, 13, 9, 7, 8, 10, 7, 13, 13, 8, 8,
8, 16, 12, 10, 14, 9, 8, 7, 9, 11, 12, 13, 13, 10, 6, 13, 9,
7, 6, 8, 6, 12, 11, 10, 11, 9, 10, 9, 13, 10, 12, 6, 13, 13,
10, 11, 11, 8, 9, 9, 15, 7, 8, 15, 15, 8, 14, 10, 6, 10, 8, 6,
12, 8, 13, 9, 16, 10, 11, 8, 6, 11, 10, 13, 12, 11, 10, 8, 8,
10, 12, 10, 7, 9, 9, 12, 8, 7, 8, 9, 6, 11, 13, 8, 10, 12, 9,
11, 13, 6, 13, 10, 8, 12, 6, 9, 9, 13, 11, 15, 6, 11, 10, 10,
10, 7, 7, 12, 12, 10, 13, 10, 10, 10, 11, 10, 13, 9, 11, 12,
10, 8, 11, 11, 10, 13, 13, 9, 8, 11, 9, 7, 10, 11, 9, 9, 11,
14, 9, 7, 10, 7, 15, 14, 11, 9, 8, 7, 13, 13, 9, 9, 7, 11, 11,
16, 9, 15, 7, 12, 7, 6, 8, 12, 8, 14, 9, 9, 8, 15, 10, 12, 13,
11, 8, 11, 8, 11, 13, 8, 11, 9, 6, 10, 11, 10, 11, 9, 8, 12,
12, 12, 8, 9, 15, 12, 14, 14, 9, 9, 10, 13, 8, 13, 13, 9, 9,
8, 11, 9, 7, 7, 9, 9, 9, 9, 7, 8, 9, 15, 16, 10, 6, 9, 12, 9,
8, 8, 8, 9, 11, 7, 15, 7, 11, 12, 8, 11, 14, 7, 6, 8, 7, 12,
11, 13, 15, 14, 12, 8, 11, 10, 11, 9, 7, 9, 8, 10, 7, 8, 15,
11, 11, 16, 13, 11, 9, 6, 9, 6, 11, 11, 11, 11, 7, 16, 11, 10,
8, 7, 11, 10, 8, 14, 6, 14, 10, 12, 6, 13, 9, 7, 11, 12, 10,
6, 9, 10, 12, 13, 8, 7, 12, 11, 8, 11, 6, 11, 12, 7, 13, 7, 14,
7, 10, 12, 10, 6, 9, 9, 9, 12, 8, 9, 6, 12, 7, 10, 9, 10, 11,
11, 7, 10, 7, 10, 10, 16, 6, 6, 6, 10, 14, 12, 7, 10, 13, 11,
9, 7, 7, 7, 11, 9, 7, 8, 11, 8, 8, 10, 10, 9, 8, 9, 12, 6, 8,
7, 9, 11, 11, 9, 10, 9, 14, 9, 7, 8, 11, 7, 6, 12, 9, 8, 10,
13, 10, 13, 15, 8, 9, 10, 15, 11, 9, 9, 13, 14, 6, 6, 10, 10,
12, 14, 7, 11, 11, 13, 10, 7, 14, 10, 9, 9, 6, 14, 12, 10, 11,
8, 12, 9, 11, 8, 16, 7, 14, 12, 13, 12, 8, 10, 11, 16, 9, 12,
13, 10, 10, 11, 10, 10, 13, 9, 9, 14, 10, 9, 16, 9, 6, 11, 6,
11, 12, 14, 15, 11, 11, 12, 12, 9, 8, 8, 11, 6, 9, 7, 10, 12,
10, 7, 10, 8, 12, 9, 13, 12, 9, 8, 12, 11, 11, 8, 11, 11, 14,
9, 16, 9, 6, 10, 10, 12, 15, 11, 8, 15, 8, 9, 7, 9, 10, 9, 8,
10, 12, 7, 8, 11, 12, 10, 10, 8, 11, 8), fev = c(1.94, 3.785,
2.123, 2.993, 2.094, 2.187, 2.23, 2.14, 5.793, 2.069, 1.979,
1.931, 1.916, 1.547, 2.219, 3.135, 1.937, 2.665, 2.971, 2.677,
3.587, 2.569, 2.973, 1.603, 4.637, 4.273, 2.759, 2.725, 2.435,
1.624, 1.858, 3.411, 1.713, 1.895, 2.542, 3.428, 2.659, 2.581,
2.076, 2.633, 2.562, 2.606, 2.335, 3.004, 1.69, 2.348, 2.822,
2.928, 2.01, 2.42, 2.592, 2.866, 2.215, 2.318, 2.631, 1.703,
1.969, 2.236, 2.165, 2.391, 2.903, 4.225, 3.387, 3.111, 1.556,
2.332, 2.851, 3.681, 2.631, 2.531, 3.924, 1.726, 4.305, 2.871,
1.75, 2.09, 2.341, 2.371, 4.448, 3.208, 1.512, 2.175, 2.5, 2.795,
2.752, 2.352, 4.683, 2.964, 2.503, 2.55, 2.923, 2.735, 2.241,
4.336, 3.255, 2.642, 2.262, 3.06, 3, 1.905, 1.691, 2.476, 1.796,
3.255, 4.324, 1.458, 3.069, 2.717, 3.456, 2.715, 3.906, 2.568,
3.53, 1.624, 3.549, 3.089, 2.855, 3.847, 1.694, 1.657, 2.182,
2.65, 2.679, 1.698, 2.069, 4.279, 4.5, 2.927, 3.806, 2.691, 1.747,
2.358, 1.962, 1.415, 2.499, 2.993, 4.789, 2.485, 4.504, 2.864,
2.458, 1.292, 1.535, 3.171, 2.328, 3.056, 2.889, 2.689, 2.175,
2.015, 2.305, 3.183, 4.55, 2.094, 1.649, 1.953, 2.119, 3.341,
1.844, 1.609, 1.429, 2.639, 1.634, 3.845, 3.078, 2.388, 2.77,
3.343, 2.487, 2.665, 3.086, 1.697, 3.297, 2.356, 1.759, 2.304,
1.699, 3.114, 2.463, 2.646, 2.988, 4.506, 1.878, 3.515, 2.292,
3.086, 4.591, 1.37, 2.093, 2.605, 3.186, 2.688, 3.141, 2.387,
3.007, 2.673, 2.827, 3.251, 2.704, 1.754, 2.417, 2.417, 3.038,
2.732, 3.011, 2.498, 3.795, 3.984, 2.434, 2.091, 2.336, 3.247,
2.57, 2.084, 2.481, 2.812, 2.574, 3.842, 2.362, 4.271, 1.947,
2.22, 2.364, 2.564, 3.33, 2.276, 2.887, 2.09, 1.872, 1.253, 2.531,
2.449, 2.803, 1.912, 1.826, 4.593, 3.222, 3.674, 3.223, 2.278,
2.419, 3.403, 1.624, 1.338, 2.303, 4.831, 1.794, 4.763, 2.196,
2.164, 2.354, 2.264, 2.891, 2.751, 4.045, 3.596, 2.193, 2.346,
1.735, 3.058, 3.887, 2.681, 2.387, 2.069, 1.666, 3.329, 3.108,
2.25, 3.12, 2.301, 1.897, 3.058, 3.519, 3.082, 2.328, 3.004,
3.799, 3.692, 2.538, 3.957, 2.316, 1.933, 2.696, 2.976, 2.709,
3.147, 3.994, 2.352, 3.042, 1.758, 2.123, 1.855, 1.79, 2.046,
2.457, 3.681, 2.259, 2.13, 1.682, 1.697, 2.893, 3.211, 2.608,
3.489, 1.719, 3.029, 3.231, 2.56, 2.481, 2.458, 2.382, 2.32,
4.073, 1.461, 3.727, 1.165, 4.065, 3.079, 1.344, 3.32, 3.395,
1.631, 1.431, 2.226, 1.64, 2.841, 3.022, 4.232, 2.635, 3.741,
3.835, 2.258, 2.081, 2.201, 2.501, 2.797, 2.578, 1.606, 1.953,
3.05, 1.92, 2.118, 2.198, 3.47, 3.102, 3.688, 3.297, 2.884, 2.135,
1.427, 2.798, 1.572, 3.169, 2.386, 2.957, 2.491, 2.135, 2.981,
2.563, 2.838, 2.673, 2.535, 2.785, 2.216, 2.639, 2.934, 1.65,
3.68, 3.11, 3.279, 1.715, 5.083, 2.604, 1.473, 2.894, 2.556,
3.203, 1.348, 2.042, 2.545, 4.073, 3.745, 2.144, 1.658, 2.384,
3.774, 1.675, 3.206, 1.672, 3.236, 4.72, 2.095, 2.599, 1.728,
3.436, 1.917, 2.1, 3.501, 3.35, 1.536, 2.166, 2.833, 1.708, 2.935,
2.016, 2.85, 1.481, 3.035, 1.612, 3.354, 2.442, 3.305, 3.425,
3.078, 1.742, 3.073, 1.829, 2.901, 2.561, 4.27, 1.718, 1.523,
1.602, 3.498, 4.309, 3.529, 1.72, 2.246, 3.577, 2.762, 2.46,
2.366, 1.796, 1.415, 3.104, 1.942, 1.495, 2.071, 2.953, 2.135,
2.341, 1.873, 2.862, 2.455, 2.358, 2.529, 4.08, 2.104, 1.78,
1.789, 1.751, 3.28, 2.524, 2.04, 2.287, 2.048, 3.78, 2.988, 1.611,
1.698, 2.463, 1.827, 1.527, 2.868, 2.076, 2.145, 2.132, 3.331,
2.758, 2.216, 4.284, 1.744, 2.659, 1.858, 2.887, 3.977, 3.016,
1.591, 4.877, 3.169, 1.343, 2.102, 2.592, 2.72, 3.222, 3.585,
1.935, 3.023, 4.13, 2.819, 3.132, 2.002, 4.842, 2.365, 1.886,
3.239, 1.423, 2.997, 4.411, 2.504, 3.49, 2.98, 4.393, 1.716,
4.007, 1.987, 4.872, 2.111, 3.074, 3.751, 3.193, 2.913, 1.999,
1.823, 3.258, 4.07, 2.457, 5.224, 3.816, 2.25, 3.127, 2.354,
1.665, 2.975, 4.756, 2.246, 2.42, 3.381, 3.2, 1.869, 3.645, 1.558,
1.338, 2.578, 1.826, 2.17, 3.001, 4.111, 3.985, 3.583, 2.974,
3.791, 2.752, 2.1, 2.333, 1.335, 3.369, 1.919, 2.588, 2.056,
2.813, 4.203, 3.09, 2.158, 3.413, 1.991, 2.579, 2.126, 3.152,
2.347, 2.631, 1.523, 2.714, 3.654, 3.515, 1.562, 3.339, 3.223,
2.891, 1.773, 4.299, 2.571, 1.695, 3.048, 2.646, 3.082, 3.122,
2.465, 2.293, 3.731, 2.288, 2.056, 1.877, 2.688, 2.52, 3.556,
2.004, 3.166, 2.822, 1.932, 1.724, 3.111, 2.866, 1.811, 2.608,
2.211, 2.754, 2.435), gender = structure(c(2L, 1L, 2L, 2L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L,
1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L,
1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L,
1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L,
2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L,
2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L,
1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L,
2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L,
2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L,
1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L,
2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L,
2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L,
2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L,
2L), .Label = c("f", "m"), class = "factor"), smoking = structure(c(1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("ns", "s"), class = "factor")), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -598L))

Body:
Although arg0naut91 has provided a great answer, I'd like to share my own implementation which is using lag:

group_stats %>%
  mutate(delta_fev = lag(mean) - mean, delta_se = sqrt(se^2 + lag(se)^2)) %>%
  tail(1) %>%
  select(delta_fev, delta_se)


问:
altair: Access rSquared-value in a regression
I am using this example https://altair-viz.github.io/user_guide/transform/regression.html
for plotting a regression trendline in altair.

```<code>import altair as alt
import pandas as pd
import numpy as np

np.random.seed(42)
x = np.linspace(0, 10)
y = x - 5 + np.random.randn(len(x))

df = pd.DataFrame({'x': x, 'y': y})

chart = alt.Chart(df).mark_point().encode(
    x='x',
    y='y'
)

chart + chart.transform_regression('x', 'y').mark_line()
</code>```

Additionally, I want to add the rSquared-value as text to the chart. How can I access the value?
According to the documentation, it should be something like:

```<code>chart + chart.transform_regression('x', 'y', params=True).mark_text()
</code>```

答:
When using mark_text() you'll need to specify the x and y location (or encoding) along with the label of the text value you want to show:

```<code>import altair as alt
import pandas as pd
import numpy as np

np.random.seed(42)
x = np.linspace(0, 10)
y = x - 5 + np.random.randn(len(x))

df = pd.DataFrame({'x': x, 'y': y})

chart = alt.Chart(df).mark_point().encode(
    x='x',
    y='y'
)
line = chart.transform_regression('x', 'y').mark_line()

params = alt.Chart(df).transform_regression(
    'x', 'y', params=True
).mark_text(align='left').encode(
    x=alt.value(20),  # pixels from left
    y=alt.value(20),  # pixels from top
    text='rSquared:N'
)

chart + line + params
</code>```

Body:
I am using this example https://altair-viz.github.io/user_guide/transform/regression.html
for plotting a regression trendline in altair.

import altair as alt
import pandas as pd
import numpy as np

np.random.seed(42)
x = np.linspace(0, 10)
y = x - 5 + np.random.randn(len(x))

df = pd.DataFrame({'x': x, 'y': y})

chart = alt.Chart(df).mark_point().encode(
    x='x',
    y='y'
)

chart + chart.transform_regression('x', 'y').mark_line()

Additionally, I want to add the rSquared-value as text to the chart. How can I access the value?
According to the documentation, it should be something like:

chart + chart.transform_regression('x', 'y', params=True).mark_text()

Body:
When using mark_text() you'll need to specify the x and y location (or encoding) along with the label of the text value you want to show:

import altair as alt
import pandas as pd
import numpy as np

np.random.seed(42)
x = np.linspace(0, 10)
y = x - 5 + np.random.randn(len(x))

df = pd.DataFrame({'x': x, 'y': y})

chart = alt.Chart(df).mark_point().encode(
    x='x',
    y='y'
)
line = chart.transform_regression('x', 'y').mark_line()

params = alt.Chart(df).transform_regression(
    'x', 'y', params=True
).mark_text(align='left').encode(
    x=alt.value(20),  # pixels from left
    y=alt.value(20),  # pixels from top
    text='rSquared:N'
)

chart + line + params


问:
Display hidden html code with jQuery
There is another solution to display a hidden input when a user choose an option from the select tag?
I want to put the HTML code outside the JS code.

jQuery code:

```<code>$(function() {

    var message = new Array(),
        $paymentOption = $("#payement_option"),
        $messageDisplay = $("#message_display");

    message[1] = '<input type="text" name="email" size="30" />';

    $paymentOption.change(function() {

        var messageIndex = $(this).val();

        $messageDisplay.empty();

        if (messageIndex > 0)
            $messageDisplay.append(message[messageIndex]);

    });

});
</code>```

HTML code like this:

```<code><select name="option"><option value="0">yes</option><option value="1">no</option</select>
</code>```

the output:

```<code><div id="message_display"></div>
</code>```

EDIT:

I want something like:

```<code><div id="message_display">
    <input type="text" name="email" size="30" />
</div>
</code>```

答:
I think you mean you want to make the message_display div visible...

```<code>$("#message_display").show();
</code>```

or edit the CSS more specifically:

```<code>$("#message_display").css("display", "block");
</code>```

I'd recommend have a browse through the JQuery API - it's a good read and shows you how much can be done and how easily: http://api.jquery.com

Title: Display hidden html code with jQuery

Body:
There is another solution to display a hidden input when a user choose an option from the select tag?
I want to put the HTML code outside the JS code.

jQuery code:

$(function() {

    var message = new Array(),
        $paymentOption = $("#payement_option"),
        $messageDisplay = $("#message_display");

    message[1] = '<input type="text" name="email" size="30" />';

    $paymentOption.change(function() {

        var messageIndex = $(this).val();

        $messageDisplay.empty();

        if (messageIndex > 0)
            $messageDisplay.append(message[messageIndex]);

    });

});

HTML code like this:

<select name="option"><option value="0">yes</option><option value="1">no</option</select>

the output:

EDIT:

I want something like:

    <input type="text" name="email" size="30" />

Body:
I think you mean you want to make the message_display div visible...

$("#message_display").show();

or edit the CSS more specifically:

$("#message_display").css("display", "block");

I'd recommend have a browse through the JQuery API - it's a good read and shows you how much can be done and how easily: http://api.jquery.com


问:
Laravel Feature test can't make a DELETE request
I'm using Laravel 5.4

web.php

```<code>Route::delete('claim/{id?}', 'ClaimController@claimRemove');
</code>```

myTest.php

```<code>$response = $this->json('delete', 'claim', [
   'id' => $id
]);
</code>```

When i run phpunit, i'm getting the

MethodNotAllowedHttpException

BUT if I run it via Postman or phpstorm rest client - it works fine, so the reason is somewhere in $this->json method. I also tried $this->call.
If I switch delete method to post in web.php and in my test file - test is passing well.
So, question is - why it's not working with DELETE method or how to test DELETE calls?:)

Thanks.

答:
If composer update simply solved your problem it sounds like that your route cache has not been updated with your latest route changes. Both composer update and composer install include normally a list of artisan commands such as route:clear as they are specified indirectly in the composer.json file when optimize is used.

Secondly, use this form below due to the fact the id is part of your route otherwise it will hit the route without an id. However it will also be acceptable because you have made the parameter optional.

```<code>$response = $this->json('delete', 'claim/' . $id, []);
</code>```

Body:
I'm using Laravel 5.4

web.php

Route::delete('claim/{id?}', 'ClaimController@claimRemove');

myTest.php

$response = $this->json('delete', 'claim', [
   'id' => $id
]);

When i run phpunit, i'm getting the

MethodNotAllowedHttpException

BUT if I run it via Postman or phpstorm rest client - it works fine, so the reason is somewhere in $this->json method. I also tried $this->call.
If I switch delete method to post in web.php and in my test file - test is passing well.
So, question is - why it's not working with DELETE method or how to test DELETE calls?:)

Thanks.

Body:
If composer update simply solved your problem it sounds like that your route cache has not been updated with your latest route changes. Both composer update and composer install include normally a list of artisan commands such as route:clear as they are specified indirectly in the composer.json file when optimize is used.

Secondly, use this form below due to the fact the id is part of your route otherwise it will hit the route without an id. However it will also be acceptable because you have made the parameter optional.

$response = $this->json('delete', 'claim/' . $id, []);


问:
How to create SQL Server table schema from a XML schema? (with .NET and Visual Studio 2008)
I have a XML schema, and I know that "xsd.exe" can generate the C# code for it. But I want to know if is possible to automatically create the MS SQL Server 2005+ tables from the XSD, with the help of this or other tools.

BTW I didn't get what the C# code generated by "xsd.exe" is worth for.
What's the difference between code generated by CodeXS and xsd.exe?

答:
I know that this is an old topic, however it was really helpful to me to know how it can be done. Maybe it would be helpful to others.

More advanced examples can be seen at Microsoft page.

So, it is possible to create manually SQL table from XSD. For example, we have the following xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <CAR_NUM>624</CAR_NUM>
      <CAR_ORDER>1</CAR_ORDER>
   </row>
   <row>
      <CAR_NUM>623</CAR_NUM>
      <CAR_ORDER>2</CAR_ORDER>
   </row>
   <row>
      <CAR_NUM>681</CAR_NUM>
      <CAR_ORDER>3</CAR_ORDER>
   </row>
   <row>
      <CAR_NUM>625</CAR_NUM>
      <CAR_ORDER>4</CAR_ORDER>
   </row>
   <row>
      <CAR_NUM>680</CAR_NUM>
      <CAR_ORDER>5</CAR_ORDER>
   </row>
</foo>
</code>```

So out XSD will look like this:

```<code><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
    <xsd:element name="row" sql:relation="CAR"
                            sql:key-fields="CAR_NUM">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="CAR_NUM"   type="xsd:integer" />
                <xsd:element name="CAR_ORDER"   type="xsd:integer" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>

</xsd:schema>
</code>```

And SQL table will look like this:

```<code>CREATE TABLE CAR (
    CAR_NUM   INT ,
    CAR_ORDER INT
GO
</code>```

And then you can use Interop.SQLXMLBULKLOADLib library to load data into SQLServer:

```<code>try
{
    var xmlFileName = @".your address here..\GetInformReplyEdited.xml";
    var xsdScheme = @".your address here..\scheme.xsd";

    var connString = "Provider=sqloledb;server=yourServer;database=Test;integrated security=SSPI";
    SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class
    {
        ConnectionString = connString,
        ErrorLogFile = "error.xml",
        KeepIdentity = false
    };
    objBL.Execute(xsdScheme, xmlFileName);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
</code>```

Body:
I know that this is an old topic, however it was really helpful to me to know how it can be done. Maybe it would be helpful to others.

More advanced examples can be seen at Microsoft page.

So, it is possible to create manually SQL table from XSD. For example, we have the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <CAR_NUM>624</CAR_NUM>
      <CAR_ORDER>1</CAR_ORDER>
   </row>
   <row>
      <CAR_NUM>623</CAR_NUM>
      <CAR_ORDER>2</CAR_ORDER>
   </row>
   <row>
      <CAR_NUM>681</CAR_NUM>
      <CAR_ORDER>3</CAR_ORDER>
   </row>
   <row>
      <CAR_NUM>625</CAR_NUM>
      <CAR_ORDER>4</CAR_ORDER>
   </row>
   <row>
      <CAR_NUM>680</CAR_NUM>
      <CAR_ORDER>5</CAR_ORDER>
   </row>
</foo>

So out XSD will look like this:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
    <xsd:element name="row" sql:relation="CAR"
                            sql:key-fields="CAR_NUM">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="CAR_NUM"   type="xsd:integer" />
                <xsd:element name="CAR_ORDER"   type="xsd:integer" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>

</xsd:schema>

And SQL table will look like this:

CREATE TABLE CAR (
    CAR_NUM   INT ,
    CAR_ORDER INT
GO

And then you can use Interop.SQLXMLBULKLOADLib library to load data into SQLServer:

try
{
    var xmlFileName = @".your address here..\GetInformReplyEdited.xml";
    var xsdScheme = @".your address here..\scheme.xsd";

    var connString = "Provider=sqloledb;server=yourServer;database=Test;integrated security=SSPI";
    SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class
    {
        ConnectionString = connString,
        ErrorLogFile = "error.xml",
        KeepIdentity = false
    };
    objBL.Execute(xsdScheme, xmlFileName);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}


问:
How to safe data from another thread to use on controls?
I have a library that serves using events data came in from async tcp operations.
When using those data in controls after they received on the UI though I get Cross-Thread Opration exception. How to solve this problem before the consumer of the library gets the data to show on his controls. So basically I need to throw the data to his own thread where using the library?

The same code used for the compact framework with linked files.

I'm using inside the library this method with a help Control to say if invoke is required but its not working.

```<code>public static void InvokeIfNecessary(Control control, Action setValue)
{

    if (control.InvokeRequired)
    {
        control.Invoke(setValue);
    }
    else
    {
        setValue();
    }
}
</code>```

A sample code using an event to serve data to the user using the library.

```<code>    if (OnClientChangeConnection != null) SafeData.InvokeIfNecessary(_helpControl, () => OnClientChangeConnection(ConnectedClients, requestClientInfo)); // ConnectedClients is an integer and requestClientInfo is a List<ClientInfo> class type.
</code>```

Thank you.

答:
The proper way to do this is to use the SynchronizationContext object.  I have included sample code.  Basically what you have to do is wrap your thread task in a class that can save a reference to a synchronization context object and callback supplied by the main thread then it calls those after the work is down.

This is a simple form:

```<code>public partial class Form1 : Form
{
    private SynchronizationContext _synchronizationContext;

    public Form1()
    {
        InitializeComponent();
        //Client must be careful to create sync context soimehwere they are sure to be on main thread
        _synchronizationContext = AsyncOperationManager.SynchronizationContext;
    }

    //Callback method implementation - must be of this form
    public void ReceiveThreadData(object threadData)
    {
        // Can use directly in UI without error
        this.listBoxMain.Items.Add((string)threadData);
    }

    private void DoSomeThreadWork()
    {
        // Thread needs callback and sync context.
        // You probably want to derive your own callback from the NET SendOrPostCallback class.
        SendOrPostCallback callback = new SendOrPostCallback(ReceiveThreadData);
        SomeThreadTask task = new SomeThreadTask(_synchronizationContext, callback);
        Thread thread = new Thread(task.ExecuteThreadTask);
        thread.Start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DoSomeThreadWork();
    }

}
</code>```

This is a class that has the thread task

```<code>/// SomeThreadTask defines the work a thread needs to do and also provides any data required along with callback pointers etc.
/// Populate a new SomeThreadTask instance with a synch context and callnbackl along with any data the thread needs
/// then start the thread to execute the task.
/// </summary>
public class SomeThreadTask
{

    private string _taskId;
    private SendOrPostCallback _completedCallback;
    private SynchronizationContext _synchronizationContext;

    /// <summary>
    /// Get instance of a delegate used to notify the main thread when done.
    /// </summary>
    internal SendOrPostCallback CompletedCallback
    {
        get { return _completedCallback; }
    }

    /// <summary>
    /// Get SynchronizationContext for main thread.
    /// </summary>
    internal SynchronizationContext SynchronizationContext
    {
        get { return _synchronizationContext; }
    }

    /// <summary>
    /// Thread entry point function.
    /// </summary>
    public void ExecuteThreadTask()
    {

        //Just sleep instead of doing any real work
        Thread.Sleep(5000);

        string message = "This is some spoof data from thread work.";

        // Execute callback on synch context to tell main thread this task is done.
        SynchronizationContext.Post(CompletedCallback, (object)message);

    }

    public SomeThreadTask(SynchronizationContext synchronizationContext, SendOrPostCallback callback)
    {
        _synchronizationContext = synchronizationContext;
        _completedCallback = callback;
    }

}
</code>```

Body:
I have a library that serves using events data came in from async tcp operations.
When using those data in controls after they received on the UI though I get Cross-Thread Opration exception. How to solve this problem before the consumer of the library gets the data to show on his controls. So basically I need to throw the data to his own thread where using the library?

The same code used for the compact framework with linked files.

I'm using inside the library this method with a help Control to say if invoke is required but its not working.

public static void InvokeIfNecessary(Control control, Action setValue)
{

    if (control.InvokeRequired)
    {
        control.Invoke(setValue);
    }
    else
    {
        setValue();
    }
}

A sample code using an event to serve data to the user using the library.

    if (OnClientChangeConnection != null) SafeData.InvokeIfNecessary(_helpControl, () => OnClientChangeConnection(ConnectedClients, requestClientInfo)); // ConnectedClients is an integer and requestClientInfo is a List<ClientInfo> class type.

Thank you.

Body:
The proper way to do this is to use the SynchronizationContext object.  I have included sample code.  Basically what you have to do is wrap your thread task in a class that can save a reference to a synchronization context object and callback supplied by the main thread then it calls those after the work is down.

This is a simple form:

public partial class Form1 : Form
{
    private SynchronizationContext _synchronizationContext;

    public Form1()
    {
        InitializeComponent();
        //Client must be careful to create sync context soimehwere they are sure to be on main thread
        _synchronizationContext = AsyncOperationManager.SynchronizationContext;
    }

    //Callback method implementation - must be of this form
    public void ReceiveThreadData(object threadData)
    {
        // Can use directly in UI without error
        this.listBoxMain.Items.Add((string)threadData);
    }

    private void DoSomeThreadWork()
    {
        // Thread needs callback and sync context.
        // You probably want to derive your own callback from the NET SendOrPostCallback class.
        SendOrPostCallback callback = new SendOrPostCallback(ReceiveThreadData);
        SomeThreadTask task = new SomeThreadTask(_synchronizationContext, callback);
        Thread thread = new Thread(task.ExecuteThreadTask);
        thread.Start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DoSomeThreadWork();
    }

}

This is a class that has the thread task

/// SomeThreadTask defines the work a thread needs to do and also provides any data required along with callback pointers etc.
/// Populate a new SomeThreadTask instance with a synch context and callnbackl along with any data the thread needs
/// then start the thread to execute the task.
/// </summary>
public class SomeThreadTask
{

    private string _taskId;
    private SendOrPostCallback _completedCallback;
    private SynchronizationContext _synchronizationContext;

    /// <summary>
    /// Get instance of a delegate used to notify the main thread when done.
    /// </summary>
    internal SendOrPostCallback CompletedCallback
    {
        get { return _completedCallback; }
    }

    /// <summary>
    /// Get SynchronizationContext for main thread.
    /// </summary>
    internal SynchronizationContext SynchronizationContext
    {
        get { return _synchronizationContext; }
    }

    /// <summary>
    /// Thread entry point function.
    /// </summary>
    public void ExecuteThreadTask()
    {

        //Just sleep instead of doing any real work
        Thread.Sleep(5000);

        string message = "This is some spoof data from thread work.";

        // Execute callback on synch context to tell main thread this task is done.
        SynchronizationContext.Post(CompletedCallback, (object)message);

    }

    public SomeThreadTask(SynchronizationContext synchronizationContext, SendOrPostCallback callback)
    {
        _synchronizationContext = synchronizationContext;
        _completedCallback = callback;
    }

}


问:
Call parallel coroutines and wait for all of them to be over
I have some coroutines:

```<code>IEnumerator a(){ /* code */ }
IEnumerator b(){ /* code */ }
IEnumerator c(){ /* code */ }
</code>```

I want to create a coroutine that calls a, b and c in parallel but wait for all of them to finish before going on, something like:

```<code>IEnumerator d(){
    StartCoroutine(a());
    StartCoroutine(b());
    StartCoroutine(c());
    wait until all of them are over
    print("all over");
}
</code>```

Obviously I could use a boolean for each coroutine to save its current state, but since this approach is not scalable, I'd prefer a more straight-forward solution.

答:
The method that I use, which is also a bit clear code and easy to use:</p>
```<code>IEnumerator First() { yield return new WaitForSeconds(1f); }
IEnumerator Second() { yield return new WaitForSeconds(2f); }
IEnumerator Third() { yield return new WaitForSeconds(3f); }

IEnumerator d()
{
    Coroutine a = StartCoroutine(First());
    Coroutine b = StartCoroutine(Second());
    Coroutine c = StartCoroutine(Third());

    //wait until all of them are over
    yield return a;
    yield return b;
    yield return c;

    print("all over");
}
</code>```

Body:
I have some coroutines:

IEnumerator a(){ /* code */ }
IEnumerator b(){ /* code */ }
IEnumerator c(){ /* code */ }

I want to create a coroutine that calls a, b and c in parallel but wait for all of them to finish before going on, something like:

IEnumerator d(){
    StartCoroutine(a());
    StartCoroutine(b());
    StartCoroutine(c());
    wait until all of them are over
    print("all over");
}

Obviously I could use a boolean for each coroutine to save its current state, but since this approach is not scalable, I'd prefer a more straight-forward solution.

Body:
The method that I use, which is also a bit clear code and easy to use:

IEnumerator First() { yield return new WaitForSeconds(1f); }
IEnumerator Second() { yield return new WaitForSeconds(2f); }
IEnumerator Third() { yield return new WaitForSeconds(3f); }

IEnumerator d()
{
    Coroutine a = StartCoroutine(First());
    Coroutine b = StartCoroutine(Second());
    Coroutine c = StartCoroutine(Third());

    //wait until all of them are over
    yield return a;
    yield return b;
    yield return c;

    print("all over");
}


问:
How to construct an array of arrays with Powershell?
To group data, every time there's a "new person" as below, I want to add their info to that temporary array and reset that array to null.

Before each "new person" array is set to null, I want to add that array to an array of people.  An array of arrays.

How can I add one array into another?

```<code>$people = import-csv "./people.csv"

$h = @{}
$h.gettype()

$all_people

ForEach ($person in $people) {
  $new_person
  if ($person -match '[0-9]') {
    Write-host $person
  }
  else {
    write-host "new person"
    write-host $person
  }
}
</code>```

output:

```<code>thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ pwsh foo.ps1

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object
new person
@{people=joe}
@{people=phone1}
@{people=phone2}
@{people=phone3}
new person
@{people=sue}
@{people=cell4}
@{people=home5}
new person
@{people=alice}
@{people=atrib6}
@{people=x7}
@{people=y9}
@{people=z10}

thufir@dur:~/flwor/people$
</code>```

I have something like this:

```<code>$people = import-csv "./people.csv"

$all_people
$new_person = "new","person"

$new_person.GetType()

ForEach ($person in $people) {

  if ($person -match '[0-9]') {
    Write-host $person
    $new_person.Add($person)
  }
  else {
    write-host "new person"
    write-host $person
    #$new_person = null
    $new_person = "new","person"
  }
}
</code>```

答:
Powershell doesnt provide a good functionality to create an array of array with use of basic arrays.

What you can do use use an array of hashtable or PsCustomObjects to create yourself an array of arrays.

Body:
To group data, every time there's a "new person" as below, I want to add their info to that temporary array and reset that array to null.

Before each "new person" array is set to null, I want to add that array to an array of people.  An array of arrays.

How can I add one array into another?

$people = import-csv "./people.csv"

$h = @{}
$h.gettype()

$all_people

ForEach ($person in $people) {
  $new_person
  if ($person -match '[0-9]') {
    Write-host $person
  }
  else {
    write-host "new person"
    write-host $person
  }
}

output:

thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ pwsh foo.ps1

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object
new person
@{people=joe}
@{people=phone1}
@{people=phone2}
@{people=phone3}
new person
@{people=sue}
@{people=cell4}
@{people=home5}
new person
@{people=alice}
@{people=atrib6}
@{people=x7}
@{people=y9}
@{people=z10}

thufir@dur:~/flwor/people$

I have something like this:

$people = import-csv "./people.csv"

$all_people
$new_person = "new","person"

$new_person.GetType()

ForEach ($person in $people) {

  if ($person -match '[0-9]') {
    Write-host $person
    $new_person.Add($person)
  }
  else {
    write-host "new person"
    write-host $person
    #$new_person = null
    $new_person = "new","person"
  }
}


问:
How do I get input from user for two diffrent instances?
I'm creating a program that displays an employee's name and salary. the name and salary is entered by the user and I want to make two employees i.e. two instances. How to get two seperate inputs from the user?

```<code>import java.util.Scanner;
</code>```

public class Employee {

```<code>String first_name;
String last_name;
double pay = 0;

public Employee(double p, String f, String l) {
    first_name = f;
    last_name = l;
    pay = p;
}

public void name_printer(){
    //To collect Area
   System.out.println("Your name is "+ first_name+" "+last_name+".");
}

public void pay_printer(){
    //To collect Area
    pay=pay*12;
    System.out.println("Your yearly pay is "+ pay+".");
}

public void pay_update(){
    //To collect Area
    pay=pay*12;
    pay=pay+(pay*0.1);
   System.out.println("Your raised yearly pay is "+ pay+".");
}

public static void main(String[] args) {
    // TODO code application logic here
    Scanner input = new Scanner(System.in);
    System.out.print("Enter first name ");
    String in1_f = input.nextLine();
    System.out.print("Enter last name ");
    String in1_l = input.nextLine();
    System.out.print("Enter your monthly pay ");
    double user1_p = input.nextDouble();
    double in1_p=0;
    if (user1_p>0){
        in1_p=user1_p;
    }
    Employee employee1 = new Employee(in1_p, in1_f, in1_l);
    employee1.name_printer();
    employee1.pay_printer();
    employee1.pay_update();

}
</code>```

答:
To get your design slightly more convenient you should follow one of the main programmers' habits - reuse the code:

```<code>// Note that I marked Scanner as final,
// since it shouldn't be modified inside the method
public Employee createEmployee(final Scanner input) {
    System.out.print("Enter first name ");
    String in1_f = input.nextLine();

    System.out.print("Enter last name ");
    String in1_l = input.nextLine();

    System.out.print("Enter your monthly pay ");
    double user1_p = input.nextDouble();
    double in1_p=0;

    if (user1_p>0){
        in1_p=user1_p;
    }

    System.out.println("All data is provided, creating instance...");
    return new Employee(in1_p, in1_f, in1_l);
}
</code>```

And then in main func:

```<code>Scanner input = new Scanner(System.in);
Employee e1 = createEmployee(input);
Employee e2 = createEmployee(input); // and so on...
</code>```

To get all data about an instance just override toString() method in your employee class (it is preferred over creating your own print methods):

```<code>@Override
public String toString() {
    StringBuilder s1 = new StringBuilder();
    s1.append("Some information " + someInformation + "\n");
    // construct the string which will represent your object
    return s1.toString();
}
</code>```

And then:

```<code>System.out.println(e1.toString());
</code>```

Body:
I'm creating a program that displays an employee's name and salary. the name and salary is entered by the user and I want to make two employees i.e. two instances. How to get two seperate inputs from the user?

import java.util.Scanner;

public class Employee {

String first_name;
String last_name;
double pay = 0;

public Employee(double p, String f, String l) {
    first_name = f;
    last_name = l;
    pay = p;
}

public void name_printer(){
    //To collect Area
   System.out.println("Your name is "+ first_name+" "+last_name+".");
}

public void pay_printer(){
    //To collect Area
    pay=pay*12;
    System.out.println("Your yearly pay is "+ pay+".");
}

public void pay_update(){
    //To collect Area
    pay=pay*12;
    pay=pay+(pay*0.1);
   System.out.println("Your raised yearly pay is "+ pay+".");
}

public static void main(String[] args) {
    // TODO code application logic here
    Scanner input = new Scanner(System.in);
    System.out.print("Enter first name ");
    String in1_f = input.nextLine();
    System.out.print("Enter last name ");
    String in1_l = input.nextLine();
    System.out.print("Enter your monthly pay ");
    double user1_p = input.nextDouble();
    double in1_p=0;
    if (user1_p>0){
        in1_p=user1_p;
    }
    Employee employee1 = new Employee(in1_p, in1_f, in1_l);
    employee1.name_printer();
    employee1.pay_printer();
    employee1.pay_update();

}

Body:
To get your design slightly more convenient you should follow one of the main programmers' habits - reuse the code:

// Note that I marked Scanner as final,
// since it shouldn't be modified inside the method
public Employee createEmployee(final Scanner input) {
    System.out.print("Enter first name ");
    String in1_f = input.nextLine();

    System.out.print("Enter last name ");
    String in1_l = input.nextLine();

    System.out.print("Enter your monthly pay ");
    double user1_p = input.nextDouble();
    double in1_p=0;

    if (user1_p>0){
        in1_p=user1_p;
    }

    System.out.println("All data is provided, creating instance...");
    return new Employee(in1_p, in1_f, in1_l);
}

And then in main func:

Scanner input = new Scanner(System.in);
Employee e1 = createEmployee(input);
Employee e2 = createEmployee(input); // and so on...

To get all data about an instance just override toString() method in your employee class (it is preferred over creating your own print methods):

@Override
public String toString() {
    StringBuilder s1 = new StringBuilder();
    s1.append("Some information " + someInformation + "\n");
    // construct the string which will represent your object
    return s1.toString();
}

And then:

System.out.println(e1.toString());


问:
Generic interface problem
So here is my problem:

I have the interface:

```<code>public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
    List<ICell<Feature>> Window { get; set; }
    Feature              GenusFeature { get; set; }
    Double               VitalityRatio { get; set; }
    String               PopulationMarker { get; set; }
    Boolean              Captured { get; set; }
}
</code>```

And wanted to implement ISubstratum interface in this way:

```<code>public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}
</code>```

But compiler says that:

The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.

In some possible ISubstratum implementation I planned to pass a Bitmap as K && ICell (extented pixel info) as T.

How to resolve this?

Thanks!

答:
```<code>public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct, IComparable<ICell<Feature>>
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}
</code>```

Title: Generic interface problem

Body:
So here is my problem:

I have the interface:

public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
    List<ICell<Feature>> Window { get; set; }
    Feature              GenusFeature { get; set; }
    Double               VitalityRatio { get; set; }
    String               PopulationMarker { get; set; }
    Boolean              Captured { get; set; }
}

And wanted to implement ISubstratum interface in this way:

public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}

But compiler says that:

The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.

In some possible ISubstratum implementation I planned to pass a Bitmap as K && ICell (extented pixel info) as T.

How to resolve this?

Thanks!