问:
How to flush the print buffer in R?
I want to run a long-running simulation and have updates printed periodically. However, I am finding that my print statements are being buffered, even when I explicitly try to flush. Here, for example:

```<code>for (i in 1:10)
{
    print(i)
    flush(stdout())
    Sys.sleep(1)
}
</code>```

I would expect this to increment every 1sec, but it outputs everything at the end, after 10 seconds.

How would you force a flush of the print buffer?

答:
You can also use cat():

```<code>for (i in 1:10) {

  # Sleep for 1 second
  Sys.sleep(1)

  # Print the current iteration
  cat(paste0("\r", i))
}
</code>```

Title: How to flush the print buffer in R?

Body:
I want to run a long-running simulation and have updates printed periodically. However, I am finding that my print statements are being buffered, even when I explicitly try to flush. Here, for example:

for (i in 1:10)
{
    print(i)
    flush(stdout())
    Sys.sleep(1)
}

I would expect this to increment every 1sec, but it outputs everything at the end, after 10 seconds.

How would you force a flush of the print buffer?

Body:
You can also use cat():

for (i in 1:10) {

  # Sleep for 1 second
  Sys.sleep(1)

  # Print the current iteration
  cat(paste0("\r", i))
}


来源: stackexchange

问:
Why is my .htaccess www. force causing external forms to fail without www.?
Because of strange cross domain AJAX problems, causing AJAX requests to fail when not using www.(the PHP handler communicating with the request is given in a relative path, so it can't be an address issue or something - that's what this question is about though), I have forced www. using .htaccess :

```<code>#enable rewrite engine and set options
Options +FollowSymLinks
RewriteEngine on

#only www.
RewriteCond %{HTTP_HOST} !^www.domain.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301]
</code>```

This works great. However, I want to allow other webmasters to post one of my forms on their website, using my form URL in their form's action attribute. This always worked, however after my .htaccess change the forms are only submitted when the webmaster adds www. to the action value. Without www. the form will not get submitted.

How should I change my .htaccess file to make sure that these forms are also submitted without www.?

答:
You could use

```<code>RewriteCond %{REQUEST_METHOD} ^GET$
</code>```

which will rewrite only GET requests, leaving POST requests as they are.

OwnerDisplayName: Tom

ContentLicense: CC BY-SA 2.5

Body:
Because of strange cross domain AJAX problems, causing AJAX requests to fail when not using www.(the PHP handler communicating with the request is given in a relative path, so it can't be an address issue or something - that's what this question is about though), I have forced www. using .htaccess :

#enable rewrite engine and set options
Options +FollowSymLinks
RewriteEngine on

#only www.
RewriteCond %{HTTP_HOST} !^www.domain.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301]

This works great. However, I want to allow other webmasters to post one of my forms on their website, using my form URL in their form's action attribute. This always worked, however after my .htaccess change the forms are only submitted when the webmaster adds www. to the action value. Without www. the form will not get submitted.

How should I change my .htaccess file to make sure that these forms are also submitted without www.?

Body:
You could use

RewriteCond %{REQUEST_METHOD} ^GET$

which will rewrite only GET requests, leaving POST requests as they are.

OwnerDisplayName: webjunkie


问:
Bit alignment, 8-bools-in-1
I'm trying to compile the following code:

```<code>union Bool
{
  bool b[8] : 8; // (1)
  bool b0,b1,b2,b3,b4,b5,b6,b7 : 1;
};
</code>```

However the line (1) doesn't compile, whats the syntax for bit aligning an array?

答:
You can't declare an array of bits in C.

The concept of an array is based on a pointer, and you can only have pointers to bytes, not to individual bits within a byte. C Bit fields allow you to pack integer components into less memory than the compiler would by default. An array isn't an integer, so you can't pack an array into a bit field. If you want to read up on the standard, you can find it at ISO/IEC 9899 - Programming languages - C (look for §6.7.2.1).

If you need speed, you could use a union of an array of bools, and if you need a compact memory footprint, you could define macros to provide more convenient access to your bit fields.

ContentLicense: CC BY-SA 3.0

Title: Bit alignment, 8-bools-in-1

Body:
I'm trying to compile the following code:

union Bool
{
  bool b[8] : 8; // (1)
  bool b0,b1,b2,b3,b4,b5,b6,b7 : 1;
};

However the line (1) doesn't compile, whats the syntax for bit aligning an array?


问:
How to remove ' ' in a list in python?
I'm still a noob when it comes to python. I have this list that contains strings. My problem is to remove ''(empty string) from the list.

I've tried to use .remove() in python but it still does not work.

For example, I have a list that contains next data:

```<code>a = ['', 'word', 'three', '', 'five']
</code>```

I just want the output to be:

```<code>a = ['word', 'three', 'five']
</code>```

答:
You can compare the length of the string and append to the list whose length is more than 1

You can do it by:

```<code>a = ['', 'word', 'three', '', 'five']
b = []

for x in a:
    if len(x) > 1:
        b.append(a)
</code>```

You can also do it by list comprehensions

```<code>a = ['', 'word', 'three', '', 'five']
b = [i for i in a if len(i) > 1]
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to remove ' ' in a list in python?

Body:
I'm still a noob when it comes to python. I have this list that contains strings. My problem is to remove ''(empty string) from the list.

I've tried to use .remove() in python but it still does not work.

For example, I have a list that contains next data:

a = ['', 'word', 'three', '', 'five']

I just want the output to be:

a = ['word', 'three', 'five']

Body:
You can compare the length of the string and append to the list whose length is more than 1

You can do it by:

a = ['', 'word', 'three', '', 'five']
b = []

for x in a:
    if len(x) > 1:
        b.append(a)

You can also do it by list comprehensions

a = ['', 'word', 'three', '', 'five']
b = [i for i in a if len(i) > 1]


问:
Group by ID except the NULL records
I am working with the next table:

```<code>**ID    Value   Data**
1        30     25/4
1        20     26/4
1        20     27/4
3        10     25/4
4        20     26/4
5        30     26/4
NULL     50     25/4
NULL     10     26/4
</code>```

And I need to query the table and have the next result:

```<code>**ID    Value   Data**
1        70     25/4
3        10     25/4
4        20     26/4
5        30     26/4
NULL     50     25/4
NULL     10     26/4
</code>```

I have this query:

```<code>select id, sum(value), min(data)
from t
group by id;
</code>```

But the query sums the NULL IDs

How can I do that?

答:
The simplest method is probably union all:

```<code>select id, sum(value), min(data)
from t
where id is not null
group by id
union all
select id, value, data
from t
where id is null;
</code>```

Title: Group by ID except the NULL records

Body:
I am working with the next table:

**ID    Value   Data**
1        30     25/4
1        20     26/4
1        20     27/4
3        10     25/4
4        20     26/4
5        30     26/4
NULL     50     25/4
NULL     10     26/4

And I need to query the table and have the next result:

**ID    Value   Data**
1        70     25/4
3        10     25/4
4        20     26/4
5        30     26/4
NULL     50     25/4
NULL     10     26/4

I have this query:

select id, sum(value), min(data)
from t
group by id;

But the query sums the NULL IDs

How can I do that?

Body:
The simplest method is probably union all:

select id, sum(value), min(data)
from t
where id is not null
group by id
union all
select id, value, data
from t
where id is null;


问:
Undefined reference - despite lib being found by linker
I have a trivial program to test for availability of python development files:

```<code>#include<Python.h>
int main(){Py_Initialize(); Py_Finalize(); }
</code>```

I compile it (with python 2.7 installed) as gcc -I/usr/include/python2.7 -lpython2.7 p.c. It works fine on other machines, except that at mostly-clean chroot of Ubuntu 12.04 (precise) I keep getting

```<code>/tmp/ccj8Mgjb.o: In function `main':
p.c:(.text+0x5): undefined reference to `Py_Initialize'
p.c:(.text+0xa): undefined reference to `Py_Finalize'
collect2: ld returned 1 exit status
</code>```

Headers are installed, /usr/lib/libpython2.7.so exists but the linker nevertheless fails. The symbol is listed in the .so file, and gcc is reading the right libpython2.7.so:

```<code>$ nm -D libpython2.7.so.1.0  | grep Py_Initialize
00000000000c9c20 T Py_Initialize
00000000000c9260 T Py_InitializeEx

$ strace -f gcc -I/usr/include/python2.7 -lpython2.7 /tmp/p.c 2>&1 |grep   libpython2.7 |grep open
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/libpython2.7.so", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/libpython2.7.a", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libpython2.7.so", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libpython2.7.a", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libpython2.7.so", O_RDONLY) = 7
</code>```

Any ideas?

答:
if with python 3.x installed, maybe this command can work:

```<code>g++ hw.cpp `/usr/bin/python3-config --cflags` `/usr/python3-config --ldflags`
</code>```

By the way, you should check you gcc and python version.

As I know, if gcc version is 5.4 and python version is 3.7, it doesn't work.(python 3.5 is work)

When you run /usr/bin/python3-config --cflags, in fact, it is the compile option.

Body:
I have a trivial program to test for availability of python development files:

#include<Python.h>
int main(){Py_Initialize(); Py_Finalize(); }

I compile it (with python 2.7 installed) as gcc -I/usr/include/python2.7 -lpython2.7 p.c. It works fine on other machines, except that at mostly-clean chroot of Ubuntu 12.04 (precise) I keep getting

