问:
Multilevel $group using mongodb
I am trying to get the count of all the different value of a key in my MongoDB. I am getting the count as well but i am getting it with 2 different objects.

```<code>{ "_id" : ObjectId("596f6e95b6a1aa8d363befeb"), produce:"potato","variety" : "abc", "state" : 'PA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befec"), produce:"potato", "variety" : "abc", "state" : 'PA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befed"), produce:"potato", "variety" : "def", "state" : 'IA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befee"), produce:"potato", "variety" : "def", "state" : 'IA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befef"), produce:"potato", "variety" : "abc", "state" : 'DA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befeg"), produce:"potato", "variety" : "abc", "state" : 'DA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befeh"), produce:"potato", "variety" : "def", "state" : 'DA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befei"), produce:"potato", "variety" : "abc", "state" : 'IA' }

db.aggregate([

    {
       $match:{produce: "potato"}
    },
    {
       "$group":{
          "_id":{"variety":"$variety","state":"$state"},
          "count":{"$sum":1}
        }
    },
    {
       "$group":{
           "_id":null,
                "counts":{
                    "$push": {"filterkey":"$_id.variety","state":"$_id.state","count":"$count"}
                }
         }
     },
])
</code>```

Actual Result : -
counts

```<code>[

    { filterkey: 'abc', state: 'PA', count: 2},
    { filterkey: 'abc', state: 'IA', count: 1},
    { filterkey: 'abc', state: 'DA', count: 2},
    { filterkey: 'def', state: 'IA', count: 2},
    { filterkey: 'def', state: 'DA', count: 1}
]
</code>```

Expected Result : -
counts

```<code>[

    { filterkey: 'abc', states:{'PA':2,'IA':1,'DA':2},
    { filterkey: 'def', states:{'IA':2,'DA':1}
]
</code>```

Is there is some way to get the data like this?

答:
You need to use multilevel $group ing here. First you need to use $group with the variety and state fields and need to $sum to get total number of unique document per variety and state.

Then second you need to use $group with the  variety to get the number of unique documents per variety.

And Finally $arrayToObject to flatten the states array.

```<code>db.collection.aggregate([
  { "$match": { "produce": "potato" }},
  { "$group": {
    "_id": { "variety": "$variety", "state": "$state" },
    "count": { "$sum": 1 }
  }},
  { "$group": {
    "_id": "$_id.variety",
    "states": {
      "$push": {
        "k": "$_id.state",
        "v": "$count"
      }
    }
  }},
  { "$addFields": {
    "states": {
      "$arrayToObject": "$states"
    }
  }}
])
</code>```

You can remove stages one by one here and can see what actually happens.

Output

```<code>[
  {
    "_id": "def",
    "states": {
      "DA": 1,
      "IA": 2
    }
  },
  {
    "_id": "abc",
    "states": {
      "DA": 2,
      "IA": 1,
      "PA": 2
    }
  }
]
</code>```

Title: Multilevel $group using mongodb

Body:
I am trying to get the count of all the different value of a key in my MongoDB. I am getting the count as well but i am getting it with 2 different objects.

{ "_id" : ObjectId("596f6e95b6a1aa8d363befeb"), produce:"potato","variety" : "abc", "state" : 'PA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befec"), produce:"potato", "variety" : "abc", "state" : 'PA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befed"), produce:"potato", "variety" : "def", "state" : 'IA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befee"), produce:"potato", "variety" : "def", "state" : 'IA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befef"), produce:"potato", "variety" : "abc", "state" : 'DA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befeg"), produce:"potato", "variety" : "abc", "state" : 'DA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befeh"), produce:"potato", "variety" : "def", "state" : 'DA' }

{ "_id" : ObjectId("596f6e95b6a1aa8d363befei"), produce:"potato", "variety" : "abc", "state" : 'IA' }

db.aggregate([

    {
       $match:{produce: "potato"}
    },
    {
       "$group":{
          "_id":{"variety":"$variety","state":"$state"},
          "count":{"$sum":1}
        }
    },
    {
       "$group":{
           "_id":null,
                "counts":{
                    "$push": {"filterkey":"$_id.variety","state":"$_id.state","count":"$count"}
                }
         }
     },
])

Actual Result : -
counts

[

    { filterkey: 'abc', state: 'PA', count: 2},
    { filterkey: 'abc', state: 'IA', count: 1},
    { filterkey: 'abc', state: 'DA', count: 2},
    { filterkey: 'def', state: 'IA', count: 2},
    { filterkey: 'def', state: 'DA', count: 1}
]

Expected Result : -
counts

[

    { filterkey: 'abc', states:{'PA':2,'IA':1,'DA':2},
    { filterkey: 'def', states:{'IA':2,'DA':1}
]

Is there is some way to get the data like this?

Body:
You need to use multilevel $group ing here. First you need to use $group with the variety and state fields and need to $sum to get total number of unique document per variety and state.

Then second you need to use $group with the  variety to get the number of unique documents per variety.

And Finally $arrayToObject to flatten the states array.

db.collection.aggregate([
  { "$match": { "produce": "potato" }},
  { "$group": {
    "_id": { "variety": "$variety", "state": "$state" },
    "count": { "$sum": 1 }
  }},
  { "$group": {
    "_id": "$_id.variety",
    "states": {
      "$push": {
        "k": "$_id.state",
        "v": "$count"
      }
    }
  }},
  { "$addFields": {
    "states": {
      "$arrayToObject": "$states"
    }
  }}
])

You can remove stages one by one here and can see what actually happens.

Output

[
  {
    "_id": "def",
    "states": {
      "DA": 1,
      "IA": 2
    }
  },
  {
    "_id": "abc",
    "states": {
      "DA": 2,
      "IA": 1,
      "PA": 2
    }
  }
]


来源: stackexchange

问:
MailChimp resubscribe a deleted member causes the API to return a 400 bad request
I've encountered a problem on MailChimp v3 API where it responds with a status 400 when I try to resubcribe a member. Here's the steps to reproduce the problem:

Subscribe a member to a list then delete that member.

Resubscribe using the API through endpoint PUT /lists/{list_id}/members/{subscriber_hash} returns a status 400

{
  'type': 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
  'title': 'Forgotten Email Not Subscribed',
  'status': 400,
  'detail': 'some@email.com was permanently deleted and cannot be re-imported. The contact must re-subscribe to get back on the list.'
}

and the request is:

```<code>{
  email_address: 'some@email.com',
  status_if_new: 'subscribed'
}
</code>```

Based on the response the solution is the member must be resubscribed which I'm actually trying to do. Anyone encountered this problem?

答:
It's not impossible to re-import the list member... just go into your MailChimp contacts and add the member that way.  Granted, you won't be able to use the API/form on your Web site, but if that e-mail needs to be in the system, this is the only way I found.

You can also take an existing contact and change his/her e-mail to the one that's been permanently deleted.  This is actually how I was able to re-import a perm deleted e-mail, as I haven't tried adding a new one, but I'm guessing it might work the same.

ContentLicense: CC BY-SA 4.0

Body:
I've encountered a problem on MailChimp v3 API where it responds with a status 400 when I try to resubcribe a member. Here's the steps to reproduce the problem:

Subscribe a member to a list then delete that member.

Resubscribe using the API through endpoint PUT /lists/{list_id}/members/{subscriber_hash} returns a status 400

{
  'type': 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
  'title': 'Forgotten Email Not Subscribed',
  'status': 400,
  'detail': 'some@email.com was permanently deleted and cannot be re-imported. The contact must re-subscribe to get back on the list.'
}

and the request is:

{
  email_address: 'some@email.com',
  status_if_new: 'subscribed'
}

Based on the response the solution is the member must be resubscribed which I'm actually trying to do. Anyone encountered this problem?


问:
ISQL 7.3 (SuSE): Ace report output to more than one file or stdout
Does anyone know how I could trick Ace into outputing to more than one file or to a file and display simultaneously without having to write an external script?.. i.e. in the Ace spec OUTPUT REPORT TO PIPE or OUTPUT REPORT TO "filename.out" > /dev/tty01a</p>

答:
For piping to multiple files, you can use:

```<code>OUTPUT
    REPORT TO PIPE "tee file2 >file1"
</code>```

You can do more than two files if you want to, courtesy of the abilities of the tee program.  Clearly, if you want the output to go to standard output as well as to a file, you pipe it to tee without the '>' redirection.

You can get the output to a pager if you use:

```<code>OUTPUT
    REPORT TO PIPE "tee file1 file2 | less"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For piping to multiple files, you can use:

OUTPUT
    REPORT TO PIPE "tee file2 >file1"

You can do more than two files if you want to, courtesy of the abilities of the tee program.  Clearly, if you want the output to go to standard output as well as to a file, you pipe it to tee without the '>' redirection.

You can get the output to a pager if you use:

OUTPUT
    REPORT TO PIPE "tee file1 file2 | less"


问:
ReactJS download file from Express Server
I'm trying to make my user able to download a file from our backend server. I've tried the solution from this question as well as the backend from this.

Sadly none of them worked. The download itself works through postman, but not in react.

Additional info: The Backend is running on the same machine but on port 3001 while the frontend is running on port 3000
I'm not sure if that helps, but the react frontend is connected to the backend via proxy in the package.json

```<code>"proxy": "http://localhost:3001",
</code>```

The client side currently looks like this:

```<code>    const download = require("downloadjs");

    const handleDownload = async () => {
      const res = await fetch("http://localhost:3001/download");
      const blob = await res.blob();
      download(blob, "test.pdf");
    }

    function App() {
      return (
        <div className="App">
          <header className="App-header">
            <button onClick={() => handleDownload().finally(() =>                 console.log("Passed through the whole handleDownload Request"))}>                </button>
          </header>
        </div>
      );
    }
</code>```

while on the backend side I'm using this code as from the previous questions asked here on stackoverflow.

```<code>    app.get('/getdoc', function (req, res) {
        res.download(path.join(__dirname, 'files/test.pdf'), function (err) {
            console.log(err);
        });
    });
</code>```

This is the Code working through Postman, but it won't trigger a download in React.

The Error occurring in react looks like this:

```<code>    App.js:8 GET http://localhost:3001/download/test.pdf    net::ERR_CONNECTION_REFUSED

    Uncaught (in promise) TypeError: Failed to fetch
</code>```

So it seems the handling on frontend seems to be the problem, as it is not triggering the Save Dialog from the browser (Chrome).

答:
Try this:

```<code>const handleDownload = () => {
var reqObj = new XMLHttpRequest();
reqObj.open('GET','http://localhost:3001/download',true);     // 'getpdf' is the URI to recongize your request at the server
reqObj.send();

reqObj.onreadystatechange = function() {
    var resObj = this;
    if(resObj.readyState == resObj.DONE) {
        if (resObj.status != 200) {
            console.log(200);
        } else if (resObj.status == 200){
            var resTxt = reqObj.responseText;
            window.location.assign(resTxt);    // Opens the pdf download prompt
        }
    }
}
</code>```

Body:
I'm trying to make my user able to download a file from our backend server. I've tried the solution from this question as well as the backend from this.

Sadly none of them worked. The download itself works through postman, but not in react.

Additional info: The Backend is running on the same machine but on port 3001 while the frontend is running on port 3000
I'm not sure if that helps, but the react frontend is connected to the backend via proxy in the package.json

"proxy": "http://localhost:3001",

The client side currently looks like this:

    const download = require("downloadjs");

    const handleDownload = async () => {
      const res = await fetch("http://localhost:3001/download");
      const blob = await res.blob();
      download(blob, "test.pdf");
    }

    function App() {
      return (

            <button onClick={() => handleDownload().finally(() =>                 console.log("Passed through the whole handleDownload Request"))}>                </button>

      );
    }

while on the backend side I'm using this code as from the previous questions asked here on stackoverflow.

    app.get('/getdoc', function (req, res) {
        res.download(path.join(__dirname, 'files/test.pdf'), function (err) {
            console.log(err);
        });
    });

This is the Code working through Postman, but it won't trigger a download in React.

The Error occurring in react looks like this:

    App.js:8 GET http://localhost:3001/download/test.pdf    net::ERR_CONNECTION_REFUSED

    Uncaught (in promise) TypeError: Failed to fetch

So it seems the handling on frontend seems to be the problem, as it is not triggering the Save Dialog from the browser (Chrome).

Body:
Try this:

const handleDownload = () => {
var reqObj = new XMLHttpRequest();
reqObj.open('GET','http://localhost:3001/download',true);     // 'getpdf' is the URI to recongize your request at the server
reqObj.send();

reqObj.onreadystatechange = function() {
    var resObj = this;
    if(resObj.readyState == resObj.DONE) {
        if (resObj.status != 200) {
            console.log(200);
        } else if (resObj.status == 200){
            var resTxt = reqObj.responseText;
            window.location.assign(resTxt);    // Opens the pdf download prompt
        }
    }
}


问:
How to define robots.txt for anguluarjs application
I want defined robots.txt as you can see below to block robots from login url:

```<code>user-agent: *
disallow: /#!/login

Sitemap: http://mysite.ir/sitemap.xml
</code>```

but google does not recognize # sign and ignore whole the site. how can i fix that problem.

答:
As per i know angularJS is not good for SEO but yet you can do some basic SEO.

Anyway, this post may help you to create robots.txt Robot.txt in angularJS

Body:
I want defined robots.txt as you can see below to block robots from login url:

user-agent: *
disallow: /#!/login

Sitemap: http://mysite.ir/sitemap.xml

but google does not recognize # sign and ignore whole the site. how can i fix that problem.


问:
I want to upload two files using two file input in the same form in laravel
I want to create a simple completion entry form. The entries are supposed to have fields for users profile picture and the documents itself. I dont want to put it in an array [] I just want to upload the picture and document separately. How do I process this in laravel?</p>

答:
Change your code in controller:

Here I use public/images directory for image upload and
public/documents directory for documents upload you can replace with your folder path

```<code>public function upload(Request $request) {
    if($request->image != ''){
        $path = 'images/';
        $file = $request->image;
        $filename = $file->getClientOriginalName();
        $file->move($path, $filename);
    }
    if($request->document != ''){
        $path = 'documents/';
        $file = $request->documents;
        $filename = $file->getClientOriginalName();
        $file->move($path, $filename);
    }
}
</code>```

Body:
Change your code in controller:

Here I use public/images directory for image upload and
public/documents directory for documents upload you can replace with your folder path

public function upload(Request $request) {
    if($request->image != ''){
        $path = 'images/';
        $file = $request->image;
        $filename = $file->getClientOriginalName();
        $file->move($path, $filename);
    }
    if($request->document != ''){
        $path = 'documents/';
        $file = $request->documents;
        $filename = $file->getClientOriginalName();
        $file->move($path, $filename);
    }
}


问:
Lambda loses captured value
I cannot understand why the captured value is lost. I understand that it is connected with an out of scope or copying of an object of LambdaWrapper. But what exactly happens? If LambdaWrapper(100) leaves the scope in Add and reference to __value loses, then why there is no same to LambdaWrapper(300).

```<code>#include <iostream>
#include <vector>
#include <functional>
using namespace std;

class LambdaWrapper {
public:
    LambdaWrapper(double new_value): __value (new_value) {
        cout << "constructed with " << __value << endl;
        __func = [this](){ cout << __value << endl;};
    }
    void call() const { __func(); }
private:
    double __value;
    function<void(void)> __func;
};

class LambdaContainer {
public:
    void Add(double value) {
        LambdaWrapper w(value); //out of scope
        parts.push_back(w);
    }

    void Add(LambdaWrapper w) // passed as value
    {
        parts.push_back(w);
    }

    void call() const {
        for (const auto& part : parts)
                part.call();
    }
private:
    vector<LambdaWrapper> parts;
};

int main() {
    LambdaContainer c;
    c.Add(100);

    LambdaWrapper w(200);
    c.Add(w);

    c.Add( LambdaWrapper(300) ); //LambdaWrapper(300) will out of scope too

    cout << "==============" << endl;
    c.call();

    return 0;
}
</code>```

The output:

```<code>constructed with 100
constructed with 200
constructed with 300
==============
6.95168e-308 <<< WHY?
200
300
</code>```

答:
I suppose this question is asking what happens, rather than "Is it ok", so in this case (usually) gdb is your friend, modifying the program to print the address of this during construction, this inside __func and the actual address of the object in the container we see:
(addresses varies, but distances and concepts should remain the same)

```<code># During constructors and captured value:
0x7fffffffda80 <- LambdaWrapper(100)
0x7fffffffdb00 <- LambdaWrapper(200)
0x7fffffffdb60 <- LambdaWrapper(300)
# Actual address of data stored in the container:
0x6170c0 <- LambdaWrapper(100)
0x6170e8 <- LambdaWrapper(200)
0x617110 <- LambdaWrapper(300)
</code>```

There is a huge value difference, this is because the creation happens on the stack, while the vector allocates data with new on the heap.

From gdb calling info proc mappings we obtain the memory addresses list:

```<code>Mapped address spaces:

          Start Addr           End Addr       Size     Offset objfile
            0x400000           0x404000     0x4000        0x0 /[...]/LambdaOutOfScope/a.out
            0x603000           0x604000     0x1000     0x3000 /[...]/LambdaOutOfScope/a.out
            0x604000           0x605000     0x1000     0x4000 /[...]/LambdaOutOfScope/a.out
            0x605000           0x637000    0x32000        0x0 [heap]

[...]

      0x7ffffffde000     0x7ffffffff000    0x21000        0x0 [stack]
  0xffffffffff600000 0xffffffffff601000     0x1000        0x0 [vsyscall]
</code>```

But this does not answer why only the 100 is changed.
The answer to the problem resides in the stack frames:
each function call has a local (usually small) variable space for static variables (those without new for simplicity).

If we check the stack info with info frame we see that:

```<code>(gdb) info frame
Stack level 0, frame at 0x7fffffffdbb0:
 rip = 0x400deb in main (main.cpp:75); saved rip = 0x7ffff7495830
 source language c++.
 Arglist at 0x7fffffffdba0, args:
 Locals at **0x7fffffffdba0**, Previous frame's sp is 0x7fffffffdbb0
 Saved registers:
  rbx at 0x7fffffffdb98, rbp at 0x7fffffffdba0, rip at 0x7fffffffdba8
</code>```

Inside main, so the 100 stays out of this frame, because it is not constructed in main but in Add, to check, when inside Add we get:

```<code>(gdb) info frame 1
Stack frame at 0x1:
 rip = 0x0; saved rip = <not saved>
 Outermost frame: previous frame identical to this frame (corrupt stack?)
 Arglist at 0x7fffffffdac8, args:
 Locals at **0x7fffffffdac8**, Previous frame's sp is 0x7fffffffdad8
 Saved registers:
  rip at 0x7fffffffdad0
</code>```

So the corruption happens when we call another function, but since the elements allocated in main are local they are preserved, if you put a c.Add(400); after the 300 you'll see it corrupted too (even if constructed after).

NOTE: I hope to have covered all, but gdb usage in detail, there are plenty of guides on the internet.

Title: Lambda loses captured value

Body:
I cannot understand why the captured value is lost. I understand that it is connected with an out of scope or copying of an object of LambdaWrapper. But what exactly happens? If LambdaWrapper(100) leaves the scope in Add and reference to __value loses, then why there is no same to LambdaWrapper(300).

#include <iostream>
#include <vector>
#include <functional>
using namespace std;

class LambdaWrapper {
public:
    LambdaWrapper(double new_value): __value (new_value) {
        cout << "constructed with " << __value << endl;
        __func = [this](){ cout << __value << endl;};
    }
    void call() const { __func(); }
private:
    double __value;
    function<void(void)> __func;
};

class LambdaContainer {
public:
    void Add(double value) {
        LambdaWrapper w(value); //out of scope
        parts.push_back(w);
    }

    void Add(LambdaWrapper w) // passed as value
    {
        parts.push_back(w);
    }

    void call() const {
        for (const auto& part : parts)
                part.call();
    }
private:
    vector<LambdaWrapper> parts;
};

int main() {
    LambdaContainer c;
    c.Add(100);

    LambdaWrapper w(200);
    c.Add(w);

    c.Add( LambdaWrapper(300) ); //LambdaWrapper(300) will out of scope too

    cout << "==============" << endl;
    c.call();

    return 0;
}

The output:

constructed with 100
constructed with 200
constructed with 300
==============
6.95168e-308 <<< WHY?
200
300

Body:
I suppose this question is asking what happens, rather than "Is it ok", so in this case (usually) gdb is your friend, modifying the program to print the address of this during construction, this inside __func and the actual address of the object in the container we see:
(addresses varies, but distances and concepts should remain the same)

# During constructors and captured value:
0x7fffffffda80 <- LambdaWrapper(100)
0x7fffffffdb00 <- LambdaWrapper(200)
0x7fffffffdb60 <- LambdaWrapper(300)
# Actual address of data stored in the container:
0x6170c0 <- LambdaWrapper(100)
0x6170e8 <- LambdaWrapper(200)
0x617110 <- LambdaWrapper(300)

There is a huge value difference, this is because the creation happens on the stack, while the vector allocates data with new on the heap.

From gdb calling info proc mappings we obtain the memory addresses list:

Mapped address spaces:

          Start Addr           End Addr       Size     Offset objfile
            0x400000           0x404000     0x4000        0x0 /[...]/LambdaOutOfScope/a.out
            0x603000           0x604000     0x1000     0x3000 /[...]/LambdaOutOfScope/a.out
            0x604000           0x605000     0x1000     0x4000 /[...]/LambdaOutOfScope/a.out
            0x605000           0x637000    0x32000        0x0 [heap]

[...]

      0x7ffffffde000     0x7ffffffff000    0x21000        0x0 [stack]
  0xffffffffff600000 0xffffffffff601000     0x1000        0x0 [vsyscall]

But this does not answer why only the 100 is changed.
The answer to the problem resides in the stack frames:
each function call has a local (usually small) variable space for static variables (those without new for simplicity).

If we check the stack info with info frame we see that:

(gdb) info frame
Stack level 0, frame at 0x7fffffffdbb0:
 rip = 0x400deb in main (main.cpp:75); saved rip = 0x7ffff7495830
 source language c++.
 Arglist at 0x7fffffffdba0, args:
 Locals at **0x7fffffffdba0**, Previous frame's sp is 0x7fffffffdbb0
 Saved registers:
  rbx at 0x7fffffffdb98, rbp at 0x7fffffffdba0, rip at 0x7fffffffdba8

Inside main, so the 100 stays out of this frame, because it is not constructed in main but in Add, to check, when inside Add we get:

(gdb) info frame 1
Stack frame at 0x1:
 rip = 0x0; saved rip = <not saved>
 Outermost frame: previous frame identical to this frame (corrupt stack?)
 Arglist at 0x7fffffffdac8, args:
 Locals at **0x7fffffffdac8**, Previous frame's sp is 0x7fffffffdad8
 Saved registers:
  rip at 0x7fffffffdad0

So the corruption happens when we call another function, but since the elements allocated in main are local they are preserved, if you put a c.Add(400); after the 300 you'll see it corrupted too (even if constructed after).

NOTE: I hope to have covered all, but gdb usage in detail, there are plenty of guides on the internet.


问:
Window.location.replace does not redirect me given url
Instead it redirects me to the url of main.js</p>

```<code>function submitPOST(elementId, api, callback) {

    let input = document.getElementById(elementId).getElementsByTagName("input");

    let body = {};
    for (let i = 0; i < input.length; i++) {
        body[input[i].name] = input[i].value;
    }

    call('POST', api, body, callback);
}

function call(method, api,body, callback) {
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onload = function () {
        if (xmlHttp.status==200){
            callback(xmlHttp.response);
        }else{
            console.log(xmlHttp.response);
        }
    };
    xmlHttp.open(method, domainName+"/api/"+api, true); // true for asynchronous
    xmlHttp.setRequestHeader("Content-Type", "application/json");
    xmlHttp.send(JSON.stringify(body));
}

function login(input){
    var response=JSON.parse(input);
    document.cookie="atoken="+response['data'];
    document.location.replace(domainName);
}
</code>```

答:
When you use empty string in domainName variable then the ajax call will correct but the replace doesn't.
If you call it correctly. For example:

submitPOST(id, api, login)

Try to use console.log (or another debug tool) to show the redirection url to you.

Btw maybe the JSON.parse throw an exception in your case. Put it into a try-catch block

```<code>function login(input){
    try {
        var response=JSON.parse(input);
        document.cookie="atoken="+response['data'];
        console.log('redirect to', domainName);
        document.location.replace(domainName);
    } catch(e) {
        console.error('error in login process',e);
    }
}
</code>```

OwnerDisplayName: Shravan S

Body:
Instead it redirects me to the url of main.js

function submitPOST(elementId, api, callback) {

    let input = document.getElementById(elementId).getElementsByTagName("input");

    let body = {};
    for (let i = 0; i < input.length; i++) {
        body[input[i].name] = input[i].value;
    }

    call('POST', api, body, callback);
}

function call(method, api,body, callback) {
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onload = function () {
        if (xmlHttp.status==200){
            callback(xmlHttp.response);
        }else{
            console.log(xmlHttp.response);
        }
    };
    xmlHttp.open(method, domainName+"/api/"+api, true); // true for asynchronous
    xmlHttp.setRequestHeader("Content-Type", "application/json");
    xmlHttp.send(JSON.stringify(body));
}

function login(input){
    var response=JSON.parse(input);
    document.cookie="atoken="+response['data'];
    document.location.replace(domainName);
}

Body:
When you use empty string in domainName variable then the ajax call will correct but the replace doesn't.
If you call it correctly. For example:

submitPOST(id, api, login)

Try to use console.log (or another debug tool) to show the redirection url to you.

Btw maybe the JSON.parse throw an exception in your case. Put it into a try-catch block

function login(input){
    try {
        var response=JSON.parse(input);
        document.cookie="atoken="+response['data'];
        console.log('redirect to', domainName);
        document.location.replace(domainName);
    } catch(e) {
        console.error('error in login process',e);
    }
}


问:
How do I create a circular (endless) RecyclerView?
I am trying to make my RecyclerView loop back to the start of my list.

I have searched all over the internet and have managed to detect when I have reached the end of my list, however I am unsure where to proceed from here.

This is what I am currently using to detect the end of the list (found here):

```<code> @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

        visibleItemCount = mLayoutManager.getChildCount();
        totalItemCount = mLayoutManager.getItemCount();
        pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

        if (loading) {
            if ( (visibleItemCount+pastVisiblesItems) >= totalItemCount) {
                loading = false;
                Log.v("...", ""+visibleItemCount);
            }
        }
 }
</code>```

When scrolled to the end, I would like to views to be visible while the displaying data from the top of the list or when scrolled to the top of the list I would display data from the bottom of the list.

For example:

View1 View2 View3 View4 View5

View5 View1 View2 View3 View4

答:
Endless recyclerView in both sides

Add onScrollListener at your recyclerview

```<code>recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            int firstItemVisible = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
            if (firstItemVisible != 1 && firstItemVisible % itemList.size() == 1) {
                ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPosition(1);
            }
            int firstCompletelyItemVisible = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
            if (firstCompletelyItemVisible == 0)
            {}

            if (firstItemVisible != RecyclerView.NO_POSITION
                    && firstItemVisible== recyclerView.getAdapter().getItemCount()%itemList.size() - 1)
            {
                ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(itemList.size() + 1, 0);
            }
        }
    });