/tmp/ccj8Mgjb.o: In function `main':
p.c:(.text+0x5): undefined reference to `Py_Initialize'
p.c:(.text+0xa): undefined reference to `Py_Finalize'
collect2: ld returned 1 exit status

Headers are installed, /usr/lib/libpython2.7.so exists but the linker nevertheless fails. The symbol is listed in the .so file, and gcc is reading the right libpython2.7.so:

$ nm -D libpython2.7.so.1.0  | grep Py_Initialize
00000000000c9c20 T Py_Initialize
00000000000c9260 T Py_InitializeEx

$ strace -f gcc -I/usr/include/python2.7 -lpython2.7 /tmp/p.c 2>&1 |grep   libpython2.7 |grep open
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/libpython2.7.so", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/libpython2.7.a", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libpython2.7.so", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libpython2.7.a", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid 10618] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libpython2.7.so", O_RDONLY) = 7

Any ideas?

Body:
if with python 3.x installed, maybe this command can work:

g++ hw.cpp `/usr/bin/python3-config --cflags` `/usr/python3-config --ldflags`

By the way, you should check you gcc and python version.

As I know, if gcc version is 5.4 and python version is 3.7, it doesn't work.(python 3.5 is work)

When you run /usr/bin/python3-config --cflags, in fact, it is the compile option.


问:
On Vimeo, how to keep the video on the last image when video ends?
Until recently, by default, after the video ends, the last image of the video was shown (as the end screens). Now, instead, a blackish background with a replay button on left bottom is shown.

How can I revert to the previous behaviour? In the presets I can't see this option. The nearest I can find is Thumbnail but, as the name tell, it show the thumbnail instead of the last image.

答:
The "Nothing" end screen, which is what you're thinking of, was changed some time ago to "Empty", returning just a blank/black screen. This change occurred as early as April 2017, but may have been later: https://vimeo.com/blog/post/more-customization-more-engagement-new-end-screen/

I found a workaround to emulate the "Nothing" behavior: set your video's end screen to "Text" and set the text to  . This text should render as blank space and grey out the last frame.

Body:
The "Nothing" end screen, which is what you're thinking of, was changed some time ago to "Empty", returning just a blank/black screen. This change occurred as early as April 2017, but may have been later: https://vimeo.com/blog/post/more-customization-more-engagement-new-end-screen/

I found a workaround to emulate the "Nothing" behavior: set your video's end screen to "Text" and set the text to &nbsp;. This text should render as blank space and grey out the last frame.


问:
TypeError: notes.push is not a function
I am running a simple piece of code as shown below.

Basically I want to read the data that is already in 'notes-data.json' and then append it.

```<code>node notes.js
</code>```

```<code>console.log('Starting notes.js');

const fs =  require('fs');

var addNote = (title, body) => {
    var notesString = fs.readFileSync('playground/notes-data.json');
    var notes;
    notes = JSON.parse(notesString);
    var note = {
        title,
        body
    };
    notes.push(note);
    fs.writeFileSync('playground/notes-data.json', JSON.stringify(note));

};

addNote("Hi", "There");

module.exports = {
    addNote: addNote
};
</code>```

Expected: When I run this program it has to add "Hi There".

Actual: Getting the below error.

```<code>(base) prakashp:newproject2 prakashp$ node notes.js
Starting notes.js
/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13
    notes.push(note);
          ^

TypeError: notes.push is not a function
    at addNote (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13:11)
    at Object.<anonymous> (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:18:1)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:499:15)
    at startMainThreadExecution (internal/bootstrap/node.js:436:3)
</code>```

If I comment the below line, I am not getting any errors.

```<code>notes = JSON.parse(notesString);
</code>```

Please help.

答:
Your json file should have an array. Here is the working code you are trying to run on repl site. After the JSON Parse, your variable needs to be an array so you can use push method onto it.

Also I found one more mistake, instead of saving note to your json file, you should be saving notes. As you will overwrite on object again to the file & will cause the app to crash again.
Use this below line.

fs.writeFileSync('playground/notes-data.json', JSON.stringify(notes));

Sample Code

Title: TypeError: notes.push is not a function

Body:
I am running a simple piece of code as shown below.

Basically I want to read the data that is already in 'notes-data.json' and then append it.

node notes.js

console.log('Starting notes.js');

const fs =  require('fs');

var addNote = (title, body) => {
    var notesString = fs.readFileSync('playground/notes-data.json');
    var notes;
    notes = JSON.parse(notesString);
    var note = {
        title,
        body
    };
    notes.push(note);
    fs.writeFileSync('playground/notes-data.json', JSON.stringify(note));

};

addNote("Hi", "There");

module.exports = {
    addNote: addNote
};

Expected: When I run this program it has to add "Hi There".

Actual: Getting the below error.

(base) prakashp:newproject2 prakashp$ node notes.js
Starting notes.js
/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13
    notes.push(note);
          ^

TypeError: notes.push is not a function
    at addNote (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13:11)
    at Object.<anonymous> (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:18:1)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:499:15)
    at startMainThreadExecution (internal/bootstrap/node.js:436:3)

If I comment the below line, I am not getting any errors.

notes = JSON.parse(notesString);

Please help.


问:
Calling functions and returning values
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

```<code> void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }
</code>```

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

答: The simplest would be return a pair<string,int> from the function. So your function signarutre would be pair<string,int> getRequiredInfo(const string& s1, const string& s2, constr string& s3);. You can then access the string and int part usinf first and second members of the pair.

Title: Calling functions and returning values

Body:
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

 void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...


问:
Call to undefined method App\Models\Car::setCreatedAt() - Laravel - 5.8.16
I am using latest Laravel. I have a model Car - id | name | * timestamp columns:

```<code>namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Car extends Model{
    protected $fillable = [
        'name'
    ];
}
</code>```

Cars migration:

```<code>public function up()
{
    Schema::create('cars', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('name')->nullable();
        $table->timestamps();
    });
</code>```

I am trying to save new row in cars table in the controller:

```<code>    $car = new Car();
    $car->name = 'example';
    $car->save();
</code>```

, but for $car->save(), I am getting this error:

Call to undefined method App\Models\Car::setCreatedAt()

Even, If I create new migration/model create_table_test (table with the same columns), I am getting the same error.

EDIT with stacktrace:

65 BadMethodCallException in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50

64 Illuminate\Database\Eloquent\Model:throwBadMethodCallException in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:36

63 Illuminate\Database\Eloquent\Model:forwardCallTo in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1614

62 Illuminate\Database\Eloquent\Model:__call in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php:47

61 Illuminate\Database\Eloquent\Model:updateTimestamps in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:791

60 Illuminate\Database\Eloquent\Model:performInsert in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:663

59 Illuminate\Database\Eloquent\Model:save in /mnt/e/xampp/htdocs/room2/project/app/Http/Controllers/Admin/CarsController.php:33

58 App\Http\Controllers\Admin\CarsController:importCars/mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54

57 call_user_func_array in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54

56 Illuminate\Routing\Controller:callAction in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php:45

55 Illuminate\Routing\ControllerDispatcher:dispatch in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Route.php:219

54 Illuminate\Routing\Route:runController in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Route.php:176

53 Illuminate\Routing\Route:run in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Router.php:680

52 Illuminate\Routing\Router:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30

51 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/barryvdh/laravel-stack-middleware/src/ClosureHttpKernel.php:30

50 Barryvdh\StackMiddleware\ClosureHttpKernel:handle in /mnt/e/xampp/htdocs/room2/project/vendor/helthe/turbolinks/StackTurbolinks.php:51

49 Helthe\Component\Turbolinks\StackTurbolinks:handle in /mnt/e/xampp/htdocs/room2/project/vendor/barryvdh/laravel-stack-middleware/src/ClosureMiddleware.php:36

48 Barryvdh\StackMiddleware\ClosureMiddleware:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163

47 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53

46 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php:41

45 Illuminate\Routing\Middleware\SubstituteBindings:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163

44 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53

43 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php:43

42 Illuminate\Auth\Middleware\Authenticate:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163

41 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53

40 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:75

39 Illuminate\Foundation\Http\Middleware\VerifyCsrfToken:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163

38 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
  ......

答:
I just re-install Laravel.

Delete vendor folder ;

Delete composer.lock;

composer update in the console.

Thanks, @Jonas Staudenmeir for your help.

Body:
I am using latest Laravel. I have a model Car - id | name | * timestamp columns:

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Car extends Model{
    protected $fillable = [
        'name'
    ];
}

Cars migration:

public function up()
{
    Schema::create('cars', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('name')->nullable();
        $table->timestamps();
    });

I am trying to save new row in cars table in the controller:

    $car = new Car();
    $car->name = 'example';
    $car->save();

, but for $car->save(), I am getting this error:

Call to undefined method App\Models\Car::setCreatedAt()

Even, If I create new migration/model create_table_test (table with the same columns), I am getting the same error.

EDIT with stacktrace:

65 BadMethodCallException in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50

64 Illuminate\Database\Eloquent\Model:throwBadMethodCallException in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:36

63 Illuminate\Database\Eloquent\Model:forwardCallTo in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1614

62 Illuminate\Database\Eloquent\Model:__call in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php:47

61 Illuminate\Database\Eloquent\Model:updateTimestamps in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:791

60 Illuminate\Database\Eloquent\Model:performInsert in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:663

59 Illuminate\Database\Eloquent\Model:save in /mnt/e/xampp/htdocs/room2/project/app/Http/Controllers/Admin/CarsController.php:33

58 App\Http\Controllers\Admin\CarsController:importCars/mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54

57 call_user_func_array in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54

56 Illuminate\Routing\Controller:callAction in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php:45

55 Illuminate\Routing\ControllerDispatcher:dispatch in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Route.php:219

54 Illuminate\Routing\Route:runController in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Route.php:176

53 Illuminate\Routing\Route:run in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Router.php:680

52 Illuminate\Routing\Router:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30

51 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/barryvdh/laravel-stack-middleware/src/ClosureHttpKernel.php:30

50 Barryvdh\StackMiddleware\ClosureHttpKernel:handle in /mnt/e/xampp/htdocs/room2/project/vendor/helthe/turbolinks/StackTurbolinks.php:51

49 Helthe\Component\Turbolinks\StackTurbolinks:handle in /mnt/e/xampp/htdocs/room2/project/vendor/barryvdh/laravel-stack-middleware/src/ClosureMiddleware.php:36

48 Barryvdh\StackMiddleware\ClosureMiddleware:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163

47 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53

46 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php:41

45 Illuminate\Routing\Middleware\SubstituteBindings:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163

44 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53

43 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php:43

42 Illuminate\Auth\Middleware\Authenticate:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163

41 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53

40 Illuminate\Routing\Pipeline:Illuminate\Routing{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:75

39 Illuminate\Foundation\Http\Middleware\VerifyCsrfToken:handle in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163

38 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline{closure} in /mnt/e/xampp/htdocs/room2/project/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
  ......


问:
Python3 csv writer failing, exiting on error "TypeError: 'newline' is an invalid keyword argument for this function
What I'm trying to do:

I'm trying to change the formatting on a csv file from space delimited to comma delimited.

What I've done:

I can ingest the csv file just fine, and print the output row-by-row to the console. That code looks like this:

```<code>with open(txtpath, mode='r', newline='') as f:
    fReader = csv.reader(f)
        for rows in fReader:
            print(rows)