</code>```

In your adapter override the getItemCount method

```<code>@Override
public int getItemCount()
{
    return itemList == null ? 0 : itemList.size() * 2 + 1;
}
</code>```

Body:
I am trying to make my RecyclerView loop back to the start of my list.

I have searched all over the internet and have managed to detect when I have reached the end of my list, however I am unsure where to proceed from here.

This is what I am currently using to detect the end of the list (found here):

 @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

        visibleItemCount = mLayoutManager.getChildCount();
        totalItemCount = mLayoutManager.getItemCount();
        pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

        if (loading) {
            if ( (visibleItemCount+pastVisiblesItems) >= totalItemCount) {
                loading = false;
                Log.v("...", ""+visibleItemCount);
            }
        }
 }

When scrolled to the end, I would like to views to be visible while the displaying data from the top of the list or when scrolled to the top of the list I would display data from the bottom of the list.

For example:

View1 View2 View3 View4 View5

View5 View1 View2 View3 View4

Body:
Endless recyclerView in both sides

Add onScrollListener at your recyclerview

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            int firstItemVisible = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
            if (firstItemVisible != 1 && firstItemVisible % itemList.size() == 1) {
                ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPosition(1);
            }
            int firstCompletelyItemVisible = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
            if (firstCompletelyItemVisible == 0)
            {}

            if (firstItemVisible != RecyclerView.NO_POSITION
                    && firstItemVisible== recyclerView.getAdapter().getItemCount()%itemList.size() - 1)
            {
                ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(itemList.size() + 1, 0);
            }
        }
    });

In your adapter override the getItemCount method

@Override
public int getItemCount()
{
    return itemList == null ? 0 : itemList.size() * 2 + 1;
}


问:
UnfinishedStubbingException
i am newbie in unit test in android.
my problem is that i have a helper class for get pixel from dp.
this code work good and have a one static method.
when i want write a test for this class, i give this error:

```<code>org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.sooran.emdad.ExampleUnitTest.setup(ExampleUnitTest.java:70)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn'
instruction is completed

at com.sooran.emdad.Util.DpUtil2.toPixels(DpUtil2.java:10)
at com.sooran.emdad.ExampleUnitTest.setup(ExampleUnitTest.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at

sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:44)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:74)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:80)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:53)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

this is my class:

```<code>public class DpUtil2 {

public static int toPixels(int dp, Context context) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    float value=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
    return (int) value;

}
</code>```

and this is my test code:

```<code>@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {

@Mock
Context context;
@Mock
Resources resources;
@Mock
DisplayMetrics displayMetrics=new DisplayMetrics();
@Mock
DpUtil2 dpUtil;

@Test
public void addition_isCorrect() {
    assertEquals(4, 2 + 2);
}

@Test
public void dpTest(){

    assertEquals(dpUtil.toPixels(64,context),168);

}

@Before
public void setup(){

    displayMetrics.setToDefaults();
    displayMetrics.density=2.625f;
    displayMetrics.widthPixels=1080;
    displayMetrics.heightPixels=1794;
    displayMetrics.scaledDensity=2.625f;
    displayMetrics.xdpi=422.03f;
    displayMetrics.ydpi=424.069f;
    displayMetrics.densityDpi=420;

    int x=168;
    doReturn(resources).when(context).getResources();
    doReturn(displayMetrics).when(resources).getDisplayMetrics();

    doReturn(x).when(dpUtil).toPixels(64,context);
    }
</code>```

i can pass test correctly with remove third do return
but why third do return give this error

答:
Well, for testing a static method, you need to use PowerMock, I used your sample and modified.

```<code>   package com.sample.mass;

    import android.content.Context;
    import android.content.res.Resources;
    import android.util.DisplayMetrics;

    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import org.mockito.MockitoAnnotations;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({DpUtil2.class})
public class DpUtil2Test {

    private DpUtil2 mDpUtil2;

    @Mock
    Context mContext;

    @Mock
    Resources mResources;

    @Mock
    DisplayMetrics mDisplayMetrics;

    private int dp = 20;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        Mockito.when(mResources.getDisplayMetrics()).thenReturn(mDisplayMetrics);
        Mockito.when(mContext.getResources()).thenReturn(mResources);

    }

    @Test
    public void testToPixels() throws Exception {
        System.out.println("yes");
        PowerMockito.mockStatic(DpUtil2.class);
        PowerMockito.when(DpUtil2.toPixels(dp, mContext)).thenReturn(dp);

        int actualResult = DpUtil2.toPixels(dp, mContext);
        //expected, actual
        Assert.assertEquals(dp, actualResult);

        PowerMockito.verifyStatic(DpUtil2.class);
        DpUtil2.toPixels(dp, mContext);
        System.out.println("-----------we are done--------------------");
    }
}
</code>```

and use these in gradle,

```<code> testImplementation 'org.mockito:mockito-core:2.2.0'
    testImplementation 'org.powermock:powermock-core:1.7.1'
    testImplementation 'org.powermock:powermock-module-junit4:1.7.1'
    testImplementation 'org.powermock:powermock-api-mockito2:1.7.1'
</code>```

Title: UnfinishedStubbingException

Body:
i am newbie in unit test in android.
my problem is that i have a helper class for get pixel from dp.
this code work good and have a one static method.
when i want write a test for this class, i give this error:

org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.sooran.emdad.ExampleUnitTest.setup(ExampleUnitTest.java:70)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn'
instruction is completed

at com.sooran.emdad.Util.DpUtil2.toPixels(DpUtil2.java:10)
at com.sooran.emdad.ExampleUnitTest.setup(ExampleUnitTest.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at

sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:44)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:74)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:80)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:53)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

this is my class:

public class DpUtil2 {

public static int toPixels(int dp, Context context) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    float value=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
    return (int) value;

}

and this is my test code:

@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {

@Mock
Context context;
@Mock
Resources resources;
@Mock
DisplayMetrics displayMetrics=new DisplayMetrics();
@Mock
DpUtil2 dpUtil;

@Test
public void addition_isCorrect() {
    assertEquals(4, 2 + 2);
}

@Test
public void dpTest(){

    assertEquals(dpUtil.toPixels(64,context),168);

}

@Before
public void setup(){

    displayMetrics.setToDefaults();
    displayMetrics.density=2.625f;
    displayMetrics.widthPixels=1080;
    displayMetrics.heightPixels=1794;
    displayMetrics.scaledDensity=2.625f;
    displayMetrics.xdpi=422.03f;
    displayMetrics.ydpi=424.069f;
    displayMetrics.densityDpi=420;

    int x=168;
    doReturn(resources).when(context).getResources();
    doReturn(displayMetrics).when(resources).getDisplayMetrics();

    doReturn(x).when(dpUtil).toPixels(64,context);
    }

i can pass test correctly with remove third do return
but why third do return give this error

Body:
Well, for testing a static method, you need to use PowerMock, I used your sample and modified.

   package com.sample.mass;

    import android.content.Context;
    import android.content.res.Resources;
    import android.util.DisplayMetrics;

    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import org.mockito.MockitoAnnotations;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({DpUtil2.class})
public class DpUtil2Test {

    private DpUtil2 mDpUtil2;

    @Mock
    Context mContext;

    @Mock
    Resources mResources;

    @Mock
    DisplayMetrics mDisplayMetrics;

    private int dp = 20;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        Mockito.when(mResources.getDisplayMetrics()).thenReturn(mDisplayMetrics);
        Mockito.when(mContext.getResources()).thenReturn(mResources);

    }

    @Test
    public void testToPixels() throws Exception {
        System.out.println("yes");
        PowerMockito.mockStatic(DpUtil2.class);
        PowerMockito.when(DpUtil2.toPixels(dp, mContext)).thenReturn(dp);

        int actualResult = DpUtil2.toPixels(dp, mContext);
        //expected, actual
        Assert.assertEquals(dp, actualResult);

        PowerMockito.verifyStatic(DpUtil2.class);
        DpUtil2.toPixels(dp, mContext);
        System.out.println("-----------we are done--------------------");
    }
}

and use these in gradle,

 testImplementation 'org.mockito:mockito-core:2.2.0'
    testImplementation 'org.powermock:powermock-core:1.7.1'
    testImplementation 'org.powermock:powermock-module-junit4:1.7.1'
    testImplementation 'org.powermock:powermock-api-mockito2:1.7.1'


问:
Change the color of a character-pointtype in gnuplot
I am trying to set the color of a character-defined point type in gnuplot. Although I can select the desire color of a system defined point type, I cannot do the same with the character-defined one. Below I present a minimal example.

```<code>set samples 5
set term pdf
set o "mwe.pdf"

p x with points lt rgb "violet" pt "V",\
  x with points lt rgb "violet" pt 2

set o
</code>```

The result looks like this:

I also tried to set the color with the lc variable method and feeding the keyword using with a column ("#005893"), buit it still doesn't change the color.

Question

How can I set the color of the letter to achieve something like this:

答:
the following works for me.

```<code>reset session
set samples 5

plot x with points pt "V" tc rgb "red" font ",20", \
  x with points lt rgb "red" pt 2 ps 3
</code>```

Result:

Body:
I am trying to set the color of a character-defined point type in gnuplot. Although I can select the desire color of a system defined point type, I cannot do the same with the character-defined one. Below I present a minimal example.

set samples 5
set term pdf
set o "mwe.pdf"

p x with points lt rgb "violet" pt "V",\
  x with points lt rgb "violet" pt 2

set o

The result looks like this:

I also tried to set the color with the lc variable method and feeding the keyword using with a column ("#005893"), buit it still doesn't change the color.

Question

How can I set the color of the letter to achieve something like this:

Body:
the following works for me.

reset session
set samples 5

plot x with points pt "V" tc rgb "red" font ",20", \
  x with points lt rgb "red" pt 2 ps 3

Result:


问:
Google Sign In error 12500
I am trying to integrate Google Sign In into my app. I don't have a back-end server, I am just getting the details of the logged on Google Account to my app.

I first tried it by using Google Sign In Example but I got an error (No code changes made except for printing the stacktrace below). I just used the example SignInActivity as I don't have a back-end server.