</code>```

This does exactly what it's supposed to, and spot checking the output confirms that the rows are being read correctly.

The Problem:

According to the official Python3 Documentation on csv.writer, "If csvfile is a file object, it should be opened with newline='' 1." My code looks like this:

```<code>with open(csvpath, 'w') as g:
        gWriter = csv.writer(g, newline='')
        gWriter.writerows(rows)
</code>```

so all together, it looks like this:

```<code>with open(txtpath, mode='r', newline='') as f:
    fReader = csv.reader(f)
    for rows in fReader:
        print(rows)
        with open(csvpath, 'w') as g:
            gWriter = csv.writer(g, newline='')
            gWriter.writerows(rows)
</code>```

However, when I run the code with both Pycharm (Anacondas 3.4 selected as project interpreter) and from the console with python3 mycode.py, both results tell me that newline "is an invalid keyword argument for this function" and references line 42, which is where my writer object is instantiated. I ran it through the debugger and it craps out as soon as I try to create the writer object. If I don't add the newline argument it asks for a dialect specification, so that doesn't work, either.

I'm sure there's something blindingly obvious that I'm missing, but I can't see it.

答:
The following will do

```<code>with open('filename_inCSV.csv',mode='r') as csvfile:
</code>```

or

```<code>with open('filename_inCSV.csv','r') as csvfile:
</code>```

Body:
What I'm trying to do:

I'm trying to change the formatting on a csv file from space delimited to comma delimited.

What I've done:

I can ingest the csv file just fine, and print the output row-by-row to the console. That code looks like this:

with open(txtpath, mode='r', newline='') as f:
    fReader = csv.reader(f)
        for rows in fReader:
            print(rows)

This does exactly what it's supposed to, and spot checking the output confirms that the rows are being read correctly.

The Problem:

According to the official Python3 Documentation on csv.writer, "If csvfile is a file object, it should be opened with newline='' 1." My code looks like this:

with open(csvpath, 'w') as g:
        gWriter = csv.writer(g, newline='')
        gWriter.writerows(rows)

so all together, it looks like this:

with open(txtpath, mode='r', newline='') as f:
    fReader = csv.reader(f)
    for rows in fReader:
        print(rows)
        with open(csvpath, 'w') as g:
            gWriter = csv.writer(g, newline='')
            gWriter.writerows(rows)

However, when I run the code with both Pycharm (Anacondas 3.4 selected as project interpreter) and from the console with python3 mycode.py, both results tell me that newline "is an invalid keyword argument for this function" and references line 42, which is where my writer object is instantiated. I ran it through the debugger and it craps out as soon as I try to create the writer object. If I don't add the newline argument it asks for a dialect specification, so that doesn't work, either.

I'm sure there's something blindingly obvious that I'm missing, but I can't see it.

Body:
The following will do

with open('filename_inCSV.csv',mode='r') as csvfile:

or

with open('filename_inCSV.csv','r') as csvfile:


问:
Django Rest Framework - Query for exact match on two fields in a mapping table
I'm using DRF and trying to search a mapping table for exact matches so I can update that record.

I have the following tables:

```<code>site
- id
- location
- address

circuit
- id
- name
- ref

sitecircuits
- site_id
- circuit_id
- active_link
</code>```

my current DRF config as below:

view

```<code>class MonitoringConnectivitySet(viewsets.ModelViewSet):
    queryset = SiteCircuits.objects.all()
    serializer_class = MonitoringSerializerConnectivity
    permission_classes = (IsAdminUser,)
    filter_class = SiteCircuits
    filter_backends = (filters.SearchFilter,)
    search_fields = ('site__id','circuit__id')
</code>```

serialiser

```<code>class MonitoringSerializerConnectivity(serializers.ModelSerializer):

    class Meta:
        model = SiteCircuits
        fields = ('site_id','circuit_id','active_link',)
</code>```

url

```<code>router.register(r'conn_set', views.MonitoringConnectivitySet)
</code>```

this url http://localhost:8100/api/conn_set/?site__id=8&circuit__id=7
returns all the results (as I doesn't search at all)

ive also tried using the below

url:

```<code>path('conn_set/<int:site_id>/<int:circuit_id>/', views.MonitoringConnectivitySet)
</code>```

serialiser:

```<code>class MonitoringSerializerConnectivity(serializers.ModelSerializer):

    class Meta:
        model = SiteCircuits
        fields = ('site_id','circuit_id','active_link',)

    def get_queryset(self):
            site_id = self.kwargs['site_id']
            circuit_id = self.kwargs['circuit_id']
            return SiteCircuits.objects.filter(site_id=site_id,circuit_id=circuit_id)
</code>```

view:

```<code>class MonitoringConnectivitySet(viewsets.ModelViewSet):
    queryset = SiteCircuits.objects.all()
    serializer_class = MonitoringSerializerConnectivity
    permission_classes = (IsAdminUser,)
</code>```

which also fails when using the url (indicating it only takes one value not two
http://localhost:8100/api/conn_set/8/7

does anyone know the right combination here? is there any special needed to be done to filter and update the mapping table?

Thanks

EDIT

when overriding the QuerySet I now get the following error:

```<code>Traceback:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
  116.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  495.             response = self.handle_exception(exc)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
  455.             self.raise_uncaught_exception(exc)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in raise_uncaught_exception
  466.         raise exc

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  492.             response = handler(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in list
  40.         queryset = self.filter_queryset(self.get_queryset())

File "/usr/local/lib/python3.6/site-packages/rest_framework/generics.py" in filter_queryset
  152.             queryset = backend().filter_queryset(self.request, queryset, self)

File "/usr/local/lib/python3.6/site-packages/django_filters/rest_framework/backends.py" in filter_queryset
  90.         filterset = self.get_filterset(request, queryset, view)

File "/usr/local/lib/python3.6/site-packages/django_filters/rest_framework/backends.py" in get_filterset
  36.         return filterset_class(**kwargs)

File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in __init__
  501.                 raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))

Exception Type: TypeError at /api/conn_set/
Exception Value: SiteCircuits() got an unexpected keyword argument 'data'
</code>```

答:
Ive have achieved my desired outcome with the below:

url:

```<code>path('conn_set/<int:site_id>/<int:circuit_id>/', views.MonitoringConnectivitySet.as_view())
</code>```

serialzier:

```<code>class MonitoringSerializerConnectivity(serializers.ModelSerializer):

    class Meta:
        model = SiteCircuits
        fields = ('site_id','circuit_id','active_link',)
</code>```

view:

```<code>class MonitoringConnectivitySet(generics.GenericAPIView):
    serializer_class = MonitoringSerializerConnectivity
    permission_classes = (IsAdminUser,)

    def get(self, request, *args, **kwargs):
        site_id = kwargs.get('site_id', '0')
        circuit_id = kwargs.get('circuit_id', '0')
        instance = get_object_or_404(SiteCircuits, site_id=site_id, circuit_id=circuit_id)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def put(self, request, *args, **kwargs):
        site_id = kwargs.get('site_id', '0')
        circuit_id = kwargs.get('circuit_id', '0')
        instance = get_object_or_404(SiteCircuits, site_id=site_id, circuit_id=circuit_id)
        serializer = MonitoringSerializerConnectivity(instance, data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_200_OK)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