```<code> Exception com.google.android.gms.common.api.ApiException: 12500:
 at com.google.android.gms.common.internal.zzb.zzz(Unknown Source)
 at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
 at com.ewise.android.api.MainActivity.onActivityResult(SignInActivity.java:89)     at android.app.Activity.dispatchActivityResult(Activity.java:7010)
 at android.app.ActivityThread.deliverResults(ActivityThread.java:4187)
 at android.app.ActivityThread.handleSendResult(ActivityThread.java:4234)
 at android.app.ActivityThread.-wrap20(ActivityThread.java)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1584)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:6316)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
</code>```

Code

```<code> public class SignInActivity extends AppCompatActivity implements
         View.OnClickListener {

     private static final String TAG = "SignInActivity";
     private static final int RC_SIGN_IN = 9001;

     private GoogleSignInClient mGoogleSignInClient;
     private TextView mStatusTextView;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         // Views
         mStatusTextView = findViewById(R.id.status);

         // Button listeners
         findViewById(R.id.sign_in_button).setOnClickListener(this);
         findViewById(R.id.sign_out_button).setOnClickListener(this);
         findViewById(R.id.disconnect_button).setOnClickListener(this);

         // [START configure_signin]
         // Configure sign-in to request the user's ID, email address, and basic
         // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
         GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                 .requestEmail()
                 .build();
         // [END configure_signin]

         // [START build_client]
         // Build a GoogleSignInClient with the options specified by gso.
         mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
         // [END build_client]

         // [START customize_button]
         // Set the dimensions of the sign-in button.
         SignInButton signInButton = findViewById(R.id.sign_in_button);
         signInButton.setSize(SignInButton.SIZE_STANDARD);
         signInButton.setColorScheme(SignInButton.COLOR_LIGHT);
         // [END customize_button]
     }

     @Override
     public void onStart() {
         super.onStart();

         // [START on_start_sign_in]
         // Check for existing Google Sign In account, if the user is already signed in
         // the GoogleSignInAccount will be non-null.
         GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
         updateUI(account);
         // [END on_start_sign_in]
     }

     // [START onActivityResult]
     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);

         // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
         if (requestCode == RC_SIGN_IN) {
             // The Task returned from this call is always completed, no need to attach
             // a listener.
             Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
             handleSignInResult(task);
         }
     }
     // [END onActivityResult]

     // [START handleSignInResult]
     private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
         try {
             GoogleSignInAccount account = completedTask.getResult(ApiException.class);

             // Signed in successfully, show authenticated UI.
             updateUI(account);
         } catch (ApiException e) {
             // The ApiException status code indicates the detailed failure reason.
             // Please refer to the GoogleSignInStatusCodes class reference for more information.
             Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
             e.printStackTrace();
             updateUI(null);
         }
     }
     // [END handleSignInResult]

     // [START signIn]
     private void signIn() {
         Intent signInIntent = mGoogleSignInClient.getSignInIntent();
         startActivityForResult(signInIntent, RC_SIGN_IN);
     }
     // [END signIn]

     // [START signOut]
     private void signOut() {
         mGoogleSignInClient.signOut()
                 .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(@NonNull Task<Void> task) {
                         // [START_EXCLUDE]
                         updateUI(null);
                         // [END_EXCLUDE]
                     }
                 });
     }
     // [END signOut]

     // [START revokeAccess]
     private void revokeAccess() {
         mGoogleSignInClient.revokeAccess()
                 .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(@NonNull Task<Void> task) {
                         // [START_EXCLUDE]
                         updateUI(null);
                         // [END_EXCLUDE]
                     }
                 });
     }
     // [END revokeAccess]

     private void updateUI(@Nullable GoogleSignInAccount account) {
         if (account != null) {
             mStatusTextView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));

             findViewById(R.id.sign_in_button).setVisibility(View.GONE);
             findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
         } else {
             mStatusTextView.setText(R.string.signed_out);

             findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
             findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
         }
     }

     @Override
     public void onClick(View v) {
         switch (v.getId()) {
             case R.id.sign_in_button:
                 signIn();
                 break;
             case R.id.sign_out_button:
                 signOut();
                 break;
             case R.id.disconnect_button:
                 revokeAccess();
                 break;
         }
     }
  }
</code>```

From what I read, the issue could be caused by SHA1 Generation.

I followed the complete guide but apparently it's not working.

I copied the SHA1 from gradle signingReport

```<code>Variant: debug
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
----------
Variant: release
Config: none
----------
Variant: debugAndroidTest
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
----------
Variant: debugUnitTest
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
</code>```

what could be the possible cause of this?

Thanks

P.S. Could this be a possible cause?

```<code>Google Play services out of date.  Requires 11720000 but found 10932470
</code>```

答:
Error PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 12500: , null)

This 12500 Error can be solved by adding a support email address
  to your project in project settings.    Open link
  https://console.firebase.google.com/

Select Your project and open settings tab.

Provide a valid support email and restart your application now.

Title: Google Sign In error 12500

Body:
I am trying to integrate Google Sign In into my app. I don't have a back-end server, I am just getting the details of the logged on Google Account to my app.

I first tried it by using Google Sign In Example but I got an error (No code changes made except for printing the stacktrace below). I just used the example SignInActivity as I don't have a back-end server.

 Exception com.google.android.gms.common.api.ApiException: 12500:
 at com.google.android.gms.common.internal.zzb.zzz(Unknown Source)
 at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
 at com.ewise.android.api.MainActivity.onActivityResult(SignInActivity.java:89)     at android.app.Activity.dispatchActivityResult(Activity.java:7010)
 at android.app.ActivityThread.deliverResults(ActivityThread.java:4187)
 at android.app.ActivityThread.handleSendResult(ActivityThread.java:4234)
 at android.app.ActivityThread.-wrap20(ActivityThread.java)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1584)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:6316)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

Code

 public class SignInActivity extends AppCompatActivity implements
         View.OnClickListener {

     private static final String TAG = "SignInActivity";
     private static final int RC_SIGN_IN = 9001;

     private GoogleSignInClient mGoogleSignInClient;
     private TextView mStatusTextView;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         // Views
         mStatusTextView = findViewById(R.id.status);

         // Button listeners
         findViewById(R.id.sign_in_button).setOnClickListener(this);
         findViewById(R.id.sign_out_button).setOnClickListener(this);
         findViewById(R.id.disconnect_button).setOnClickListener(this);

         // [START configure_signin]
         // Configure sign-in to request the user's ID, email address, and basic
         // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
         GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                 .requestEmail()
                 .build();
         // [END configure_signin]

         // [START build_client]
         // Build a GoogleSignInClient with the options specified by gso.
         mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
         // [END build_client]

         // [START customize_button]
         // Set the dimensions of the sign-in button.
         SignInButton signInButton = findViewById(R.id.sign_in_button);
         signInButton.setSize(SignInButton.SIZE_STANDARD);
         signInButton.setColorScheme(SignInButton.COLOR_LIGHT);
         // [END customize_button]
     }

     @Override
     public void onStart() {
         super.onStart();

         // [START on_start_sign_in]
         // Check for existing Google Sign In account, if the user is already signed in
         // the GoogleSignInAccount will be non-null.
         GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
         updateUI(account);
         // [END on_start_sign_in]
     }

     // [START onActivityResult]
     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);

         // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
         if (requestCode == RC_SIGN_IN) {
             // The Task returned from this call is always completed, no need to attach
             // a listener.
             Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
             handleSignInResult(task);
         }
     }
     // [END onActivityResult]

     // [START handleSignInResult]
     private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
         try {
             GoogleSignInAccount account = completedTask.getResult(ApiException.class);

             // Signed in successfully, show authenticated UI.
             updateUI(account);
         } catch (ApiException e) {
             // The ApiException status code indicates the detailed failure reason.
             // Please refer to the GoogleSignInStatusCodes class reference for more information.
             Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
             e.printStackTrace();
             updateUI(null);
         }
     }
     // [END handleSignInResult]

     // [START signIn]
     private void signIn() {
         Intent signInIntent = mGoogleSignInClient.getSignInIntent();
         startActivityForResult(signInIntent, RC_SIGN_IN);
     }
     // [END signIn]

     // [START signOut]
     private void signOut() {
         mGoogleSignInClient.signOut()
                 .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(@NonNull Task<Void> task) {
                         // [START_EXCLUDE]
                         updateUI(null);
                         // [END_EXCLUDE]
                     }
                 });
     }
     // [END signOut]

     // [START revokeAccess]
     private void revokeAccess() {
         mGoogleSignInClient.revokeAccess()
                 .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(@NonNull Task<Void> task) {
                         // [START_EXCLUDE]
                         updateUI(null);
                         // [END_EXCLUDE]
                     }
                 });
     }
     // [END revokeAccess]

     private void updateUI(@Nullable GoogleSignInAccount account) {
         if (account != null) {
             mStatusTextView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));

             findViewById(R.id.sign_in_button).setVisibility(View.GONE);
             findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
         } else {
             mStatusTextView.setText(R.string.signed_out);

             findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
             findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
         }
     }

     @Override
     public void onClick(View v) {
         switch (v.getId()) {
             case R.id.sign_in_button:
                 signIn();
                 break;
             case R.id.sign_out_button:
                 signOut();
                 break;
             case R.id.disconnect_button:
                 revokeAccess();
                 break;
         }
     }
  }

From what I read, the issue could be caused by SHA1 Generation.