</code>```

Body:
I'm using DRF and trying to search a mapping table for exact matches so I can update that record.

I have the following tables:

site
- id
- location
- address

circuit
- id
- name
- ref

sitecircuits
- site_id
- circuit_id
- active_link

my current DRF config as below:

view

class MonitoringConnectivitySet(viewsets.ModelViewSet):
    queryset = SiteCircuits.objects.all()
    serializer_class = MonitoringSerializerConnectivity
    permission_classes = (IsAdminUser,)
    filter_class = SiteCircuits
    filter_backends = (filters.SearchFilter,)
    search_fields = ('site__id','circuit__id')

serialiser

class MonitoringSerializerConnectivity(serializers.ModelSerializer):

    class Meta:
        model = SiteCircuits
        fields = ('site_id','circuit_id','active_link',)

url

router.register(r'conn_set', views.MonitoringConnectivitySet)

this url http://localhost:8100/api/conn_set/?site__id=8&circuit__id=7
returns all the results (as I doesn't search at all)

ive also tried using the below

url:

path('conn_set/<int:site_id>/<int:circuit_id>/', views.MonitoringConnectivitySet)

serialiser:

class MonitoringSerializerConnectivity(serializers.ModelSerializer):

    class Meta:
        model = SiteCircuits
        fields = ('site_id','circuit_id','active_link',)

    def get_queryset(self):
            site_id = self.kwargs['site_id']
            circuit_id = self.kwargs['circuit_id']
            return SiteCircuits.objects.filter(site_id=site_id,circuit_id=circuit_id)

view:

class MonitoringConnectivitySet(viewsets.ModelViewSet):
    queryset = SiteCircuits.objects.all()
    serializer_class = MonitoringSerializerConnectivity
    permission_classes = (IsAdminUser,)

which also fails when using the url (indicating it only takes one value not two
http://localhost:8100/api/conn_set/8/7

does anyone know the right combination here? is there any special needed to be done to filter and update the mapping table?

Thanks

EDIT

when overriding the QuerySet I now get the following error:

Traceback:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
  116.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  495.             response = self.handle_exception(exc)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
  455.             self.raise_uncaught_exception(exc)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in raise_uncaught_exception
  466.         raise exc

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  492.             response = handler(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in list
  40.         queryset = self.filter_queryset(self.get_queryset())

File "/usr/local/lib/python3.6/site-packages/rest_framework/generics.py" in filter_queryset
  152.             queryset = backend().filter_queryset(self.request, queryset, self)

File "/usr/local/lib/python3.6/site-packages/django_filters/rest_framework/backends.py" in filter_queryset
  90.         filterset = self.get_filterset(request, queryset, view)

File "/usr/local/lib/python3.6/site-packages/django_filters/rest_framework/backends.py" in get_filterset
  36.         return filterset_class(**kwargs)

File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in __init__
  501.                 raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))

Exception Type: TypeError at /api/conn_set/
Exception Value: SiteCircuits() got an unexpected keyword argument 'data'

Body:
Ive have achieved my desired outcome with the below:

url:

path('conn_set/<int:site_id>/<int:circuit_id>/', views.MonitoringConnectivitySet.as_view())

serialzier:

class MonitoringSerializerConnectivity(serializers.ModelSerializer):

    class Meta:
        model = SiteCircuits
        fields = ('site_id','circuit_id','active_link',)

view:

class MonitoringConnectivitySet(generics.GenericAPIView):
    serializer_class = MonitoringSerializerConnectivity
    permission_classes = (IsAdminUser,)

    def get(self, request, *args, **kwargs):
        site_id = kwargs.get('site_id', '0')
        circuit_id = kwargs.get('circuit_id', '0')
        instance = get_object_or_404(SiteCircuits, site_id=site_id, circuit_id=circuit_id)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def put(self, request, *args, **kwargs):
        site_id = kwargs.get('site_id', '0')
        circuit_id = kwargs.get('circuit_id', '0')
        instance = get_object_or_404(SiteCircuits, site_id=site_id, circuit_id=circuit_id)
        serializer = MonitoringSerializerConnectivity(instance, data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_200_OK)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)


问:
changing object keys acording to an array
i have an object and 2 arrays. i want to change object keys according to arr2, object keys and arr1 values are identical while arr1 and arr2 placement of values in arrays are identical but not values themselves, while i don't want to ask how to solve it want to know how should i approach this problem, thank you for your time

```<code>    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]
</code>```

expected outcome

```<code>    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}
</code>```

答:
Assuming you want to preserve keys names not present on arr1 on the new object. Then you can first create a Map between old names and new names (In case ES6 is not an option for you, use an object here for the mapping). Then you can traverse the Object.entries() with Array.reduce() to generate the new object, where only the related keys names are mapped to new ones, and the rest are preserved.

const obj = {
  name1: "some value 1",
  name3: "some value 2",
  name2: "some value 3",
  name4: "some value 4",
  name5: "some value 5"
}

const arr1 = ["name1", "name2", "name3"];
const arr2 = ["Name1", "Name2", "Name3"];

// Create a map between old names and new names.
let keysMap = new Map(arr1.map((key, idx) => [key, arr2[idx]]));

// Generate the new object, preserving non-mapped keys names.
let newObj = Object.entries(obj).reduce((acc, [k, v]) =>
{
    acc[keysMap.has(k) ? keysMap.get(k) : k] = v;
    return acc;
}, {});

console.log(newObj);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Body:
i have an object and 2 arrays. i want to change object keys according to arr2, object keys and arr1 values are identical while arr1 and arr2 placement of values in arrays are identical but not values themselves, while i don't want to ask how to solve it want to know how should i approach this problem, thank you for your time

    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]

expected outcome

    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}

Body:
Assuming you want to preserve keys names not present on arr1 on the new object. Then you can first create a Map between old names and new names (In case ES6 is not an option for you, use an object here for the mapping). Then you can traverse the Object.entries() with Array.reduce() to generate the new object, where only the related keys names are mapped to new ones, and the rest are preserved.

const obj = {
  name1: "some value 1",
  name3: "some value 2",
  name2: "some value 3",
  name4: "some value 4",
  name5: "some value 5"
}

const arr1 = ["name1", "name2", "name3"];
const arr2 = ["Name1", "Name2", "Name3"];

// Create a map between old names and new names.
let keysMap = new Map(arr1.map((key, idx) => [key, arr2[idx]]));

// Generate the new object, preserving non-mapped keys names.
let newObj = Object.entries(obj).reduce((acc, [k, v]) =>
{
    acc[keysMap.has(k) ? keysMap.get(k) : k] = v;
    return acc;
}, {});

console.log(newObj);

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


问:
php address request
i have this request method:

```<code>if (!$_REQUEST['0'])  {
    echo "Address missing...";
    die();
} else {
    code
    code etc.
}
</code>```

And address is: http://localhost/api.php?0=address

If I open: api.php?0=0 I should get another error which says address doesn't correct. But I get Address missing... In my opinion something wrong with:

```<code>if (!$_REQUEST['0'])
</code>```

Any ideas?

答:
```<code>if(!isset($_REQUEST['0']))
{
    die("Address not provided");
}
else
{
    // code
}
</code>```

Title: php address request

Body:
i have this request method:

if (!$_REQUEST['0'])  {
    echo "Address missing...";
    die();
} else {
    code
    code etc.
}

And address is: http://localhost/api.php?0=address

If I open: api.php?0=0 I should get another error which says address doesn't correct. But I get Address missing... In my opinion something wrong with:

if (!$_REQUEST['0'])

Any ideas?


问:
How to group contents in an array of dictionary?
I know this could have been solved easily from backend but was curious to know if there is any efficient way to solve this issue from front end using js.

I have an array

```<code>[
 {
    id: 11
    ruleDesc: "rule 1 "
 },
{
    id: 15
    ruleDesc: "rule 2 "
 },
{
    id: 12
    ruleDesc: "rule 3 "
 },
{
    id: 11
    ruleDesc: "rule 4 "
 },
{
    id: 11
    ruleDesc: "rule 5 "
 },

]
</code>```

What I'm expecting is

```<code>[
  {
        id: 11
        ruleDesc: "rule 1 "
        ruleDesc: "rule 4 "
        ruleDesc: "rule 5 "
     },
{
        id: 12
        ruleDesc: "rule 3 "
     },
{
        id: 15
        ruleDesc: "rule 2 "
     },
]
</code>```

答:
This is similar to the answer from Masheer Ali, but I think the reduction is a little nicer:

const transform = arr => Object .values (arr .reduce ((a, {id, ruleDesc}) =>
  ({...a, [id]: {id, ruleDesc: [...( (a [id] || {}) .ruleDesc || [] ), ruleDesc]}}),
  {}
))

const rules = [{id: 11, ruleDesc: "rule 1 "}, {id: 15, ruleDesc: "rule 2 "}, {id: 12, ruleDesc: "rule 3 "}, {id: 11, ruleDesc: "rule 4 "}, {id: 11, ruleDesc: "rule 5 "}]

console .log (
  transform (rules)
)```
</div>
</div>
</p>

<p>One advantage is that if you have additional properties you want to merge, it's only a minor tweak:</p>

<pre class="lang-js prettyprint-override"><code>const transform = arr => Object .values (arr .reduce ((a, {id, ruleDesc, ...rest}) =>
  ({...a, [id]: {...(a[id] || {}), id,  ruleDesc: [...((a[id] || {}).ruleDesc || []) , ruleDesc], ...rest}}),
  {}
))
</code>```

Body:
I know this could have been solved easily from backend but was curious to know if there is any efficient way to solve this issue from front end using js.

I have an array

[
 {
    id: 11
    ruleDesc: "rule 1 "
 },
{
    id: 15
    ruleDesc: "rule 2 "
 },
{
    id: 12
    ruleDesc: "rule 3 "
 },
{
    id: 11
    ruleDesc: "rule 4 "
 },
{
    id: 11
    ruleDesc: "rule 5 "
 },

]

What I'm expecting is

[
  {
        id: 11
        ruleDesc: "rule 1 "
        ruleDesc: "rule 4 "
        ruleDesc: "rule 5 "
     },
{
        id: 12
        ruleDesc: "rule 3 "
     },
{
        id: 15
        ruleDesc: "rule 2 "
     },
]

Body:
This is similar to the answer from Masheer Ali, but I think the reduction is a little nicer:

const transform = arr => Object .values (arr .reduce ((a, {id, ruleDesc}) =>
  ({...a, [id]: {id, ruleDesc: [...( (a [id] || {}) .ruleDesc || [] ), ruleDesc]}}),
  {}
))

const rules = [{id: 11, ruleDesc: "rule 1 "}, {id: 15, ruleDesc: "rule 2 "}, {id: 12, ruleDesc: "rule 3 "}, {id: 11, ruleDesc: "rule 4 "}, {id: 11, ruleDesc: "rule 5 "}]

console .log (
  transform (rules)
)

One advantage is that if you have additional properties you want to merge, it's only a minor tweak:

const transform = arr => Object .values (arr .reduce ((a, {id, ruleDesc, ...rest}) =>
  ({...a, [id]: {...(a[id] || {}), id,  ruleDesc: [...((a[id] || {}).ruleDesc || []) , ruleDesc], ...rest}}),
  {}
))


问:
R - How to create a data frame from a data frame with conditions?
I have a data frame that has many columns, but I want to create another data frame that only has the columns race and spouse. I have this sample of data.

```<code>  gender name    race realm  spouse
1  Female Adanel  Men  Gondor  Not Married
2  Male   Lagduf  Orc  Mordor  Married
2  Male   Boromir Men  Gondor  Married
</code>```

I would like to create another data frame with race and spouse (where the creature is "married") so that I can plot a graph from it showing the marriage variation between races. The only data that should appear in the new data frame would be the following one:

```<code>  race spouse
1 Orc  Married
2 Men  Married
</code>```

I would like to get the columns race and spouse(where the creature is "Married"). I have tried something like this:

```<code>marriedCreatures <- data %>% filter(spouse == "Married" & race)
</code>```

As I've recently started working with R I don't know how I am supposed to create this new data frame from other data frame's columns.

I would appreciate if anyone could help me with that.

Thanks!

答:
```<code>df <- data.frame(
  gender = c("Female", "Male", "Male"),
  name = c("Adanel", "Lagduf", "Boromir"),
  race = c("Men", "Orc", "Men"),
  spouse = c("Not married", "Married", "Married")
)

library(dplyr)

# base R
marriedCreatures <- df[df$spouse == "Married", c("race", "spouse")]
marriedCreatures

# dplyr
marriedCreatures <- df %>%
  dplyr::filter(spouse == "Married") %>%
  dplyr::select(race, spouse)
marriedCreatures
</code>```

If prefer the dplyr version, but a one-liner should be nice too :-)

Body:
I have a data frame that has many columns, but I want to create another data frame that only has the columns race and spouse. I have this sample of data.

  gender name    race realm  spouse
1  Female Adanel  Men  Gondor  Not Married
2  Male   Lagduf  Orc  Mordor  Married
2  Male   Boromir Men  Gondor  Married

I would like to create another data frame with race and spouse (where the creature is "married") so that I can plot a graph from it showing the marriage variation between races. The only data that should appear in the new data frame would be the following one:

  race spouse
1 Orc  Married
2 Men  Married

I would like to get the columns race and spouse(where the creature is "Married"). I have tried something like this:

marriedCreatures <- data %>% filter(spouse == "Married" & race)

As I've recently started working with R I don't know how I am supposed to create this new data frame from other data frame's columns.

I would appreciate if anyone could help me with that.

Thanks!

Body:
df <- data.frame(
  gender = c("Female", "Male", "Male"),
  name = c("Adanel", "Lagduf", "Boromir"),
  race = c("Men", "Orc", "Men"),
  spouse = c("Not married", "Married", "Married")
)

library(dplyr)

# base R
marriedCreatures <- df[df$spouse == "Married", c("race", "spouse")]
marriedCreatures

# dplyr
marriedCreatures <- df %>%
  dplyr::filter(spouse == "Married") %>%
  dplyr::select(race, spouse)
marriedCreatures

If prefer the dplyr version, but a one-liner should be nice too :-)


问:
Is there any way to implement Initializer lists (kind of) in older version of c++ (Before c++11)?
i have tried to implement (kind of :) Initializer lists in older version of c++. like below..

```<code>#include <vector>
#include <cstdarg>
#include <iostream>

using namespace std;

template <class T>
vector <T> VEC_VA(size_t argCount,T arg1, ... )
{
    va_list arguments;
    vector <T> sList;

    va_start ( arguments, argCount);
    for ( int x = 0; x < (int)argCount; x++ )
        sList.push_back(va_arg ( arguments, T));
    va_end ( arguments );

    return sList;
}

struct Test
{
    Test(int _x,std::string _s):x(_x),s(_s){}
    int x;
    std::string s;
};

void methodWithArgs(vector<Test> testObjs)
{
    cout<<"Size:"<<testObjs.size()<<endl;
    for (std::vector<Test>::const_iterator it = testObjs.begin();it != testObjs.end();++it)
        std::cout << it->x <<":"<< it->s.c_str()<< std::endl;
}

int main()
{
    methodWithArgs(VEC_VA(2,Test(1,"one"),Test(2,"two")));
    return 0;
}
</code>```

But this kind of implementation works in Visual studio 2012 (v11.0). But not in Linux g++ compiler. And ended with an Error: "cannot pass objects of non-trivially-copyable type ‘struct Test’ through ‘...’"

So is there any better idea?

答:
If you are willing to accept a slightly different syntax then all you need is a version of vector::push_back() that returns a reference to the vector. Something like this:

```<code>#include <vector>
#include <iostream>

template<typename T>
class VEC_VA_HELP {
   std::vector<T> vector;
public:
   VEC_VA_HELP(T arg1) : vector() { vector.push_back(arg1); }
   VEC_VA_HELP &operator()(T arg) { vector.push_back(arg); return *this; }
   operator std::vector<T> &() { return vector; }
};
template<typename T>
VEC_VA_HELP<T> VEC_VA(T arg1) { return VEC_VA_HELP<T>(arg1); }

struct Test {
   Test(int _x) : x(_x) {}
   int x;
};

void methodWithArgs(std::vector<Test> const &testObjs) {
   std::cout << testObjs.size() << std::endl;
   for (std::vector<Test>::const_iterator it = testObjs.begin();
        it != testObjs.end();
        ++it)
      std::cout << it->x << std::endl;
}

int
main(void)
{
   methodWithArgs(VEC_VA(Test(1))(Test(2))(Test(3)));
   return 0;
}
</code>```

Also recursive templates come to mind but I am not sure how clean the syntax would be with them. See also this question about overloading the comma operator.

Body:
i have tried to implement (kind of :) Initializer lists in older version of c++. like below..

#include <vector>
#include <cstdarg>
#include <iostream>

using namespace std;

template <class T>
vector <T> VEC_VA(size_t argCount,T arg1, ... )
{
    va_list arguments;
    vector <T> sList;

    va_start ( arguments, argCount);
    for ( int x = 0; x < (int)argCount; x++ )
        sList.push_back(va_arg ( arguments, T));
    va_end ( arguments );

    return sList;
}

struct Test
{
    Test(int _x,std::string _s):x(_x),s(_s){}
    int x;
    std::string s;
};

void methodWithArgs(vector<Test> testObjs)
{
    cout<<"Size:"<<testObjs.size()<<endl;
    for (std::vector<Test>::const_iterator it = testObjs.begin();it != testObjs.end();++it)
        std::cout << it->x <<":"<< it->s.c_str()<< std::endl;
}

int main()
{
    methodWithArgs(VEC_VA(2,Test(1,"one"),Test(2,"two")));
    return 0;
}

But this kind of implementation works in Visual studio 2012 (v11.0). But not in Linux g++ compiler. And ended with an Error: "cannot pass objects of non-trivially-copyable type ‘struct Test’ through ‘...’"

So is there any better idea?

Body:
If you are willing to accept a slightly different syntax then all you need is a version of vector::push_back() that returns a reference to the vector. Something like this:

#include <vector>
#include <iostream>

template<typename T>
class VEC_VA_HELP {
   std::vector<T> vector;
public:
   VEC_VA_HELP(T arg1) : vector() { vector.push_back(arg1); }
   VEC_VA_HELP &operator()(T arg) { vector.push_back(arg); return *this; }
   operator std::vector<T> &() { return vector; }
};
template<typename T>
VEC_VA_HELP<T> VEC_VA(T arg1) { return VEC_VA_HELP<T>(arg1); }

struct Test {
   Test(int _x) : x(_x) {}
   int x;
};

void methodWithArgs(std::vector<Test> const &testObjs) {
   std::cout << testObjs.size() << std::endl;
   for (std::vector<Test>::const_iterator it = testObjs.begin();
        it != testObjs.end();
        ++it)
      std::cout << it->x << std::endl;
}

int
main(void)
{
   methodWithArgs(VEC_VA(Test(1))(Test(2))(Test(3)));
   return 0;
}

Also recursive templates come to mind but I am not sure how clean the syntax would be with them. See also this question about overloading the comma operator.


问:
IBM API Connect "XML to JSON" policy appends $ char and does not give expected JSON
Hi I am using "XML to JSON" policy to change my XML into JSON but it is adding an extra "$" character. not sure what is the benefit of having it and how to get rid of that.
Currently:
 hello becomes { "a": { "$" : "hello" } }
Expecting it to return { "a": "hello" }

Can anyone please help here?

答: The best way to do XML to JSON and JSON to XML transforms is using the mapping node,  if you use the "automatic" nodes, it is slower than the mapping nodes and also might have weird behaviours like adding "$"  or later removing them...   (according to my experience, if the XML has attributes, it might remove the "$".. so I moved to mapping nodes and ready..) </p>


问:
Error while updating property 'd' of a view managed by: RNSVGPath
I am struggling for last few days with the below error in react native.

My intention:
Dynamically fetch chart data and plot multiple charts on my page.

Whenever I have a succesful fetch the sData[] gets filled. However my chart keeps thrwoing an error:
Error while updating property 'd' of a view managed by: RNSVGPath
null
Attempt to invoke interface method 'int java.Charsequence.length()' on a null object reference

If the fetch fails and my sData is set to default array [5,4,3,2,1] as below in the code, the chart is able to render.

What am i missing/messing? Please help.

```<code>import React, { Component } from 'react';
import {AsyncStorage} from 'react-native';
import { LineChart, Grid } from 'react-native-svg-charts';
import { Container, Header, Content, List, ListItem, Text, Left, Right, Body , Button, Title} from 'native-base';

const data = [1,2,3,4,5,6,7];

export default class SomeDetails extends Component {

  constructor(props)
  {
    super(props);
    this.state = { 'user': '',
                    'email': '',
                    'privLevel': '',
                    'phNum': '',
                    UserApiUrl: '<SOMEAPI>',
                    sData: [],
                    someData: ''
     }
  }

  componentDidMount() {
    this._loadInitialState().done();
  }

  _loadInitialState = async () => {
    var uPhVal = await AsyncStorage.getItem('uPh');
    var uEmailVal = await AsyncStorage.getItem('uEmail');
    var uPrivVal = await AsyncStorage.getItem('uPlevel');
    var uName = await AsyncStorage.getItem('username');

    if(uName !== null)
    {
      this.setState({'user': uName});
      this.setState({'phNum': uPhVal});
      this.setState({'email': uEmailVal});
      this.setState({'privLevel':uPrivVal})
    }

    var postString = "SOME STRING FOR MY API"
    console.log(postString);
    response  = await fetch(this.state.UserApiUrl, {
        method: 'POST',
        body: postString
    })
    res = await response.json();
    console.log(res.success);
    if (res.success == "true") {
        this.setState({ someData: res.someLatestVal });
        var dataItems = this.state.someData.split(';');
        for(let j=0;j<dataItems.length; j++)
        {
            var dataI = dataItems[j].split(':');
            this.setState({sData: this.state.sData.concat([dataI[0]]) } );
        }
    }
    else {
        //  console.log("Req: Unable to fetch");
        this.setState({sData: [1,2,3,4,5]});
        this.setState({loading: true});
    }

     console.log(this.state.sData);

  }

  render() {

    const { navigation } = this.props;
    const someName = navigation.getParam('someName', 'no-name');

    return (
      <Container>
        <Content>
          <List>
            <ListItem>
              <Text>Sensorname: { someName } </Text>
            </ListItem>
            <LineChart
                style={{ height: 70, width: 120 }}
                data={ this.state.sData }
                svg={{ stroke: 'rgb(134, 65, 244)' }}
                contentInset={{ top: 20, bottom: 20 }}
                >
            <Grid/>
            </LineChart>

          </List>
        </Content>
      </Container>
    );
  }
}
</code>```

答:
We fixed this by ensuring VictoryLine always gets at least 2 data points.  If passed only one data point it may crash.

Here's the working code with a simple check for whether a data set has at least two items:

      {dataSetsWithGaps.map(coordList =>
        coordList.length < 2 ? null : (
          <VictoryLine
            key={`line_${coordList[0].x.toString()}`}
            interpolation={interpolationMethod}
            data={coordList}
          />
        ),
      )}
```

Body:
I am struggling for last few days with the below error in react native.