I followed the complete guide but apparently it's not working.

I copied the SHA1 from gradle signingReport

Variant: debug
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
----------
Variant: release
Config: none
----------
Variant: debugAndroidTest
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
----------
Variant: debugUnitTest
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047

what could be the possible cause of this?

Thanks

P.S. Could this be a possible cause?

Google Play services out of date.  Requires 11720000 but found 10932470


问:
how to get a complete command of X apps via 'wmctl' and 'ps'?
I'm working on a program that can query running X apps, save all the commands of running apps and them reopen them latter.

I encounter an issue. wmctctl can query the pid of Onlyoffice, for example the pid is 123. Then run ps -ef -q 123, I see that the CMD is ./DesktopEditors which should be a invalid command, because ./one_command only can work in special folder include file one_command.

I can get a complete command by running ps -ef -q $(pgrep -P 123).

Is there a straight way to get the complete command of Onlyoffice just via wmctl and ps?

If there is a better way to get all commands of X apps, please let me know. Thanks.

答:
I suggest using ps -h -e -o pid,args command piped with a grep

This should provide full command path with it arguments and options.

For example find all running java programs with their arguments (might be extensive):

```<code>ps -eo pid,args | grep java
</code>```

In your case I suggest a small awk script, that looks for the pid given as 3rd input field in current line:

```<code>wmctrl -l -p|awk '{system("ps -h --pid "$3" -o args")}'
</code>```

Sample output

```<code>nautilus-desktop --force
/usr/libexec/gnome-terminal-server
/usr/libexec/gnome-terminal-server
</code>```

update

Transforming current directory ./ to  to full path.
Assuming ./ represent the current working directory.
Add the following pipe.

```<code>wmctrl -l -p|awk '{system("ps -h --pid "$3" -o args")}'|sed "s|^\./|$PWD/|"
</code>```

Find the script or program DesktopEditors in your computer, using find / -name "DesktopEditors".

But I believe this is useless if you are trying to reverse engineer a web based application that requires some kind of a browser emulator.

Body:
I suggest using ps -h -e -o pid,args command piped with a grep

This should provide full command path with it arguments and options.

For example find all running java programs with their arguments (might be extensive):

ps -eo pid,args | grep java

In your case I suggest a small awk script, that looks for the pid given as 3rd input field in current line:

wmctrl -l -p|awk '{system("ps -h --pid "$3" -o args")}'

Sample output

nautilus-desktop --force
/usr/libexec/gnome-terminal-server
/usr/libexec/gnome-terminal-server

update

Transforming current directory ./ to  to full path.
Assuming ./ represent the current working directory.
Add the following pipe.

wmctrl -l -p|awk '{system("ps -h --pid "$3" -o args")}'|sed "s|^\./|$PWD/|"

Find the script or program DesktopEditors in your computer, using find / -name "DesktopEditors".

But I believe this is useless if you are trying to reverse engineer a web based application that requires some kind of a browser emulator.


问:
Why inheritance works this way in Java?
I'm new to Java and I'm trying to understand what would happen when I assign a child class instance to a parent class instance variable by simulating the following program.

```<code>public class ConfusionWithInheritance {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        DerievedClass d = new DerievedClass();
        BaseClass b = BaseClass.class.cast(d);
        BaseClass b1 = new DerievedClass();
        b.doSomeJob();
        b.printMagic(); //-> Compiler shouted me that it didn't know this method here.
    }
}
class BaseClass {
    public void doSomeJob() {
        System.out.println("Printing Value X");
    }
}
class DerievedClass extends BaseClass {
    public void doSomeJob() {
        System.out.println("Printing Value Y");
    }
    public void printMagic() {
        System.out.println("Printing magic...");
    }
}
</code>```

1) Why am I allowed to assign an instance of a child class to a parent type variable?

2) From this answer, it's explained that since I'm telling the blue print of the class to be - the parent class - it knows only the methods in the parent class. Then why it's printing the value in the method of child class when I'm invoking childInstance.doSomeJob()?

答:
When creating an object:

```<code>BaseClass b1 = new DerievedClass();
</code>```

What we're saying is:

```<code>ReferenceType variableName = new ConcreteImplementation();
</code>```

Think of it as the ReferenceType providing a scaffold for a new Object.

When an object is created it looks to this ReferenceType and creates an object with all the methods in ReferenceType as a skeleton.

Then we look at the ConcreteImplementation for the implementation of the methods.
So the compiler looks to ConcreteImplementation to fill in all the methods.

Only what's defined in ReferenceType is implemented in the final object.

Think of casting as changing the ReferenceType of an already existing object

With the line:

```<code>DerievedClass d = new DerievedClass();
</code>```

ReferenceType is DerievedClass so we take all the methods from DerivedClass
and fill them in with the implementation from the ConcreteImplementation which is DerivedClass.

Then we're casting DerievedClass d to BaseClass b.

```<code>BaseClass b = BaseClass.class.cast(d);
</code>```

d has all the implementation from DerivedClass but the scaffold came from the ReferencType BaseClass so we can't call printMagic
because it doesn't exist in BaseClass.

Does that make sense?

Hope it helps

Title: Why inheritance works this way in Java?

Body:
I'm new to Java and I'm trying to understand what would happen when I assign a child class instance to a parent class instance variable by simulating the following program.

public class ConfusionWithInheritance {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        DerievedClass d = new DerievedClass();
        BaseClass b = BaseClass.class.cast(d);
        BaseClass b1 = new DerievedClass();
        b.doSomeJob();
        b.printMagic(); //-> Compiler shouted me that it didn't know this method here.
    }
}
class BaseClass {
    public void doSomeJob() {
        System.out.println("Printing Value X");
    }
}
class DerievedClass extends BaseClass {
    public void doSomeJob() {
        System.out.println("Printing Value Y");
    }
    public void printMagic() {
        System.out.println("Printing magic...");
    }
}

1) Why am I allowed to assign an instance of a child class to a parent type variable?

2) From this answer, it's explained that since I'm telling the blue print of the class to be - the parent class - it knows only the methods in the parent class. Then why it's printing the value in the method of child class when I'm invoking childInstance.doSomeJob()?

Body:
When creating an object:

BaseClass b1 = new DerievedClass();

What we're saying is:

ReferenceType variableName = new ConcreteImplementation();

Think of it as the ReferenceType providing a scaffold for a new Object.

When an object is created it looks to this ReferenceType and creates an object with all the methods in ReferenceType as a skeleton.

Then we look at the ConcreteImplementation for the implementation of the methods.
So the compiler looks to ConcreteImplementation to fill in all the methods.

Only what's defined in ReferenceType is implemented in the final object.

Think of casting as changing the ReferenceType of an already existing object

With the line:

DerievedClass d = new DerievedClass();

ReferenceType is DerievedClass so we take all the methods from DerivedClass
and fill them in with the implementation from the ConcreteImplementation which is DerivedClass.

Then we're casting DerievedClass d to BaseClass b.

BaseClass b = BaseClass.class.cast(d);

d has all the implementation from DerivedClass but the scaffold came from the ReferencType BaseClass so we can't call printMagic
because it doesn't exist in BaseClass.

Does that make sense?

Hope it helps


问:
Cannot instantiate abstract class
I have base abastract class Employee with pure virtual method clone

```<code>virtual Employee* clone() const = 0;
</code>```

Also i have derived class DeveloperEmployee that override this method:

```<code>DeveloperEmployee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}
</code>```

Now I have these lines in main:

```<code>DeveloperEmployee* a = new DeveloperEmployee(description, project);
DeveloperEmployee* a_copy = a->clone();
</code>```

And I cannot change these lines. It says me that I can't instantiate abstract class, so how should I change the code?

If I change overrided method to

```<code>Employee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}
</code>```

I have cast problem in main and I cannot change main.

答:
I'm not sure what the other answers mean by "you don't override, because return type is different". Return type is not part of the function signature, and it is perfectly fine to change return type to a derived one, provided that return type was originally a pointer or reference to a type (i.e. they are covariant types - thanks for the link HolyBlackCat).

The following example compiles (with warning about unused variable). See it online!:

```<code>class A{
public:
    virtual A* foo() const = 0;
};

class B:public A{
public:
    B* foo() const override {return new B();}
};

int main() {
    B b;
    A* ptr = b.foo();
}
</code>```

If it wasn't allowed, compiler would throw an error thanks to the override keyword, for example in GCC:

```<code>prog.cc:12:17: error: conflicting return type specified for 'virtual

std::__cxx11::string B::bar()'
     std::string bar() override { return {}; }
                 ^~~
prog.cc:6:20: note: overridden function is 'virtual double A::bar()'
     virtual double bar() = 0;
                    ^~~
</code>```

The problem is somewhere in the code you don't show. Perhaps you're trying to create a variable of type Employee somewhere?

Title: Cannot instantiate abstract class

Body:
I have base abastract class Employee with pure virtual method clone

virtual Employee* clone() const = 0;

Also i have derived class DeveloperEmployee that override this method:

DeveloperEmployee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}

Now I have these lines in main:

DeveloperEmployee* a = new DeveloperEmployee(description, project);
DeveloperEmployee* a_copy = a->clone();

And I cannot change these lines. It says me that I can't instantiate abstract class, so how should I change the code?

If I change overrided method to

Employee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}

I have cast problem in main and I cannot change main.

Body:
I'm not sure what the other answers mean by "you don't override, because return type is different". Return type is not part of the function signature, and it is perfectly fine to change return type to a derived one, provided that return type was originally a pointer or reference to a type (i.e. they are covariant types - thanks for the link HolyBlackCat).