My intention:
Dynamically fetch chart data and plot multiple charts on my page.

Whenever I have a succesful fetch the sData[] gets filled. However my chart keeps thrwoing an error:
Error while updating property 'd' of a view managed by: RNSVGPath
null
Attempt to invoke interface method 'int java.Charsequence.length()' on a null object reference

If the fetch fails and my sData is set to default array [5,4,3,2,1] as below in the code, the chart is able to render.

What am i missing/messing? Please help.

import React, { Component } from 'react';
import {AsyncStorage} from 'react-native';
import { LineChart, Grid } from 'react-native-svg-charts';
import { Container, Header, Content, List, ListItem, Text, Left, Right, Body , Button, Title} from 'native-base';

const data = [1,2,3,4,5,6,7];

export default class SomeDetails extends Component {

  constructor(props)
  {
    super(props);
    this.state = { 'user': '',
                    'email': '',
                    'privLevel': '',
                    'phNum': '',
                    UserApiUrl: '<SOMEAPI>',
                    sData: [],
                    someData: ''
     }
  }

  componentDidMount() {
    this._loadInitialState().done();
  }

  _loadInitialState = async () => {
    var uPhVal = await AsyncStorage.getItem('uPh');
    var uEmailVal = await AsyncStorage.getItem('uEmail');
    var uPrivVal = await AsyncStorage.getItem('uPlevel');
    var uName = await AsyncStorage.getItem('username');

    if(uName !== null)
    {
      this.setState({'user': uName});
      this.setState({'phNum': uPhVal});
      this.setState({'email': uEmailVal});
      this.setState({'privLevel':uPrivVal})
    }

    var postString = "SOME STRING FOR MY API"
    console.log(postString);
    response  = await fetch(this.state.UserApiUrl, {
        method: 'POST',
        body: postString
    })
    res = await response.json();
    console.log(res.success);
    if (res.success == "true") {
        this.setState({ someData: res.someLatestVal });
        var dataItems = this.state.someData.split(';');
        for(let j=0;j<dataItems.length; j++)
        {
            var dataI = dataItems[j].split(':');
            this.setState({sData: this.state.sData.concat([dataI[0]]) } );
        }
    }
    else {
        //  console.log("Req: Unable to fetch");
        this.setState({sData: [1,2,3,4,5]});
        this.setState({loading: true});
    }

     console.log(this.state.sData);

  }

  render() {

    const { navigation } = this.props;
    const someName = navigation.getParam('someName', 'no-name');

    return (
      <Container>
        <Content>
          <List>
            <ListItem>
              <Text>Sensorname: { someName } </Text>
            </ListItem>
            <LineChart
                style={{ height: 70, width: 120 }}
                data={ this.state.sData }
                svg={{ stroke: 'rgb(134, 65, 244)' }}
                contentInset={{ top: 20, bottom: 20 }}
                >
            <Grid/>
            </LineChart>

          </List>
        </Content>
      </Container>
    );
  }
}


问:
allow touch control up and down in aframe
touch control in aframe scene works only in the left and right, it does not work up and down using a mobile
however using the desktop it works perfectly
when I added touch control, look control is removed

how to add both of them at the same time

答:
Please specify if you are using an iOS device or an Android. Steps to follow:

On iOS 12.2 it is a known issue as Apple has disabled deviceorientation and device motion in Safari.  Tried to manually enable it but still doesn't work.  Installed Chrome and cardboard-vr files but no fruitful results.

On Android, install google cardboard, if you don't have it.  Update the version of the Aframe, make sure you are on A-Frame 0.9.2.


问:
Ansible - using json imported from Consul
I have a json content on Consul that I import to my playbook. The json contains account names and passwords:

```<code>{
    "account_1": "password_1",
    "account_2": "password_2",
    "account_3": "password_3"
}
</code>```

After registering it to variable I wish to be able to use every user name and password. Since these jsons may contain different numbers of entries, I was hoping I could use with_items for this. Can someone help me out?

Debugging the whole json works with no issues:

```<code>TASK [debug] **************************************************************************
ok: [localhost] => {
    "accountsDataFromConsul.data.Value": {
        "account_1": "password_1",
        "account_2": "password_2",
        "account_3": "password_3"
    }
}
</code>```

I try to get to individual entries (user names and passwords). I tried the below code, but it returned only user names:

```<code>- debug:
    var: item
  with_items: "{{accountsDataFromConsul.data.Value}}"
</code>```

```<code>TASK [debug] ******************************************************************************
ok: [localhost] => (item=account_1) => {
    "item": "account_1"
}
ok: [localhost] => (item=account_2) => {
    "item": "account_2"
}
ok: [localhost] => (item=account_3) => {
    "item": "account_3"
}
</code>```

Body:
I have a json content on Consul that I import to my playbook. The json contains account names and passwords:

{
    "account_1": "password_1",
    "account_2": "password_2",
    "account_3": "password_3"
}

After registering it to variable I wish to be able to use every user name and password. Since these jsons may contain different numbers of entries, I was hoping I could use with_items for this. Can someone help me out?

Debugging the whole json works with no issues:

TASK [debug] **************************************************************************
ok: [localhost] => {
    "accountsDataFromConsul.data.Value": {
        "account_1": "password_1",
        "account_2": "password_2",
        "account_3": "password_3"
    }
}

I try to get to individual entries (user names and passwords). I tried the below code, but it returned only user names:

- debug:
    var: item
  with_items: "{{accountsDataFromConsul.data.Value}}"

TASK [debug] ******************************************************************************
ok: [localhost] => (item=account_1) => {
    "item": "account_1"
}
ok: [localhost] => (item=account_2) => {
    "item": "account_2"
}
ok: [localhost] => (item=account_3) => {
    "item": "account_3"
}

Body:
Map data is not iterable via ansible loops.

Take a look at the dict2items filter.

#!/usr/bin/env ansible-playbook
- name: Lets munge some data
  hosts: localhost
  gather_facts: false
  become: false
  vars:
    my_dict:
      key_one: value_one
      key_two: value_two
    my_json: '{"key_one": "value_one", "key_two": "value_two"}'
  tasks:
  - name: Iterate over a dict
    debug:
      msg: "{{ item.key }} {{ item.value }}"
    loop: "{{ my_dict | dict2items }}"

  - name: Iterate over json
    debug:
      msg: "{{ item.key }} {{ item.value }}"
    loop: "{{ my_json | from_json | dict2items }}"

PLAY [Lets munge some data] *****************************************************************************************************************************************************************************************************

TASK [Iterate over a dict] ******************************************************************************************************************************************************************************************************
ok: [localhost] => (item={'key': 'key_one', 'value': 'value_one'}) => {
    "msg": "key_one value_one"
}
ok: [localhost] => (item={'key': 'key_two', 'value': 'value_two'}) => {
    "msg": "key_two value_two"
}

TASK [Iterate over json] ********************************************************************************************************************************************************************************************************
ok: [localhost] => (item={'key': 'key_one', 'value': 'value_one'}) => {
    "msg": "key_one value_one"
}
ok: [localhost] => (item={'key': 'key_two', 'value': 'value_two'}) => {
    "msg": "key_two value_two"
}

PLAY RECAP **********************************************************************************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


问:
Coding a subtraction loop that takes in a list
I am making a calculator and need a subtraction loop for the code to work. Right now it is scanning the list but only doing the first and last numbers not the entire list.

```<code>if(a.equals("Subtract")) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        System.out.println("Enter integers one at a time in order");
        System.out.println("When completed type done");
        while (scan.hasNextInt()) {
            list.add(scan.nextInt());
        }
        Integer[] nums = list.toArray(new Integer[0]);
        for (int i = 0; i < nums.length-1; i++) {
            sum = nums[0];
            sum = sum - nums[i+1];
        }
        System.out.println("Your total is " + sum);
        System.out.println("-----------------------------");
        main(args);
        }
</code>```

Only subtracts the first and last numbers of loop not entire loop in order

答:
I suspect Java 8 streams is not what OP is after but for completeness here is a way to make use of the List instead of a for loop using streams

```<code>if (!list.isEmpty) {
    sum = list.get(0) - list.subList(1, list.size()).stream().reduce(0,Integer::sum);
}
</code>```

If a loop is prefered then at least use the list already created

```<code>sum = list.get(0);
for (int i = 1; i < list.size(); i++) {
    sum -= list.get(i);
}
</code>```

Body:
I am making a calculator and need a subtraction loop for the code to work. Right now it is scanning the list but only doing the first and last numbers not the entire list.

if(a.equals("Subtract")) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        System.out.println("Enter integers one at a time in order");
        System.out.println("When completed type done");
        while (scan.hasNextInt()) {
            list.add(scan.nextInt());
        }
        Integer[] nums = list.toArray(new Integer[0]);
        for (int i = 0; i < nums.length-1; i++) {
            sum = nums[0];
            sum = sum - nums[i+1];
        }
        System.out.println("Your total is " + sum);
        System.out.println("-----------------------------");
        main(args);
        }

Only subtracts the first and last numbers of loop not entire loop in order

Body:
I suspect Java 8 streams is not what OP is after but for completeness here is a way to make use of the List instead of a for loop using streams

if (!list.isEmpty) {
    sum = list.get(0) - list.subList(1, list.size()).stream().reduce(0,Integer::sum);
}

If a loop is prefered then at least use the list already created

sum = list.get(0);
for (int i = 1; i < list.size(); i++) {
    sum -= list.get(i);
}


问:
Transaction not inserting data into database, keeps rolling back but I can't see the issue
The sql commands work in phpmyadmin but won't work in the code. I get no error messages and it appears to be successful but nothing goes inot the database. I have tried various methods but just cannot locate the problem. Really at a loss. Maybe a transaction is not the best way of inserting data into multiple tables? </p>

```<code>$db->beginTransaction(); // ***********************
$stmt = $db->prepare('INSERT INTO guests
VALUES (null, :sFirstName, :sLastName, :sEmail, :sPhone, :sAddressLine1, :sCity, :sCountry);
SELECT * FROM guests
INNER JOIN countries ON guests.country_fk = countries.country_id;');

$stmt->bindValue(':sFirstName', $sFirstName);
$stmt->bindValue(':sLastName', $sLastName);
$stmt->bindValue(':sEmail', $sEmail);
$stmt->bindValue(':sPhone', $sPhone);
$stmt->bindValue(':sAddressLine1', $sAddressLine1);
$stmt->bindValue(':sCity', $sCity);
$stmt->bindValue(':sCountry', $sCountry);
if(  !$stmt->execute() ){
  echo 'Cannot update the user '.__LINE__;
  $db->rollBack();
  exit;
}

 $stmt = $db->prepare('INSERT INTO reservations VALUES(null, :sRoomId, :sCheckInDate,
 :sCheckOutDate, :nightsRequested, :iNumberOfGuests);
 SELECT *
 FROM reservations
 INNER JOIN rooms ON reservations.room_fk = rooms.room_id;');
 $stmt->bindValue(':sRoomId', $sRoomId);
$stmt->bindValue(':sCheckInDate', $sCheckInDate);
$stmt->bindValue(':sCheckOutDate', $sCheckOutDate);
$stmt->bindValue(':nightsRequested', $nightsRequested);
$stmt->bindValue(':iNumberOfGuests', $sNumberOfGuests);
if(  !$stmt->execute() ){
  echo 'Cannot insert a user '.__LINE__;
  $db->rollBack();
  exit;
}

// SUCCESS
echo 'DONE';
$db->commit(); // ***********************
</code>```

答: One statement at a time.  Your two statements happen to be an INSERT and a SELECT, but any combination of statements will cause trouble.

Body:
The sql commands work in phpmyadmin but won't work in the code. I get no error messages and it appears to be successful but nothing goes inot the database. I have tried various methods but just cannot locate the problem. Really at a loss. Maybe a transaction is not the best way of inserting data into multiple tables?

$db->beginTransaction(); // ***********************
$stmt = $db->prepare('INSERT INTO guests
VALUES (null, :sFirstName, :sLastName, :sEmail, :sPhone, :sAddressLine1, :sCity, :sCountry);
SELECT * FROM guests
INNER JOIN countries ON guests.country_fk = countries.country_id;');

$stmt->bindValue(':sFirstName', $sFirstName);
$stmt->bindValue(':sLastName', $sLastName);
$stmt->bindValue(':sEmail', $sEmail);
$stmt->bindValue(':sPhone', $sPhone);
$stmt->bindValue(':sAddressLine1', $sAddressLine1);
$stmt->bindValue(':sCity', $sCity);
$stmt->bindValue(':sCountry', $sCountry);
if(  !$stmt->execute() ){
  echo 'Cannot update the user '.__LINE__;
  $db->rollBack();
  exit;
}

 $stmt = $db->prepare('INSERT INTO reservations VALUES(null, :sRoomId, :sCheckInDate,
 :sCheckOutDate, :nightsRequested, :iNumberOfGuests);
 SELECT *
 FROM reservations
 INNER JOIN rooms ON reservations.room_fk = rooms.room_id;');
 $stmt->bindValue(':sRoomId', $sRoomId);
$stmt->bindValue(':sCheckInDate', $sCheckInDate);
$stmt->bindValue(':sCheckOutDate', $sCheckOutDate);
$stmt->bindValue(':nightsRequested', $nightsRequested);
$stmt->bindValue(':iNumberOfGuests', $sNumberOfGuests);
if(  !$stmt->execute() ){
  echo 'Cannot insert a user '.__LINE__;
  $db->rollBack();
  exit;
}

// SUCCESS
echo 'DONE';
$db->commit(); // ***********************


问:
Observable from more than one BehaviorRelay RxSwift
I am trying to achieve a subscription of 3 different BehaviorRelay using RxSwift. The idea is following:

```<code>let disposeBag = DisposeBag()

class ClassA{

    var br1 = BehaviorRelay(value: "BR1_1")
    var br2 = BehaviorRelay(value: "BR2_1")
    var br3 = BehaviorRelay(value: "BR3_1")

    /* Some other variables */

}
let classA = ClassA()

class ClassB:CustomStringConvertible{
    let classA:ClassA

    var description: String{
        return "\(br1.value), \(br2.value), \(br3.value)"
    }

    var br1:BehaviorRelay<String>{
        return classA.br1
    }
    var br2:BehaviorRelay<String>{
        return classA.br2
    }
    var br3:BehaviorRelay<String>{
        return classA.br3
    }

    init(classA:ClassA) {
        self.classA = classA
    }

}
let classB = ClassB(classA: classA)

classB.br1.asObservable().subscribe { (value) in
    print(value)
}

classA.br1.accept("BR1_2")
</code>```

It prints:

```<code>next(BR1_1)
next(BR1_2)
</code>```

By doing that I am "populating" my ClassB with objects from ClassA and by setting a subscription to the objects in ClassB i can react to the next events.

However, I would like to create a function such as:

```<code>func reactingFunction(br1:BehaviorRelay<String>, br2:BehaviorRelay<String>, br3:BehaviorRelay<String>){
    /**/
}
</code>```

to be called every time any of the br produces onNext event. Can I create a mix subscription for all of them?

Thank you

答:
I have found out a solution by implementing CombineLast:

```<code>Observable.combineLatest(classB.br1, classB.br2, classB.br3).subscribe(onNext: { (br1, br2, br3) in
    reactingFunction(br1: br1, br2: br2, br3: br3)
}).disposed(by: disposeBag)
</code>```

Then I have changed the reactingFunction to accept only the values:

```<code>func reactingFunction(br1:String, br2:String, br3:String){
    print("Reacting Function -> \(br1) & \(br2) \(br3)")
}
</code>```

From the example:

```<code>classA.br1.accept("BR1_2")
classA.br1.accept("BR1_3")
classA.br1.accept("BR1_4")
classA.br1.accept("BR1_5")
classA.br2.accept("BR2_2")
classA.br3.accept("BR3_2")
classA.br2.accept("BR2_3")
</code>```

It prints:

```<code>Reacting Function -> BR1_1 & BR2_1 BR3_1
Reacting Function -> BR1_2 & BR2_1 BR3_1
Reacting Function -> BR1_3 & BR2_1 BR3_1
Reacting Function -> BR1_4 & BR2_1 BR3_1
Reacting Function -> BR1_5 & BR2_1 BR3_1
Reacting Function -> BR1_5 & BR2_2 BR3_1
Reacting Function -> BR1_5 & BR2_2 BR3_2
Reacting Function -> BR1_5 & BR2_3 BR3_2
</code>```

Body:
I am trying to achieve a subscription of 3 different BehaviorRelay using RxSwift. The idea is following:

let disposeBag = DisposeBag()

class ClassA{

    var br1 = BehaviorRelay(value: "BR1_1")
    var br2 = BehaviorRelay(value: "BR2_1")
    var br3 = BehaviorRelay(value: "BR3_1")

    /* Some other variables */

}
let classA = ClassA()

class ClassB:CustomStringConvertible{
    let classA:ClassA

    var description: String{
        return "\(br1.value), \(br2.value), \(br3.value)"
    }

    var br1:BehaviorRelay<String>{
        return classA.br1
    }
    var br2:BehaviorRelay<String>{
        return classA.br2
    }
    var br3:BehaviorRelay<String>{
        return classA.br3
    }

    init(classA:ClassA) {
        self.classA = classA
    }

}
let classB = ClassB(classA: classA)

classB.br1.asObservable().subscribe { (value) in
    print(value)
}

classA.br1.accept("BR1_2")

It prints:

next(BR1_1)
next(BR1_2)

By doing that I am "populating" my ClassB with objects from ClassA and by setting a subscription to the objects in ClassB i can react to the next events.

However, I would like to create a function such as:

func reactingFunction(br1:BehaviorRelay<String>, br2:BehaviorRelay<String>, br3:BehaviorRelay<String>){
    /**/
}

to be called every time any of the br produces onNext event. Can I create a mix subscription for all of them?

Thank you

Body:
I have found out a solution by implementing CombineLast:

Observable.combineLatest(classB.br1, classB.br2, classB.br3).subscribe(onNext: { (br1, br2, br3) in
    reactingFunction(br1: br1, br2: br2, br3: br3)
}).disposed(by: disposeBag)

Then I have changed the reactingFunction to accept only the values:

func reactingFunction(br1:String, br2:String, br3:String){
    print("Reacting Function -> \(br1) & \(br2) \(br3)")
}

From the example:

classA.br1.accept("BR1_2")
classA.br1.accept("BR1_3")
classA.br1.accept("BR1_4")
classA.br1.accept("BR1_5")
classA.br2.accept("BR2_2")
classA.br3.accept("BR3_2")
classA.br2.accept("BR2_3")

It prints:

Reacting Function -> BR1_1 & BR2_1 BR3_1
Reacting Function -> BR1_2 & BR2_1 BR3_1
Reacting Function -> BR1_3 & BR2_1 BR3_1
Reacting Function -> BR1_4 & BR2_1 BR3_1
Reacting Function -> BR1_5 & BR2_1 BR3_1
Reacting Function -> BR1_5 & BR2_2 BR3_1
Reacting Function -> BR1_5 & BR2_2 BR3_2
Reacting Function -> BR1_5 & BR2_3 BR3_2


问:
Where is the screenshot file from Xcode UI Test?
I'm interested how to find the location of a screenshot which is created during UI Tests of my app. I would like to understand how Fastlane Snapshot grabs this screenshot. After couple of hours of research I can't find location of those screenshots.</p>

答:
Xcode screenshot file from UI Test

To make screenshot you can call the next method

```<code>func makeScreenShot() {
    let screenshot = XCUIScreen.main.screenshot()
    let fullScreenshotAttachment = XCTAttachment(screenshot: screenshot)
    fullScreenshotAttachment.lifetime = .keepAlways

    add(fullScreenshotAttachment)
}
</code>```

You can find screenshots in Xcode -> Report navigator -> select your test

Or go to

```<code>DerivedData -> ProjectName... -> Logs -> Test -> find .xcresult -> Show Package Contents -> Attachments
</code>```
```<code>#For example
/Users/<mac_name>/Library/Developer/Xcode/DerivedData/<project_name>-<...>/Logs/Test/Test-<target_name>-<...>.xcresult
</code>```

[Xcode run tests]

Body:
Xcode screenshot file from UI Test

To make screenshot you can call the next method

func makeScreenShot() {
    let screenshot = XCUIScreen.main.screenshot()
    let fullScreenshotAttachment = XCTAttachment(screenshot: screenshot)
    fullScreenshotAttachment.lifetime = .keepAlways

    add(fullScreenshotAttachment)
}

You can find screenshots in Xcode -> Report navigator -> select your test

Or go to

DerivedData -> ProjectName... -> Logs -> Test -> find .xcresult -> Show Package Contents -> Attachments

#For example
/Users/<mac_name>/Library/Developer/Xcode/DerivedData/<project_name>-<...>/Logs/Test/Test-<target_name>-<...>.xcresult

[Xcode run tests]


问:
Prevent trailing zero with pandas "to_csv"
I'm trying to export a CSV string to a D3 web application, but the command to_csv insists on adding a trailing 0 to the data, which prevents a proper use by D3.

Here's a minimal example to illustrate the problem.

My (simplified) dataframe is:

```<code>>>> df = pd.DataFrame([['Alex',20.0000, 50.650]],columns=['Name','Age', 'Weight'])
   Name   Age  Weight
0  Alex  20.0   50.65
</code>```

df['Age'] contains a float, as indicated by:

```<code>>>> df['Age']
0    20.0
Name: Age, dtype: float64
</code>```

Then based on this answer I run .astype(object) to get the format I would like:

```<code>>>> df=df.astype(object)
   Name Age Weight
0  Alex  20  50.65
</code>```

Now, df['Age'] contains an object, with no trailing zero:

```<code>>>> df['Age']
0    20
Name: Age, dtype: object
</code>```

That's what I would like to export with to_csv, but this command reappends a trailing 0 to the number, which I want to avoid:

```<code>>>> df_csv = df.to_csv(sep=',', index = False)
>>> df_csv
'Name,Age,Weight\nAlex,20.0,50.65\n'
</code>```

I tried using df_csv = df.to_csv(sep=',', index = False, float_format='%.0f') based on this answer, but that doesn't work because there are other floats in my dataframe for which I wish to keep non-zero decimals.

How could I prevent this trailing 0 to appear for numbers with no decimals?

答:
Another way using Pandas replace :

df = df.astype(str)
df = df.replace(to_replace = "\.0+$",value = "", regex = True)
```

This way you don't need to import any extra module.

Body:
I'm trying to export a CSV string to a D3 web application, but the command to_csv insists on adding a trailing 0 to the data, which prevents a proper use by D3.

Here's a minimal example to illustrate the problem.

My (simplified) dataframe is:

>>> df = pd.DataFrame([['Alex',20.0000, 50.650]],columns=['Name','Age', 'Weight'])
   Name   Age  Weight
0  Alex  20.0   50.65

df['Age'] contains a float, as indicated by:

>>> df['Age']
0    20.0
Name: Age, dtype: float64

Then based on this answer I run .astype(object) to get the format I would like:

>>> df=df.astype(object)
   Name Age Weight
0  Alex  20  50.65

Now, df['Age'] contains an object, with no trailing zero:

>>> df['Age']
0    20
Name: Age, dtype: object

That's what I would like to export with to_csv, but this command reappends a trailing 0 to the number, which I want to avoid:

>>> df_csv = df.to_csv(sep=',', index = False)
>>> df_csv
'Name,Age,Weight\nAlex,20.0,50.65\n'

I tried using df_csv = df.to_csv(sep=',', index = False, float_format='%.0f') based on this answer, but that doesn't work because there are other floats in my dataframe for which I wish to keep non-zero decimals.

How could I prevent this trailing 0 to appear for numbers with no decimals?

Body:
Another way using Pandas replace :

df = df.astype(str)
df = df.replace(to_replace = "\.0+$",value = "", regex = True)

This way you don't need to import any extra module.


问:
How can i create a button with boolean and a specific id?
I am currently coding a component to display documentation, like qt doc (https://doc.qt.io/qt-5/qstring.html) and I am using CodeMirror to display a code example.

I am using Angular 2:

          {{ method?.name }}

        <button class="button" *ngIf="!showCode" (click)="showCloseExample()">Show example</button>
        <button class="button" *ngIf="showCode" (click)="showCloseExample()">Close example</button>

          <app-code-mirror [data]="method.documentation"></app-code-mirror>

```

I created a button to show or hide a div with a CodeMirror component inside but when I click this button, it opens every examples.
I think it's because it's on an ngFor.
When I click this button, I want to open only one div and not all.

答:
The problem with your code is that you are changing one variable showCode. You are also watching that showCode variable, and opening/closing each of your snippets whenever it changes.

There are many solutions for this problem, one of them being as follows:

Add a new boolean in each object of your methods array. Lets call it showCode, as  you did. Now each method has a showCode flag. Instead of ngIf="showCode", you will have ngIf="method.showCode".

Now, instead of (click)="showCloseExample()", you can do something like (click)="method.showCode = !method.showCode". (I believe this is the right syntax in Angular, if not, bind it to a function and pass the index of the method, and then update methods showCode flag)

Body:
I am currently coding a component to display documentation, like qt doc (https://doc.qt.io/qt-5/qstring.html) and I am using CodeMirror to display a code example.

I am using Angular 2:

          {{ method?.name }}

        <button class="button" *ngIf="!showCode" (click)="showCloseExample()">Show example</button>
        <button class="button" *ngIf="showCode" (click)="showCloseExample()">Close example</button>

          <app-code-mirror [data]="method.documentation"></app-code-mirror>

I created a button to show or hide a div with a CodeMirror component inside but when I click this button, it opens every examples.
I think it's because it's on an ngFor.
When I click this button, I want to open only one div and not all.


问:
How to prevent 'click' event to fire before 'dblclick' event
I have to handle two events which are 'click' and 'dblclick' but the click event always fires before dblclick event and don't let dblclick event to execute. How can I make the event to execute correctly 'click' and 'dblclick'</p>

```<code>google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng)
 });

 google.maps.event.addListener(map, 'click', function(event) {
   click_events(map, event.latLng)
 });
</code>```

答:
from https://api.jquery.com/dblclick/

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

how about handling it yourself, here an example for a multi-click detection:

let timeout, n = 0, delay = 250;

document.querySelector(".clicker").addEventListener("click", function(event) {
  ++n;
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    clickHandler.call(this, n, event);
    n = 0;
  }, delay);

  // a visual aid for how many times you've already clicked in this sequence
  event.target.textContent = n;
});