The following example compiles (with warning about unused variable). See it online!:

class A{
public:
    virtual A* foo() const = 0;
};

class B:public A{
public:
    B* foo() const override {return new B();}
};

int main() {
    B b;
    A* ptr = b.foo();
}

If it wasn't allowed, compiler would throw an error thanks to the override keyword, for example in GCC:

prog.cc:12:17: error: conflicting return type specified for 'virtual

std::__cxx11::string B::bar()'
     std::string bar() override { return {}; }
                 ^~~
prog.cc:6:20: note: overridden function is 'virtual double A::bar()'
     virtual double bar() = 0;
                    ^~~

The problem is somewhere in the code you don't show. Perhaps you're trying to create a variable of type Employee somewhere?


问:
How to fix date formatting using python3
I have data with the date format as follows:

    date_format = 190410
    year  = 19
    month = 04
    date  = 10
```

<p>I want to change the date format, to be like this:</p>

```date_format = 10-04-2019
```

How do I solve this problem?

答:
```<code>>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'
</code>```

datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.

Body:
I have data with the date format as follows:

    date_format = 190410
    year  = 19
    month = 04
    date  = 10

I want to change the date format, to be like this:

date_format = 10-04-2019

How do I solve this problem?

Body:
>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'

datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.


问:
ScriptEngineManager extra cautious exception handling
I wanted to consult about JDK code exception handling,

In ScriptEngineManager from lines 120 there are unused secondary catch for ServiceConfigurationError which can't be thrown as I understand it

```<code>   try {
        while (itr.hasNext()) {
            try {
                ScriptEngineFactory fact = (ScriptEngineFactory) itr.next();
                facList.add(fact);
            } catch (ServiceConfigurationError err) {
                System.err.println("ScriptEngineManager providers.next(): "
                             + err.getMessage());
                if (DEBUG) {
                    err.printStackTrace();
                }
                // one factory failed, but check other factories...
                continue;
            }
        }
    } catch (ServiceConfigurationError err) {
        System.err.println("ScriptEngineManager providers.hasNext(): "
                        + err.getMessage());
</code>```

Is there a reason why a second catch will be necessary? it seems it effect only while (itr.hasNext()) which doesn't throw any exception

Or is it just overly cautious to ensure method not throwing exception in any case, as commented

```<code>// do not throw any exception here.
</code>```

Actually java allows you to duplicate such try-catch  without any error/warning:

```<code> try {
     try {
            ScriptEngineFactory fact = itr.next();
            engineSpis.add(fact);
        } catch (ServiceConfigurationError err) {
            err.printStackTrace();
        }
    } catch (ServiceConfigurationError err) {
        err.printStackTrace();
    }
</code>```

If I'll concatenate catches in same try I would get compilation error

```<code>Unreachable catch block for ServiceConfigurationError. It is already handled by the catch block for ServiceConfigurationError
</code>```

答:
Minor misconception: the second catch does not only cover the while loop. It would also take care about such exceptions thrown from within the first catch block.

But you are correct: that catch block, as well as the loop "header" should not throw such an exception. It seems rather odd that simply iterating an iterator needs "protection" in such a way.

Thus: maybe this is a leftover when other code existed in that method. Or it is overdoing. Or worst case, the code that we don't see (that creates that iterator) can in fact throwing that kind of error. Which, as said, would be odd and a very bizarre design, to say the least.

Body:
I wanted to consult about JDK code exception handling,

In ScriptEngineManager from lines 120 there are unused secondary catch for ServiceConfigurationError which can't be thrown as I understand it

   try {
        while (itr.hasNext()) {
            try {
                ScriptEngineFactory fact = (ScriptEngineFactory) itr.next();
                facList.add(fact);
            } catch (ServiceConfigurationError err) {
                System.err.println("ScriptEngineManager providers.next(): "
                             + err.getMessage());
                if (DEBUG) {
                    err.printStackTrace();
                }
                // one factory failed, but check other factories...
                continue;
            }
        }
    } catch (ServiceConfigurationError err) {
        System.err.println("ScriptEngineManager providers.hasNext(): "
                        + err.getMessage());

Is there a reason why a second catch will be necessary? it seems it effect only while (itr.hasNext()) which doesn't throw any exception

Or is it just overly cautious to ensure method not throwing exception in any case, as commented

// do not throw any exception here.

Actually java allows you to duplicate such try-catch  without any error/warning:

 try {
     try {
            ScriptEngineFactory fact = itr.next();
            engineSpis.add(fact);
        } catch (ServiceConfigurationError err) {
            err.printStackTrace();
        }
    } catch (ServiceConfigurationError err) {
        err.printStackTrace();
    }

If I'll concatenate catches in same try I would get compilation error

Unreachable catch block for ServiceConfigurationError. It is already handled by the catch block for ServiceConfigurationError


问:
Retrieving some values in array
Hi
I have an array of random question nos (ids). I have one form with a label for the question, a radiobutton list for their answers and a next button & checkbox to review that question. When I click the next button next(random from array) question appears. I want question id(array) those are checked for review.  How can I do this?
I used code as follows that calculates array (like this:10111) as i gives 1 value for checked & 0 for unchecked rather that this i want array of question ids those are checked :</p>

```<code>//Code gives array of checked values in terms of 1 & o
            int g;
            if (chkmark.Checked == true)
            {
                g = 1;
            }
            else
            {
                g = 0;
            }
            int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
            int[] temp1 = (int[])Session["arrofchk"];
            int k, no;

            if (temp1 == null)
                no = 0;
            else
                no = temp.Length;
            for (k = 0; k < no; k++)
            {
           chkarray[k] = temp1[k];
            }
            chkarray[j] = g;
</code>```

答:
With the information you have given, this is the best I can do.  This will return a random number from your array which I assume to be of ints since it holds numbers (or IDs as you said).</p>

```<code>        int[] questionIDs = new int[10];
        Random randomIndex = new Random(DateTime.Now.Millisecond);
        int nextQuestion = questionIDs[randomIndex.Next(questionIDs.Length - 1)];
</code>```

Title: Retrieving some values in array

Body:
Hi
I have an array of random question nos (ids). I have one form with a label for the question, a radiobutton list for their answers and a next button & checkbox to review that question. When I click the next button next(random from array) question appears. I want question id(array) those are checked for review.  How can I do this?
I used code as follows that calculates array (like this:10111) as i gives 1 value for checked & 0 for unchecked rather that this i want array of question ids those are checked :

//Code gives array of checked values in terms of 1 & o
            int g;
            if (chkmark.Checked == true)
            {
                g = 1;
            }
            else
            {
                g = 0;
            }
            int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
            int[] temp1 = (int[])Session["arrofchk"];
            int k, no;

            if (temp1 == null)
                no = 0;
            else
                no = temp.Length;
            for (k = 0; k < no; k++)
            {
           chkarray[k] = temp1[k];
            }
            chkarray[j] = g;

Body:
With the information you have given, this is the best I can do.  This will return a random number from your array which I assume to be of ints since it holds numbers (or IDs as you said).

        int[] questionIDs = new int[10];
        Random randomIndex = new Random(DateTime.Now.Millisecond);
        int nextQuestion = questionIDs[randomIndex.Next(questionIDs.Length - 1)];


问:
apply() function not working on individual rows
I have written a function to extract data from a large matrix ("c.mat") for each row in a data.frame ("df.1"). The data.frame has an indexing row in it ("df.1$hour") which corresponds to the relevant column in the matrix. There is an equal number of rows between the matrix and the data.frame so the function goes:

```<code>assignUV.FUN <- function(df, mat){
  num=df$hour
  value = mat[as.numeric(rownames(df)),num]
  return(value)
}
</code>```

Quite simple. However when using apply to run this for each row:

```<code>df.1 <- data.frame(hour= round(runif(10,1,100)), x = seq(1,10, length=10))
c.mat <- matrix(runif(1000,1,5), nrow=10)

try <- apply(df.1, 1, assignUV.FUN, mat = c.mat, df=df.1)
</code>```

I get the error:

```<code>Error in FUN(newX[, i], ...) : unused argument (newX[, i])
</code>```

I'm sure there is a conflict here whereby I am calling the data.frame twice, once from inside the assignUV.FUN function and once with apply but I can;t figure out why this won't work.

Any thoughts? It works fine if I just run on a single row:

```<code>assignUV.FUN(df = df.1[1,], mat=c.mat)
</code>```

答:
Ronak's vector approach is the way to go, but I hope this can be instructive. apply does not pass a data.frame to FUN, but instead a vector, so you can try,

```<code>assignUV.FUN <- function(DF, mat){
  num=DF[1]
  value = mat[DF[2],num]
  return(value)
}

try <- apply(df.1, 1, assignUV.FUN, mat = c.mat)
</code>```

It is unnecessary to pass all arguments of FUN to apply, I only passed c.mat since it is not being 'looped through'. Also, I try to avoid naming data.frames df, since R already has a function called df (density of the F distribution).

Body:
I have written a function to extract data from a large matrix ("c.mat") for each row in a data.frame ("df.1"). The data.frame has an indexing row in it ("df.1$hour") which corresponds to the relevant column in the matrix. There is an equal number of rows between the matrix and the data.frame so the function goes:

assignUV.FUN <- function(df, mat){
  num=df$hour
  value = mat[as.numeric(rownames(df)),num]
  return(value)
}

Quite simple. However when using apply to run this for each row:

df.1 <- data.frame(hour= round(runif(10,1,100)), x = seq(1,10, length=10))
c.mat <- matrix(runif(1000,1,5), nrow=10)

try <- apply(df.1, 1, assignUV.FUN, mat = c.mat, df=df.1)

I get the error:

Error in FUN(newX[, i], ...) : unused argument (newX[, i])

I'm sure there is a conflict here whereby I am calling the data.frame twice, once from inside the assignUV.FUN function and once with apply but I can;t figure out why this won't work.

Any thoughts? It works fine if I just run on a single row:

assignUV.FUN(df = df.1[1,], mat=c.mat)

Body:
Ronak's vector approach is the way to go, but I hope this can be instructive. apply does not pass a data.frame to FUN, but instead a vector, so you can try,

assignUV.FUN <- function(DF, mat){
  num=DF[1]
  value = mat[DF[2],num]
  return(value)
}

try <- apply(df.1, 1, assignUV.FUN, mat = c.mat)

It is unnecessary to pass all arguments of FUN to apply, I only passed c.mat since it is not being 'looped through'. Also, I try to avoid naming data.frames df, since R already has a function called df (density of the F distribution).


问:
make:entity fails for some existing entites
I like to use make:entity MyEntity to ammend entities (add fields, getters, setters). Normally it gives the output:

```<code>$ sym make:entity MyEntity
Your entity already exists! So let's add some new fields!
</code>```

However, for some entities this will result in

```<code>$ sym make:entity SomeOtherEntity
[ERROR] The file "src/Repository/SomeOtherEntity.php" can't be generated because it already exists.
</code>```

The difference between the entities is their location:

MyEntity is in src/Entity

SomeOtherEntity is in src/Domain/Model

However, the entities are all included in the config, as I added

```<code>Model:
    is_bundle: false
    type: annotation
    dir: '%kernel.project_dir%/src/Domain/Model'
    prefix: 'App\Domain\Model'
    alias: Model
App:
    is_bundle: false
    type: annotation
    dir: '%kernel.project_dir%/src/Entity'
    prefix: 'App\Entity'
    alias: App
</code>```

E.g. migrations work fine with this. It is just that make:entity fails.
The question is, can I use make:entity for entities that are not loacated in the default locatio?

Any hint would be apppreciated.

答:
Yes you can.

In order to create brand new entity in different namespace with command make:entity, you can use command:

php bin/console make:entity \\App\\Domain\\Model\\SomeOtherEntity

If you use make:entity for existing entities, you should add flag --regenerate to the command.

So the command for regenerating getters and setters for existing entity will look a bit differently:

php bin/console make:entity --regenerate App\\Domain\\Model\\SomeOtherEntity

Body:
I like to use make:entity MyEntity to ammend entities (add fields, getters, setters). Normally it gives the output:

$ sym make:entity MyEntity
Your entity already exists! So let's add some new fields!

However, for some entities this will result in

$ sym make:entity SomeOtherEntity
[ERROR] The file "src/Repository/SomeOtherEntity.php" can't be generated because it already exists.

The difference between the entities is their location:

MyEntity is in src/Entity

SomeOtherEntity is in src/Domain/Model

However, the entities are all included in the config, as I added

Model:
    is_bundle: false
    type: annotation
    dir: '%kernel.project_dir%/src/Domain/Model'
    prefix: 'App\Domain\Model'
    alias: Model
App:
    is_bundle: false
    type: annotation
    dir: '%kernel.project_dir%/src/Entity'
    prefix: 'App\Entity'
    alias: App

E.g. migrations work fine with this. It is just that make:entity fails.
The question is, can I use make:entity for entities that are not loacated in the default locatio?

Any hint would be apppreciated.


问:
How to plot three categorical values?
I have data like the following (three categorical values):

```<code>data <- data.frame(Comp = (rep(c('Oral','Text'), each = 8)),
                   Cat = rep(c('Declative','Non-declative'), 4),
                   Type = rep(c('Free','Used'), each = 4))
</code>```

I want to have an interaction.plot or barplot with these three categorical values in R. Would you give me any tip?

答:
Although your supplied data don't produce a good display since the cells are all equal sized you can use base r to make a mosaic plot.

```<code>data <- data.frame(Comp = (rep(c('Oral','Text'), each = 8)),
                   Cat = rep(c('Declative','Non-declative'), 4),
                   Type = rep(c('Free','Used'), each = 3))
mosaicplot(table( data$Comp,data$Cat,data$Type))
</code>```

Here's a variant on your data that shows it a little better.

```<code>data <- data.frame(Comp = (rep(c('Oral','Text'), each = 8)),
                   Cat = rep(c('Declative','Non-declative'), 4),
                   Type = c(rep(c('Free','Used'), each = 3), c('Used', 'Used')))
mosaicplot(table( data$Comp,data$Cat,  data$Type))

</code>```

Of course you can go to specialized packages to get other variations,  vcd is one but if you search you will find others.

Title: How to plot three categorical values?

Body:
I have data like the following (three categorical values):

data <- data.frame(Comp = (rep(c('Oral','Text'), each = 8)),
                   Cat = rep(c('Declative','Non-declative'), 4),
                   Type = rep(c('Free','Used'), each = 4))

I want to have an interaction.plot or barplot with these three categorical values in R. Would you give me any tip?

Body:
Although your supplied data don't produce a good display since the cells are all equal sized you can use base r to make a mosaic plot.

data <- data.frame(Comp = (rep(c('Oral','Text'), each = 8)),
                   Cat = rep(c('Declative','Non-declative'), 4),
                   Type = rep(c('Free','Used'), each = 3))
mosaicplot(table( data$Comp,data$Cat,data$Type))

Here's a variant on your data that shows it a little better.

data <- data.frame(Comp = (rep(c('Oral','Text'), each = 8)),
                   Cat = rep(c('Declative','Non-declative'), 4),
                   Type = c(rep(c('Free','Used'), each = 3), c('Used', 'Used')))
mosaicplot(table( data$Comp,data$Cat,  data$Type))

Of course you can go to specialized packages to get other variations,  vcd is one but if you search you will find others.


问:
How to normalize a relative path using pathlib
I'm trying to use relative paths in Python, and I want to put my csv files in a separate folder from my python code.

My python program is in the following folder:

```<code>G:\projects\code
</code>```

I want to read this file which is one level up:

```<code>G:\projects\data\sales.csv
</code>```

How do I specify a path using pathlib that is one level up from my current working folder? I don't want to change the current working folder.

I tried this:

```<code>from pathlib import Path
file = Path.cwd() /'..'/'data'/'sales.csv'
</code>```

But now the 'file' variable equals this:

```<code>'G:/projects/code/../data/sales.csv'
</code>```

I read through the docs and either it isn't explained there or I'm just missing it.

答:
Do you mean "read my csv files"?

The import keyword has a different meaning in Python (you import only other Python modules).

In any case, in order to read a file located one folder above your Python file, you can use this:

```<code>import os
filePath = os.path.dirname(__file__)+'/../'+fileName
fileDesc = open(filePath)
fileData = fileDesc.read()
fileDesc.close()
...
</code>```

Body:
I'm trying to use relative paths in Python, and I want to put my csv files in a separate folder from my python code.

My python program is in the following folder:

G:\projects\code

I want to read this file which is one level up:

G:\projects\data\sales.csv

How do I specify a path using pathlib that is one level up from my current working folder? I don't want to change the current working folder.

I tried this:

from pathlib import Path
file = Path.cwd() /'..'/'data'/'sales.csv'

But now the 'file' variable equals this:

'G:/projects/code/../data/sales.csv'

I read through the docs and either it isn't explained there or I'm just missing it.

Body:
Do you mean "read my csv files"?

The import keyword has a different meaning in Python (you import only other Python modules).

In any case, in order to read a file located one folder above your Python file, you can use this:

import os
filePath = os.path.dirname(__file__)+'/../'+fileName
fileDesc = open(filePath)
fileData = fileDesc.read()
fileDesc.close()
...


问:
Stop the Android browser gets refreshed
The Android browser gets refreshed within my app when the keyboard (Android version devices which have a flip keyboard) is pulled out and the app loses cetain elements. How can we prevent the browser to be refresh.</p>

答:
When the phone is flipped out, the active activity is closed and reopened. You need to use OnSaveInstanceState and onRestoreInstanceState to persist your data and restore it when this happens.

UPDATE: You can also take a look at this thread for more info: How to stop android activity destruction

Title: Stop the Android browser gets refreshed


问:
How to preprocess a column with too many NAN values?
I have a training data of shape (596000, 58) and below image has some of the features vs number of "NAN"s in the features/rows using train.isnull().sum().

Considering each feature has equal importance and are categorical values Should I remove the column cat6 and cat8? as for cat6 411792/596000 are NaNs and for cat8 266928/596000 are NaNs.

Is there a way to deal with this situation ? or I have to remove both the columns ?

input [12]: train.isnull().sum()

output [12]:

答:
Removing both cat6 and cat8 is best here.
As you have 500k values, assuming all the above values are categorical, rest you can make a new category for rest NaN values of other features.


问:
How to use an image on the left in a cell of UITableView
I want to use radio button images in each cell of my TableView. This images should be aligned to the left so that it would give an impression of selecting a single from multiple rows.

Please provide me with links, tutorials or code snippets.

Thanks,

答:
for this you have to create custom cell.
and change image of whole cell including radiobutton image when it is selected..</p>

ContentLicense: CC BY-SA 2.5