// just something visual
const cssNamedColors = ["Maroon","Red","Orange","Yellow","Olive","Green","Purple","Fuchsia","Lime","Teal","Aqua","Blue","Navy","Black","Gray","Silver","White"];

// decide what to do for *n* clicks:
function clickHandler(n, event) {
  event.target.style.background = cssNamedColors[n-1];
  event.target.textContent = n + " - " + cssNamedColors[n-1];
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.clicker {
  display: block;
  background: #888;
  padding: 100px 0;
  text-align: center;
  font-size: 36px;
  color: white;
  cursor: pointer;
  text-shadow: -1px -1px 3px #000, 1px -1px 3px #000, -1px 1px 3px #000, 1px 1px 3px #000;
}</code>```

(Multi-)Click me
```

Body:
I have to handle two events which are 'click' and 'dblclick' but the click event always fires before dblclick event and don't let dblclick event to execute. How can I make the event to execute correctly 'click' and 'dblclick'

google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng)
 });

 google.maps.event.addListener(map, 'click', function(event) {
   click_events(map, event.latLng)
 });

Body:
from https://api.jquery.com/dblclick/

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

how about handling it yourself, here an example for a multi-click detection:

let timeout, n = 0, delay = 250;

document.querySelector(".clicker").addEventListener("click", function(event) {
  ++n;
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    clickHandler.call(this, n, event);
    n = 0;
  }, delay);

  // a visual aid for how many times you've already clicked in this sequence
  event.target.textContent = n;
});

// just something visual
const cssNamedColors = ["Maroon","Red","Orange","Yellow","Olive","Green","Purple","Fuchsia","Lime","Teal","Aqua","Blue","Navy","Black","Gray","Silver","White"];

// decide what to do for *n* clicks:
function clickHandler(n, event) {
  event.target.style.background = cssNamedColors[n-1];
  event.target.textContent = n + " - " + cssNamedColors[n-1];
}

.clicker {
  display: block;
  background: #888;
  padding: 100px 0;
  text-align: center;
  font-size: 36px;
  color: white;
  cursor: pointer;
  text-shadow: -1px -1px 3px #000, 1px -1px 3px #000, -1px 1px 3px #000, 1px 1px 3px #000;
}

<div class="clicker">(Multi-)Click me</div>


问:
How to repeat a trigger keydown event?
I'm setting a little help system (step-by-step) with html and jquery. When you complete one step, if you click in the "Next" button, you can see the next step. I would like to allow user to press also the right arrow key to move forward whit the guide.
I setting the trigger to simulate the click but it works only once time.

```<code>
$(".next").click(function(){
    //function
});

$("body").keydown(function(e) {
  if(e.keyCode == 39) { // right
    $(".next").trigger('click'); // simulate the click on .next
  }
}); // keydown
</code>```

Here a demo:
http://jsfiddle.net/mlarsen1982/sqrx9gz7/5

答:
You're body element is probably getting blown away. Try adding the keydown event handler to the document instead of the body. </p>

```<code>$(".next").click(function(){
    //function
});

$(document).keydown(function(e) {
  if(e.keyCode == 39) { // right
    $(".next").trigger('click'); // simulate the click on .next
  }
}); // keydown
</code>```

Title: How to repeat a trigger keydown event?

Body:
I'm setting a little help system (step-by-step) with html and jquery. When you complete one step, if you click in the "Next" button, you can see the next step. I would like to allow user to press also the right arrow key to move forward whit the guide.
I setting the trigger to simulate the click but it works only once time.

$(".next").click(function(){
    //function
});

$("body").keydown(function(e) {
  if(e.keyCode == 39) { // right
    $(".next").trigger('click'); // simulate the click on .next
  }
}); // keydown

Here a demo:
http://jsfiddle.net/mlarsen1982/sqrx9gz7/5

Body:
You're body element is probably getting blown away. Try adding the keydown event handler to the document instead of the body.

$(".next").click(function(){
    //function
});

$(document).keydown(function(e) {
  if(e.keyCode == 39) { // right
    $(".next").trigger('click'); // simulate the click on .next
  }
}); // keydown