问:
how to subset part of data using for-loop
I am a newbie to R programming recently.

I want to transform the existing matrix form to new one.

The matrix that I have as follows,

data()

```<code>    1       2       3       4       5       6
1   0.60!   0.29!   1.42!   0.64    1.06    1.02
2   1.33!   0.68!   1.44!   1.44    1.05    1.03
3   0.60    0.67@   0.64    1.37    2.40    1.00
4   1.37    0.29    1.43    0.63    1.05    2.32
5   1.39    0.68    1.40    1.46    1.06    1.02
6   0.63    0.68    0.61    1.46    1.74    1.05
7   1.39    0.68    1.01    0.65    2.43    2.27
....
</code>```

I've listed the first line with '!' And '@' for easy understanding.

What I want to is,

vari()

```<code>    1       2       3       4       5       6       7
1   0.60!   0.29!   1.42!   1.33!   0.68!   1.44!   0.67@
2   0.29    1.42    0.64    0.68    1.44    1.44    0.64
3   1.42    0.64    1.06    1.44    1.44    1.05    1.37
4   0.64    1.06    1.02    1.44    1.05    1.03    2.40
5   1.33    0.68    1.44    0.60    0.67    0.64    0.29
6
….
</code>```

I would like to list the data in the 1:2 rows and 1:3 columns in one line and locate the (3,2)value to (1,7) in vari matrix.

I think it would be work with the for-loop. I made the code, however, it is my first time to make it. So, it doesn't work well.

This is my trial....

```<code>x=matrix(nrow = nrow(data)-2, ncol = 8);

for ( i in 1:(nrow(data)))
{ for ( j in 1:(ncol(data)))
{
  x[i,j]<-((c(as.vector(t(as.matrix(data[i:i+1,j:j+2]))),data[i+2,j+1])))
}
}
x
</code>```

however, it represent the following sentence

"Error in data[i:i + 1, j:j + 2] : subscript out of bounds"

Please help me!!!

Body:
I am a newbie to R programming recently.

I want to transform the existing matrix form to new one.

The matrix that I have as follows,

data()

    1       2       3       4       5       6
1   0.60!   0.29!   1.42!   0.64    1.06    1.02
2   1.33!   0.68!   1.44!   1.44    1.05    1.03
3   0.60    0.67@   0.64    1.37    2.40    1.00
4   1.37    0.29    1.43    0.63    1.05    2.32
5   1.39    0.68    1.40    1.46    1.06    1.02
6   0.63    0.68    0.61    1.46    1.74    1.05
7   1.39    0.68    1.01    0.65    2.43    2.27
....

I've listed the first line with '!' And '@' for easy understanding.

What I want to is,

vari()

    1       2       3       4       5       6       7
1   0.60!   0.29!   1.42!   1.33!   0.68!   1.44!   0.67@
2   0.29    1.42    0.64    0.68    1.44    1.44    0.64
3   1.42    0.64    1.06    1.44    1.44    1.05    1.37
4   0.64    1.06    1.02    1.44    1.05    1.03    2.40
5   1.33    0.68    1.44    0.60    0.67    0.64    0.29
6
….

I would like to list the data in the 1:2 rows and 1:3 columns in one line and locate the (3,2)value to (1,7) in vari matrix.

I think it would be work with the for-loop. I made the code, however, it is my first time to make it. So, it doesn't work well.

This is my trial....

x=matrix(nrow = nrow(data)-2, ncol = 8);

for ( i in 1:(nrow(data)))
{ for ( j in 1:(ncol(data)))
{
  x[i,j]<-((c(as.vector(t(as.matrix(data[i:i+1,j:j+2]))),data[i+2,j+1])))
}
}
x

however, it represent the following sentence

"Error in data[i:i + 1, j:j + 2] : subscript out of bounds"

Please help me!!!

Body:
You needed to improve your indexing into the second data frame, I have added the n counter for this.

x=matrix(nrow = nrow(data)-2, ncol = 7);

n=1
for ( i in 1:(nrow(data)-3)){
  for ( j in 1:(ncol(data)-2)){
    x[n,]<-c(t(data[i:(i+1),j:(j+2)]),data[i+2,j+1])
    n=n+1
  }
}

 x
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0.60 0.29 1.42 1.33 0.68 1.44 0.67
[2,] 0.29 1.42 0.64 0.68 1.44 1.44 0.64
[3,] 1.42 0.64 1.06 1.44 1.44 1.05 1.37
[4,] 0.64 1.06 1.02 1.44 1.05 1.03 2.40
[5,] 1.33 0.68 1.44 0.60 0.67 0.64 0.29

Also be careful i:i+1is different to i:(i+1) which is what you were after.


来源: stackexchange

问:
In a socket.recv(1024), how can I search for a specific word inside of it?
I have a simple banner grabber. If I grab a banner from Google, I receive something back.

I want to find a specific word inside the socket data? How can I do that?

My Banner grabber:

```<code>import socket
import ipaddress

import socket
host = "www.google.nl"
port = 80
addr = (host, port)
s = socket.socket()
s.connect (addr)
s.send(b'GET / HTTP/1.1\n\n\n')
print(s.recv(1024))
</code>```

Banner I receive from Google.nl (s.recv(1024)):

b'HTTP/1.1 302 Found\r\nCache-Control: private\r\nContent-Type: text/html; charset=UTF-8\r\nReferrer-Policy: no-referrer\r\nLocation: http://www.google.nl/?gfe_rd=cr&dcr=0&ei=XrAKWpHeJ9GC3gOB_ZWoBg\r\nContent-Length: 268\r\nDate: Tue, 14 Nov 2017 08:59:10 GMT\r\n\r\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE>\n
302 Moved
\nThe document has moved\nhere.\r\n\r\n'

What I want:

```<code>If "Document" is in s.recv(1024):
print ("Document is found in the banner!")

Else:
print ("No keyword found")
</code>```

答:
If you write the pseudo code if else construct in python (simple change), store the received bytes in variable and naively transform them to string, you can continue your programming with:

```<code>import socket
host = "www.google.nl"
port = 80
addr = (host, port)
s = socket.socket()
s.connect(addr)
s.send(b'GET / HTTP/1.1\n\n\n')
b_text = s.recv(1024)
print(b_text)
if "Document" in str(b_text):
    print("Document is found in the banner!")
else:
    print("No keyword found")
</code>```

In case you want to spare the variable (I do not know the use case), a code snippet working "directly on the result of the s.recv() call" is:

```<code>import socket
host = "www.google.nl"
port = 80
addr = (host, port)
s = socket.socket()
s.connect(addr)
s.send(b'GET / HTTP/1.1\n\n\n')
if "Document" in str(s.recv(1024)):
    print("Document is found in the banner!")
else:
    print("No keyword found")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a simple banner grabber. If I grab a banner from Google, I receive something back.

I want to find a specific word inside the socket data? How can I do that?

My Banner grabber:

import socket
import ipaddress

import socket
host = "www.google.nl"
port = 80
addr = (host, port)
s = socket.socket()
s.connect (addr)
s.send(b'GET / HTTP/1.1\n\n\n')
print(s.recv(1024))

Banner I receive from Google.nl (s.recv(1024)):

b'HTTP/1.1 302 Found\r\nCache-Control: private\r\nContent-Type: text/html; charset=UTF-8\r\nReferrer-Policy: no-referrer\r\nLocation: http://www.google.nl/?gfe_rd=cr&dcr=0&ei=XrAKWpHeJ9GC3gOB_ZWoBg\r\nContent-Length: 268\r\nDate: Tue, 14 Nov 2017 08:59:10 GMT\r\n\r\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE>\n
302 Moved
\nThe document has moved\nhere.\r\n\r\n'

What I want:

If "Document" is in s.recv(1024):
print ("Document is found in the banner!")

Else:
print ("No keyword found")

Body:
If you write the pseudo code if else construct in python (simple change), store the received bytes in variable and naively transform them to string, you can continue your programming with:

import socket
host = "www.google.nl"
port = 80
addr = (host, port)
s = socket.socket()
s.connect(addr)
s.send(b'GET / HTTP/1.1\n\n\n')
b_text = s.recv(1024)
print(b_text)
if "Document" in str(b_text):
    print("Document is found in the banner!")
else:
    print("No keyword found")

In case you want to spare the variable (I do not know the use case), a code snippet working "directly on the result of the s.recv() call" is:

import socket
host = "www.google.nl"
port = 80
addr = (host, port)
s = socket.socket()
s.connect(addr)
s.send(b'GET / HTTP/1.1\n\n\n')
if "Document" in str(s.recv(1024)):
    print("Document is found in the banner!")
else:
    print("No keyword found")


问:
UnitOfWork: How to rollback and keep the logs
I have a method as below:

using (var unitOfWork = _unitOfWorkManager.Begin())
{
    var result = await ExcuteOperator(input);
    if (!result.WorkflowStatus)
    {
        unitOfWork.Dispose();
    }
    unitOfWork.Complete();
}

public async Task<ExecuteOperatorOutput> ExcuteOperator(ExecuteOperatorInput input)
{
    //Doing something
    DoSomething(input);

    //Insert log
    await _logRepository.InsertAsync(logInput);

    //Recursive
    return await ExcuteOperator(input);
}
```

My question is: How to rollback the unitOfWork manually without throw exception before unitOfWork.Complete() and keep the inserted logs?

答:
There is no way to rollback the unitOfWork manually.

See rationale/attempts: https://github.com/aspnetboilerplate/aspnetboilerplate/issues?q=rollback

That said, an interested reader is welcome to attempt and solve the issues.

How to keep the logs after the transaction rolled back?

Begin a new unitOfWork that gets completed:

public async Task<ExecuteOperatorOutput> ExcuteOperator(ExecuteOperatorInput input)
{
    //...

    using (var unitOfWork = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
    {
        await _logRepository.InsertAsync(logInput);
        unitOfWork.Complete();
    }

    //...
}
```

Body:
I have a method as below:

using (var unitOfWork = _unitOfWorkManager.Begin())
{
    var result = await ExcuteOperator(input);
    if (!result.WorkflowStatus)
    {
        unitOfWork.Dispose();
    }
    unitOfWork.Complete();
}

public async Task<ExecuteOperatorOutput> ExcuteOperator(ExecuteOperatorInput input)
{
    //Doing something
    DoSomething(input);

    //Insert log
    await _logRepository.InsertAsync(logInput);

    //Recursive
    return await ExcuteOperator(input);
}

My question is: How to rollback the unitOfWork manually without throw exception before unitOfWork.Complete() and keep the inserted logs?


问:
response.data sent from php backend is empty
I'm working in a website of temporary emails, one of the functionality that I have to implement is getting the origin of the email(getting email's headers), so I implemented this code to do that:

backend(php):

```<code>function get_original_email($mailid, $address) {
global $mailbox;

if (_load_one_email($mailid, $address) !== null) {
    header('Content-type: application/json');
    $headers = imap_fetchheader($mailbox->getImapStream(), $mailid, FT_UID);
    //$body = imap_body($mailbox->getImapStream(), $mailid, FT_UID);
    print (json_encode(array('originalEmail' => $headers)));
} else {
    error(404, 'retrieving error: invalid username/mailid combination');
}
</code>```

}

angularjs controller:

```<code>self.getOriginal = function (mail, domain) {

    var firstTo = Object.keys(mail.to)[0];
    $http.get(backend_url, {params:{username: firstTo, original_email_id: mail.id, domain:domain}})
        .then(
            function successCallback(response) {
                self.originalEmail = response.data.originalEmail;
                $log.error(response); //To show response content.
            },
            function errorCallback(response) {
                $log.error(response, this);
                self.error = {
                    title: "HTTP_ERROR",
                    desc: "There is a problem with geting the original email. (HTTP_ERROR).",
                    detail: response
                };
            });
}
</code>```

this code works fine the most of the emails but when I try to Signup for Blockchain.com for example, getting original fails and I get this in chrome inspector:

```<code>{data: "", status: 200, config: {…}, statusText: "OK", headers: ƒ}config: {method: "GET", transformRequest: Array(1), transformResponse: Array(1), jsonpCallbackParam: "callback", paramSerializer: ƒ, …}data: ""headers: ƒ (d)status: 200statusText: "OK"__proto__: Object
</code>```

I downloded the content of the headers:

```<code> Return-path: <bounces+1772275-ae77-jeff=mailinbox.co@sendgrid.net>
Envelope-to: jeff@mailinbox.co
Delivery-date: Mon, 25 Sep 2017 18:25:32 +0200
Received: from o1.mail.blockchain.info ([198.21.6.174])
    by  with esmtps (TLSv1.2:ECDHE-RSA-AES128-GCM-SHA256:128)
    (Exim 4.89)
    (envelope-from <bounces+1772275-ae77-jeff=mailinbox.co@sendgrid.net>)
    id 1dwWCK-0008U5-Eu
    for jeff@mailinbox.co; Mon, 25 Sep 2017 18:25:32 +0200
DKIM-Signature: v=1; a=rsa-sha1; c=relaxed/relaxed;
    d=blockchain.info;
    h=content-transfer-encoding:content-type:from:mime-version:subject:to;
    s=m1; bh=A+wGBBGT0nPZi611WDiY8hyoJiA=; b=BvDSkuUQpbkbwvS176xTK19
    evW+h0n9QLlMlqNQRy8pEZXRaMtPm3o9szysUlrzFB8+ucaSyCQqhdjobKRA5LvP
    L5BS9814iqFpV+Kzrb8gMc3aSl/aycBTqBxQYeuTtsWWT1I6VMHLPquVqOuS4ZjG
    n1ia1O5mFsFtvNJpligI=
Received: by filter0934p1mdw1.sendgrid.net with SMTP id filter0934p1mdw1-27911-59C92DF5-1D
        2017-09-25 16:25:25.327461844 +0000 UTC
Received: from MTc3MjI3NQ (236.212.190.35.bc.googleusercontent.com [35.190.212.236])
    by ismtpd0001p1lon1.sendgrid.net (SG) with HTTP id 8U6IPbOfSEO07nzJUAkd1Q
    for <jeff@mailinbox.co>; Mon, 25 Sep 2017 16:25:25.209 +0000 (UTC)
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset=UTF-8
Date: Mon, 25 Sep 2017 16:25:25 +0000 (UTC)
From: "Blockchain" <no-reply@blockchain.info>
Mime-Version: 1.0
Subject: Welcome To My Wallet
To: jeff@mailinbox.co
Message-ID: <8U6IPbOfSEO07nzJUAkd1Q@ismtpd0001p1lon1.sendgrid.net>
X-SG-EID: rp6B7bPLkmILpCROEdQ6zxTTWV8/jMJblylXDv403K5XiCqxnco7VnA/3IqSz7BIqYEji4cv4ijjl3
 obxT0otJleksoYG645Y4eGShknp4SWqOkaFs63Ycjvax2oooiiWDaX5/JGhenxjRDma8xla9eBS4Fg
 kwS3NpJQZSN3iSig19KAiQSGMIT4FhORo8kD0hDQAJhfzUT/JT1pcnAx8mMsZ9/JyELfQe9pet+yLB
 8=
X-Spam-Score: 10
X-Spam-Bar: +
X-Spam-Report: Spam detection software, running on the system "", has
 identified this incoming email as possible spam.  The original message
 has been attached to this so you can view it (if it isn't spam) or label
 similar future email.  If you have any questions, see
 the administrator of that system for details.

 Content preview:  Verify Your Email Thank you for creating a Blockchain wallet.
    Verify your email below to complete your setup. Yes, This Is My Email Your
    Wallet ID: 8a622806-96bd-44f3-a267-77f5af68a3dd Use your unique Wallet ID
    to log into your Blockchain wallet. Copyright © 2017 Blockchain Luxembourg
    S.A. All rights reserved. Click here to Unsubscribe [...]

 Content analysis details:   (1.0 points, 5.0 required)

  pts rule name              description
 ---- ---------------------- --------------------------------------------------
  0.0 URIBL_BLOCKED          ADMINISTRATOR NOTICE: The query to URIBL was blocked.
                             See
                             http://wiki.apache.org/spamassassin/DnsBlocklists#dnsbl-block
                              for more information.
                             [URIs: blockchain.info]
  0.0 HTML_MESSAGE           BODY: HTML included in message
  1.1 MIME_HTML_ONLY         BODY: Message only has text/html MIME parts
 -0.1 DKIM_VALID_AU          Message has a valid DKIM or DK signature from author's
                             domain
  0.1 DKIM_SIGNED            Message has a DKIM or DK signature, not necessarily valid
 -0.1 DKIM_VALID             Message has at least one valid DKIM or DK signature
X-redirected: yes
</code>```

because I'm getting the content in the download function which uses the print directly without using json_encode (to send a json format ), so I believe that the problem is with the json format, but I don't what is the problem exactly, so if you have any idea thanks for sharing.

答:
The problem was with some special characters that may appear in the message content(the $headers), so I have to clean them, for that I created this function:

```<code>function _clean_origin($origin){
  $origin = preg_replace('/[^\da-z \n\rA-Z.,!<>()+-?]/'," ",$origin);
  return $origin;
</code>```

}

which I call in the get_original_email to clean $headers, so I can get the headers normally.

Body:
I'm working in a website of temporary emails, one of the functionality that I have to implement is getting the origin of the email(getting email's headers), so I implemented this code to do that:

backend(php):

function get_original_email($mailid, $address) {
global $mailbox;

if (_load_one_email($mailid, $address) !== null) {
    header('Content-type: application/json');
    $headers = imap_fetchheader($mailbox->getImapStream(), $mailid, FT_UID);
    //$body = imap_body($mailbox->getImapStream(), $mailid, FT_UID);
    print (json_encode(array('originalEmail' => $headers)));
} else {
    error(404, 'retrieving error: invalid username/mailid combination');
}

}

angularjs controller:

self.getOriginal = function (mail, domain) {

    var firstTo = Object.keys(mail.to)[0];
    $http.get(backend_url, {params:{username: firstTo, original_email_id: mail.id, domain:domain}})
        .then(
            function successCallback(response) {
                self.originalEmail = response.data.originalEmail;
                $log.error(response); //To show response content.
            },
            function errorCallback(response) {
                $log.error(response, this);
                self.error = {
                    title: "HTTP_ERROR",
                    desc: "There is a problem with geting the original email. (HTTP_ERROR).",
                    detail: response
                };
            });
}

this code works fine the most of the emails but when I try to Signup for Blockchain.com for example, getting original fails and I get this in chrome inspector:

{data: "", status: 200, config: {…}, statusText: "OK", headers: ƒ}config: {method: "GET", transformRequest: Array(1), transformResponse: Array(1), jsonpCallbackParam: "callback", paramSerializer: ƒ, …}data: ""headers: ƒ (d)status: 200statusText: "OK"__proto__: Object

I downloded the content of the headers:

 Return-path: <bounces+1772275-ae77-jeff=mailinbox.co@sendgrid.net>
Envelope-to: jeff@mailinbox.co
Delivery-date: Mon, 25 Sep 2017 18:25:32 +0200
Received: from o1.mail.blockchain.info ([198.21.6.174])
    by  with esmtps (TLSv1.2:ECDHE-RSA-AES128-GCM-SHA256:128)
    (Exim 4.89)
    (envelope-from <bounces+1772275-ae77-jeff=mailinbox.co@sendgrid.net>)
    id 1dwWCK-0008U5-Eu
    for jeff@mailinbox.co; Mon, 25 Sep 2017 18:25:32 +0200
DKIM-Signature: v=1; a=rsa-sha1; c=relaxed/relaxed;
    d=blockchain.info;
    h=content-transfer-encoding:content-type:from:mime-version:subject:to;
    s=m1; bh=A+wGBBGT0nPZi611WDiY8hyoJiA=; b=BvDSkuUQpbkbwvS176xTK19
    evW+h0n9QLlMlqNQRy8pEZXRaMtPm3o9szysUlrzFB8+ucaSyCQqhdjobKRA5LvP
    L5BS9814iqFpV+Kzrb8gMc3aSl/aycBTqBxQYeuTtsWWT1I6VMHLPquVqOuS4ZjG
    n1ia1O5mFsFtvNJpligI=
Received: by filter0934p1mdw1.sendgrid.net with SMTP id filter0934p1mdw1-27911-59C92DF5-1D
        2017-09-25 16:25:25.327461844 +0000 UTC
Received: from MTc3MjI3NQ (236.212.190.35.bc.googleusercontent.com [35.190.212.236])
    by ismtpd0001p1lon1.sendgrid.net (SG) with HTTP id 8U6IPbOfSEO07nzJUAkd1Q
    for <jeff@mailinbox.co>; Mon, 25 Sep 2017 16:25:25.209 +0000 (UTC)
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset=UTF-8
Date: Mon, 25 Sep 2017 16:25:25 +0000 (UTC)
From: "Blockchain" <no-reply@blockchain.info>
Mime-Version: 1.0
Subject: Welcome To My Wallet
To: jeff@mailinbox.co
Message-ID: <8U6IPbOfSEO07nzJUAkd1Q@ismtpd0001p1lon1.sendgrid.net>
X-SG-EID: rp6B7bPLkmILpCROEdQ6zxTTWV8/jMJblylXDv403K5XiCqxnco7VnA/3IqSz7BIqYEji4cv4ijjl3
 obxT0otJleksoYG645Y4eGShknp4SWqOkaFs63Ycjvax2oooiiWDaX5/JGhenxjRDma8xla9eBS4Fg
 kwS3NpJQZSN3iSig19KAiQSGMIT4FhORo8kD0hDQAJhfzUT/JT1pcnAx8mMsZ9/JyELfQe9pet+yLB
 8=
X-Spam-Score: 10
X-Spam-Bar: +
X-Spam-Report: Spam detection software, running on the system "", has
 identified this incoming email as possible spam.  The original message
 has been attached to this so you can view it (if it isn't spam) or label
 similar future email.  If you have any questions, see
 the administrator of that system for details.

 Content preview:  Verify Your Email Thank you for creating a Blockchain wallet.
    Verify your email below to complete your setup. Yes, This Is My Email Your
    Wallet ID: 8a622806-96bd-44f3-a267-77f5af68a3dd Use your unique Wallet ID
    to log into your Blockchain wallet. Copyright © 2017 Blockchain Luxembourg
    S.A. All rights reserved. Click here to Unsubscribe [...]

 Content analysis details:   (1.0 points, 5.0 required)

  pts rule name              description
 ---- ---------------------- --------------------------------------------------
  0.0 URIBL_BLOCKED          ADMINISTRATOR NOTICE: The query to URIBL was blocked.
                             See
                             http://wiki.apache.org/spamassassin/DnsBlocklists#dnsbl-block
                              for more information.
                             [URIs: blockchain.info]
  0.0 HTML_MESSAGE           BODY: HTML included in message
  1.1 MIME_HTML_ONLY         BODY: Message only has text/html MIME parts
 -0.1 DKIM_VALID_AU          Message has a valid DKIM or DK signature from author's
                             domain
  0.1 DKIM_SIGNED            Message has a DKIM or DK signature, not necessarily valid
 -0.1 DKIM_VALID             Message has at least one valid DKIM or DK signature
X-redirected: yes

because I'm getting the content in the download function which uses the print directly without using json_encode (to send a json format ), so I believe that the problem is with the json format, but I don't what is the problem exactly, so if you have any idea thanks for sharing.

Body:
The problem was with some special characters that may appear in the message content(the $headers), so I have to clean them, for that I created this function:

function _clean_origin($origin){
  $origin = preg_replace('/[^\da-z \n\rA-Z.,!<>()+-?]/'," ",$origin);
  return $origin;

}

which I call in the get_original_email to clean $headers, so I can get the headers normally.


问:
Merging list of two objects to create a third object on the basis of common attribute
I have two different csv files having data on two different entities and I have to merge two different csv files to create one on the basis of sql join type equijoin and left join.

so I have created first entity as class name Customer having attributes:

```<code>int CustomerId ;
String CustomerName;
int OrderId;
</code>```

And List of object of this class like:

```<code>Customer c1 = new Customer(CustomerId, CustomerName, OrderId);
1 million objects..

List<Customer> cust = new ArrayList<>();
cust.add(c1);
cust.add(c2);
so on to make list of 1 million object.
</code>```

Similarly, I have created class of second entity Order having attributes:

```<code>int orderId;
String orderName;
Date orderdate;

Order o1 = new Order(orderId, orderName, orderdate);
so on 1 million object
List<Oder> order = new ArrayList<>();
</code>```

Now I need to merge both the object on the basis of orderId and generate third object having result class having all the attributes from both the classes described above.

Please suggest me solution using java stream 8 to map both the streams of list to create inner join and left join type example in the third new result class.

答:
Aside from the getters, your Customer class should have the following method:

```<code>public boolean orderMatch(Order order) {
    //fixed the attribute name so it would be in camelCase
    return orderId == order.getId();
}
</code>```

Of course, this implies that Order has a getId() getter method to get its id attribute.

Finally, you'll need a CustomerExtended class.

```<code>class CustomerExtended {
    int customerId ;
    String customerName;
    Order customerOrder;

    public CustomerExtended(Customer customer, Order order) {
        customerId = customer.getId();
        customerName = customer.getName();
        customerOrder = order;
    }
}
</code>```

Now, you can create a Function which would search for the corresponding Order and append it to a Customer:

```<code>Function<Customer,CustomerExtended> extendCustomer = (c) ->{
    //I used the more descriptive name orderList instead of o1.
    Optional<Order> order = orderList.stream()
                                     .filter(c::orderMatch)
                                     .findFirst();
    if(order.isPresent()) {
        return new CustomerExtended(c,order.get());
    }
    return null;
};
</code>```

And then you can apply it to the Customer list through a map.

```<code>List<CustomerExtended> newCustomerList = customerList.stream()
                                                     .map(c -> extendCustomer.apply(c))
                                                     .collect(Collectors.toList());
</code>```

EDIT: A few last notes

There should be some check that the ID numbers are not duplicate either when adding the objects to the lists, or when the lists are populated.

For semantic purposes, The Customer object as it is should be renamed CustomerOrder or be separated into an object only for customer info and an object which would store the relation between customer and order.

The case where an order is not found should be better handled and throw an exception.

Body:
I have two different csv files having data on two different entities and I have to merge two different csv files to create one on the basis of sql join type equijoin and left join.

so I have created first entity as class name Customer having attributes:

int CustomerId ;
String CustomerName;
int OrderId;

And List of object of this class like:

Customer c1 = new Customer(CustomerId, CustomerName, OrderId);
1 million objects..

List<Customer> cust = new ArrayList<>();
cust.add(c1);
cust.add(c2);
so on to make list of 1 million object.

Similarly, I have created class of second entity Order having attributes:

int orderId;
String orderName;
Date orderdate;

Order o1 = new Order(orderId, orderName, orderdate);
so on 1 million object
List<Oder> order = new ArrayList<>();

Now I need to merge both the object on the basis of orderId and generate third object having result class having all the attributes from both the classes described above.

Please suggest me solution using java stream 8 to map both the streams of list to create inner join and left join type example in the third new result class.

Body:
Aside from the getters, your Customer class should have the following method:

public boolean orderMatch(Order order) {
    //fixed the attribute name so it would be in camelCase
    return orderId == order.getId();
}

Of course, this implies that Order has a getId() getter method to get its id attribute.

Finally, you'll need a CustomerExtended class.

class CustomerExtended {
    int customerId ;
    String customerName;
    Order customerOrder;

    public CustomerExtended(Customer customer, Order order) {
        customerId = customer.getId();
        customerName = customer.getName();
        customerOrder = order;
    }
}

Now, you can create a Function which would search for the corresponding Order and append it to a Customer:

Function<Customer,CustomerExtended> extendCustomer = (c) ->{
    //I used the more descriptive name orderList instead of o1.
    Optional<Order> order = orderList.stream()
                                     .filter(c::orderMatch)
                                     .findFirst();
    if(order.isPresent()) {
        return new CustomerExtended(c,order.get());
    }
    return null;
};

And then you can apply it to the Customer list through a map.

List<CustomerExtended> newCustomerList = customerList.stream()
                                                     .map(c -> extendCustomer.apply(c))
                                                     .collect(Collectors.toList());

EDIT: A few last notes

There should be some check that the ID numbers are not duplicate either when adding the objects to the lists, or when the lists are populated.

For semantic purposes, The Customer object as it is should be renamed CustomerOrder or be separated into an object only for customer info and an object which would store the relation between customer and order.

The case where an order is not found should be better handled and throw an exception.


问:
C++ variable declation syntax
I recently came across this construct:
    int(m);
which seems to be equivalent to:
    int m;

Oddly, I have never seen this particular idiom before.  Can someone point me to a reference where I can read the spec on this, or just explain directly?  Does this also work in straight C?

Thanks,
ConfusedDeveloper

答:
It's also used to cast.  Like,</p>

```<code>double m= 10.0;
int n= int(m);
</code>```

ContentLicense: CC BY-SA 2.5

Title: C++ variable declation syntax

Body:
It's also used to cast.  Like,

double m= 10.0;
int n= int(m);


问:
sql query with two joins and a simple logic
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

```<code> | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P
</code>```

User Table

```<code>| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx
</code>```

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')
</code>```

答:
Change your query as below. If you only want data from first table then no need join query only use inner query

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u WHERE u.ID not in
(select f.friend_id from friends_list f where f.status IN ('P', 'B')) order by u.ID;
</code>```

Fiddle

EDIT

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status NOT IN ('P', 'B') OR f.status IS NULL ORDER BY u.ID
</code>```

Body:
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

 | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P

User Table

| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')

Body:
Change your query as below. If you only want data from first table then no need join query only use inner query

select DISTINCT u.ID, u.user_nicename from wp_users u WHERE u.ID not in
(select f.friend_id from friends_list f where f.status IN ('P', 'B')) order by u.ID;

Fiddle

EDIT

select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status NOT IN ('P', 'B') OR f.status IS NULL ORDER BY u.ID


问:
React changes not visible in DOM
I have a good history playing with react. But today I faced a very strange issue.

I have a hamburger which receives a list of values and the one of the values is selected which I send from the parent through this.refs.child1.setValues(). this setValues function calls setState and that one value is selected through className parameter in react.

So in the first step I select first value among 20 values.

the react tab shows this about the first li element:

```<code>className="{something} +class1"
</code>```

rest all elements have:

```<code>className="{something}"
</code>```

which is fine. ('class1' is the class which is added dynamically on setstate) and the dom shows first value selected and the rest unselected.

now problem is in the second step as I select another value say 3rd one, so first value should get deselected and 3rd should be selected and the expected react values for 3rd should be

className="{something} + class1" and for the rest its showing className="{something}"

which is working fine in the react tab BUT in the elements tab both the li elements are getting selected as they both have class1 but class1 should be only with the 3rd element not with the first one (which was previously selected)

答:
Since React works by using the Virtual DOM, it only makes changes in the DOM to elements it detects a change to. So, since you're never actually removing a class from the first element, it never does a rerender of it, it only rerenders the third one because that's the only one you actually changed.

You need to do something like this:

```<code>removeClass() {
    let allLinks = document.querySelectorAll('.something');
    allLinks.map((link) => link.classList.remove('class1'));

    //and here just call the function to add the class to the right
    //element.
}
</code>```

Title: React changes not visible in DOM

Body:
I have a good history playing with react. But today I faced a very strange issue.

I have a hamburger which receives a list of values and the one of the values is selected which I send from the parent through this.refs.child1.setValues(). this setValues function calls setState and that one value is selected through className parameter in react.

So in the first step I select first value among 20 values.

the react tab shows this about the first li element:

className="{something} +class1"

rest all elements have:

className="{something}"

which is fine. ('class1' is the class which is added dynamically on setstate) and the dom shows first value selected and the rest unselected.

now problem is in the second step as I select another value say 3rd one, so first value should get deselected and 3rd should be selected and the expected react values for 3rd should be

className="{something} + class1" and for the rest its showing className="{something}"

which is working fine in the react tab BUT in the elements tab both the li elements are getting selected as they both have class1 but class1 should be only with the 3rd element not with the first one (which was previously selected)

Body:
Since React works by using the Virtual DOM, it only makes changes in the DOM to elements it detects a change to. So, since you're never actually removing a class from the first element, it never does a rerender of it, it only rerenders the third one because that's the only one you actually changed.

You need to do something like this:

removeClass() {
    let allLinks = document.querySelectorAll('.something');
    allLinks.map((link) => link.classList.remove('class1'));

    //and here just call the function to add the class to the right
    //element.
}


问:
How to get a mysql output to a php variable?
Here I have two variables called $semresult, $examresult where i need to store the results of two respective queries. And then I need to do a calculation with them. The code I tried so far is

```<code>  $output = '';
  $connect = mysqli_connect("localhost", "root", "", "crudnew");

        $semfee = "select sum(amount) from semesterfees";
        $semresult = mysqli_query($connect,$semfee);

        $examfee = "select sum(amount) from examfees";
        $examresult = mysqli_query($connect,$examfee);

        $income = ((int)$semresult + (int)$examresult);
</code>```

But whenever I run the above code $semresult, $examresult gets the error "object of class mysqli_result could not be converted to int". Please help :')

答:
You are passing invalid query. Please check once try this</p>

```<code>    $semfee = "select sum(amount) from semesterfees";
    $semresult = mysqli_query($connect,$semfee );

    $examfee = "select sum(amount) from examfees";
    $examresult = mysqli_query($connect,$examfee);

    $income = ((int)$semresult['amount'] + (int)$examresult['amount']);
</code>```

Body:
Here I have two variables called $semresult, $examresult where i need to store the results of two respective queries. And then I need to do a calculation with them. The code I tried so far is

  $output = '';
  $connect = mysqli_connect("localhost", "root", "", "crudnew");

        $semfee = "select sum(amount) from semesterfees";
        $semresult = mysqli_query($connect,$semfee);

        $examfee = "select sum(amount) from examfees";
        $examresult = mysqli_query($connect,$examfee);

        $income = ((int)$semresult + (int)$examresult);

But whenever I run the above code $semresult, $examresult gets the error "object of class mysqli_result could not be converted to int". Please help :')

Body:
You are passing invalid query. Please check once try this

    $semfee = "select sum(amount) from semesterfees";
    $semresult = mysqli_query($connect,$semfee );

    $examfee = "select sum(amount) from examfees";
    $examresult = mysqli_query($connect,$examfee);

    $income = ((int)$semresult['amount'] + (int)$examresult['amount']);


问:
Using grep on posixct vectors
I have multiple date-time columns and I need to verify which of them are in the timezone CEST

```<code>dat <- structure(c(1491199401.363, 1491201912.62, 1491205392.67, 1491205933.457, 1491206198.027, 1491206802.243), class = c("POSIXct", "POSIXt"), tzone = "")
dat
#[1] "2017-04-03 08:03:21 CEST" "2017-04-03 08:45:12 CEST" [3]
#"2017-04-03 09:43:12 CEST" "2017-04-03 09:52:13 CEST" [5] "2017-04-03
#09:56:38 CEST" "2017-04-03 10:06:42 CEST"

any(grep("CEST", dat))
#[1] FALSE
any(grep("CEST", "2017-04-03 08:03:21 CEST"))
#[1] TRUE
</code>```

I can get this method to work if I copy/paste the elements into the grep function, but not if I run it on the vector itself. Using as.character(dat) does not work either. How do I do this?

答:
We can extract the time zone with format and use %in% to get the

```<code>"CEST" %in% format(dat, format="%Z")
#[1] TRUE
</code>```

Or another option is to unclass after converting to POSIXlt and extract the zone

```<code>"CEST" %in% unclass(as.POSIXlt(dat))$zone
#[1] TRUE
</code>```

In the single element that the OP was grepping it is a character class while the dat is POSIXct class.  So, it will be able to find the substring using grep.  Even if, we convert the 'dat' to character, it will lose the attributes i.e.

```<code>as.character(dat)
#[1] "2017-04-03 08:03:21" "2017-04-03 08:45:12" "2017-04-03 09:43:12" "2017-04-03 09:52:13" "2017-04-03 09:56:38" "2017-04-03 10:06:42"
</code>```

and therefore grep will not be able to pick it

```<code>grepl("CEST", as.character(dat))
#[1] FALSE FALSE FALSE FALSE FALSE FALSE
</code>```

Title: Using grep on posixct vectors

Body:
I have multiple date-time columns and I need to verify which of them are in the timezone CEST

dat <- structure(c(1491199401.363, 1491201912.62, 1491205392.67, 1491205933.457, 1491206198.027, 1491206802.243), class = c("POSIXct", "POSIXt"), tzone = "")
dat
#[1] "2017-04-03 08:03:21 CEST" "2017-04-03 08:45:12 CEST" [3]
#"2017-04-03 09:43:12 CEST" "2017-04-03 09:52:13 CEST" [5] "2017-04-03
#09:56:38 CEST" "2017-04-03 10:06:42 CEST"

any(grep("CEST", dat))
#[1] FALSE
any(grep("CEST", "2017-04-03 08:03:21 CEST"))
#[1] TRUE

I can get this method to work if I copy/paste the elements into the grep function, but not if I run it on the vector itself. Using as.character(dat) does not work either. How do I do this?

Body:
We can extract the time zone with format and use %in% to get the

"CEST" %in% format(dat, format="%Z")
#[1] TRUE

Or another option is to unclass after converting to POSIXlt and extract the zone

"CEST" %in% unclass(as.POSIXlt(dat))$zone
#[1] TRUE

In the single element that the OP was grepping it is a character class while the dat is POSIXct class.  So, it will be able to find the substring using grep.  Even if, we convert the 'dat' to character, it will lose the attributes i.e.

as.character(dat)
#[1] "2017-04-03 08:03:21" "2017-04-03 08:45:12" "2017-04-03 09:43:12" "2017-04-03 09:52:13" "2017-04-03 09:56:38" "2017-04-03 10:06:42"

and therefore grep will not be able to pick it

grepl("CEST", as.character(dat))
#[1] FALSE FALSE FALSE FALSE FALSE FALSE


问:
QT Creator project file: how to check for android arm vs x86
In QT Creator .pro file done for an Android project I need to include different files based on target architecture (or compiler). In particular, for ARM and x86 architecture I need to include a different manifest.xml file, since I need to specify a different version code, as written in Multiple APK guidelines.

I need something like this:

```<code>android_armv7{
    DISTFILES += android/arm/AndroidManifest.xml
}
android_x86{
    DISTFILES += android/x86/AndroidManifest.xml
}
</code>```

android_armv7 and android_x86 do not exist.

Moreover, how to check the architecture/compiler in C++ code too?

答:
You can use: (tested with Qt 5.9.2)

```<code>equals(QT_ARCH, arm): DISTFILES += android/arm/AndroidManifest.xml
equals(QT_ARCH, i386): DISTFILES += android/x86/AndroidManifest.xml
</code>```

I'd had the same issue for setting library search paths.

Maybe this can help others when they find this question.

Body:
In QT Creator .pro file done for an Android project I need to include different files based on target architecture (or compiler). In particular, for ARM and x86 architecture I need to include a different manifest.xml file, since I need to specify a different version code, as written in Multiple APK guidelines.

I need something like this:

android_armv7{
    DISTFILES += android/arm/AndroidManifest.xml
}
android_x86{
    DISTFILES += android/x86/AndroidManifest.xml
}

android_armv7 and android_x86 do not exist.

Moreover, how to check the architecture/compiler in C++ code too?

Body:
You can use: (tested with Qt 5.9.2)

equals(QT_ARCH, arm): DISTFILES += android/arm/AndroidManifest.xml
equals(QT_ARCH, i386): DISTFILES += android/x86/AndroidManifest.xml

I'd had the same issue for setting library search paths.

Maybe this can help others when they find this question.


问:
Why does checking whether a file exists in hadoop cause a NullPointerException?
I'm trying to create or open a file to store some output in HDFS, but I'm getting a NullPointerException when I call the exists method in the second to last line of the code snippet below:

```<code>DistributedFileSystem dfs = new DistributedFileSystem();
Path path = new Path("/user/hadoop-user/bar.txt");
if (!dfs.exists(path)) dfs.createNewFile(path);
FSDataOutputStream dos = dfs.create(path);
</code>```

Here is the stack trace:

```<code>java.lang.NullPointerException
        at org.apache.hadoop.dfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:390)
        at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:667)
        at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:80)
        at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:65)
        at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:47)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:227)
        at org.apache.hadoop.mapred.TaskTracker$Child.main(TaskTracker.java:2209)
</code>```

What could the problem be?

答:
The default constructor DistributedFileSystem() does not perform initialization; you need to call dfs.initialize() explicitly.

The reason you are getting a null pointer exception is that the DistributedFileSystem internally uses an instance of DFSClient. Since you did not call initialize(), the instance of DFSClient is null. getFileStatus() calls dfsClient.getFileInfo(getPathName(f) - which causes  NullPointerException, since dfsClient is null.

See https://trac.declarativity.net/browser/src/hdfs/org/apache/hadoop/dfs/DistributedFileSystem.java?rev=3593

Body:
I'm trying to create or open a file to store some output in HDFS, but I'm getting a NullPointerException when I call the exists method in the second to last line of the code snippet below:

DistributedFileSystem dfs = new DistributedFileSystem();
Path path = new Path("/user/hadoop-user/bar.txt");
if (!dfs.exists(path)) dfs.createNewFile(path);
FSDataOutputStream dos = dfs.create(path);

Here is the stack trace:

java.lang.NullPointerException
        at org.apache.hadoop.dfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:390)
        at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:667)
        at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:80)
        at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:65)
        at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:47)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:227)
        at org.apache.hadoop.mapred.TaskTracker$Child.main(TaskTracker.java:2209)

What could the problem be?


问:
REST API Two seperate resources to create a user?
Currently building a REST API and one of the functions of it will be to create users. There are two ways my application will create users:

Register, users add themselves with the usual data: email, password, username, date of birth.

Manual creation, admin adds a user with usual data AND any extra data as required.

My setup is a users table, users_metadata table and users_permissions table, as well as a few others. The email and password are stored in the users table, the username and date of birth in the users_metadata table. When manually creating a user other metadata and the user's permissions, as well as data in the other tables, can be changed.

Would it be better to have two different resources to handle creating a user?

答:
Would it be better to have two different resources to handle creating a user?

I wouldn't create two different resources that both represent the user and both model its creation process. Since a user is a user, in my opinion they should be created trough the same resource.

Manual creation, admin adds a user with usual data AND any extra data as required.

When manually creating a user other metadata and the user's permissions, as well as data in the other tables, can be changed.

If it makes sense, you could model this extra data as a separate (sub)resource. The same goes for permissions. This sub resource can then have its own URL (for instance /users/{id}/meta and /users/{id}/permissions) to which the client issues separate POST requests, or it can be nested in the data structure that is sent to the API, like so:

```<code>{
    "name": "John",
    "email-address": "john@doe.com",
    "permissions": {
        "read": true,
        "write": false
    },
    "meta-data": {
        "date-of-birth": "2000-01-01"
    }
}
</code>```

The approach with separate sub resources at their own URLs makes access control and validation a bit easier. On the other hand, it puts a bigger burden on the client. It can also put you in the position where an admin creates a user, the basic information is saved, but there is an error saving permissions; depending on your use case you may or may not need to somehow handle that automatically.

The approach where the sub resources are nested in the data structure makes the logic to handle the POST request a bit more complex, but it does make the client side of things easier and gives you the option to make the whole action atomic by wrapping it in a transaction and rolling back if anything goes wrong.

Note: These two approaches are not mutually exclusive; you can do both if you want.

Which of these approaches is best will depend on how many sub resources there are, how complex they are and how complex the access control to the sub resources is; the more sub resources there are and/or the more complex access control is, the more likely I would be to setup different URLs for the sub resources.

In this specific case, I would net the sub resources in the data structure and have the clients POST all the data at once.

Body:
Would it be better to have two different resources to handle creating a user?

I wouldn't create two different resources that both represent the user and both model its creation process. Since a user is a user, in my opinion they should be created trough the same resource.

Manual creation, admin adds a user with usual data AND any extra data as required.

When manually creating a user other metadata and the user's permissions, as well as data in the other tables, can be changed.

If it makes sense, you could model this extra data as a separate (sub)resource. The same goes for permissions. This sub resource can then have its own URL (for instance /users/{id}/meta and /users/{id}/permissions) to which the client issues separate POST requests, or it can be nested in the data structure that is sent to the API, like so:

{
    "name": "John",
    "email-address": "john@doe.com",
    "permissions": {
        "read": true,
        "write": false
    },
    "meta-data": {
        "date-of-birth": "2000-01-01"
    }
}

The approach with separate sub resources at their own URLs makes access control and validation a bit easier. On the other hand, it puts a bigger burden on the client. It can also put you in the position where an admin creates a user, the basic information is saved, but there is an error saving permissions; depending on your use case you may or may not need to somehow handle that automatically.

The approach where the sub resources are nested in the data structure makes the logic to handle the POST request a bit more complex, but it does make the client side of things easier and gives you the option to make the whole action atomic by wrapping it in a transaction and rolling back if anything goes wrong.

Note: These two approaches are not mutually exclusive; you can do both if you want.

Which of these approaches is best will depend on how many sub resources there are, how complex they are and how complex the access control to the sub resources is; the more sub resources there are and/or the more complex access control is, the more likely I would be to setup different URLs for the sub resources.

In this specific case, I would net the sub resources in the data structure and have the clients POST all the data at once.


问:
Django ReportLab PDF generation with SimpleDocTemplate
I am using SimpleDocTemplate to genetare and download pdf. My current code generating the PDF corectly but the pdf getting open in another tab of chrome browser with empty page and Its asking for 'Open' or 'Save' in FireFox browser. Where shoud i change my code to directly download the PDF without opening it in another Tab of Chrome. Thanks in advance.
This is the code..

```<code> def GenerateTc(request):

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename = "TC.pdf"'

    doc = SimpleDocTemplate(response,topMargin=20)
    doc.pagesize = landscape(A4)

    elements = []

    data= [

                 ['---OFFICE USE ONLY---'],
                 ['Date :','','ClassTeacher Signature: :',''],
                 ['Principal Signature :','','Accountant Signature :',''],
                 ['Student Name :'+' '+''],
                 ['Remark :','','',''],
          ]
    style =TableStyle([

                            ('SPAN',(2,15),(3,15)),
                            ('SPAN',(0,16),(1,16)),
                            ('SPAN',(2,16),(3,16)),
                            ('SPAN',(0,17),(3,17)),
                            ('SPAN',(0,18),(3,18)),
                    ])
    #Configure style and word wrap
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = 'CJK'
    ps = ParagraphStyle('title', fontSize=15, alignment=TA_CENTER,)
    data2 = [[Paragraph(cell, s) for cell in row] for row in data]
    t=Table(data2)
    t.setStyle(style)
    getSampleStyleSheet()
    elements.append(Paragraph("TRANSFER/DISCONTINUATION ACKNOWLEDGEMENT",ps))
    elements.append(Spacer(1,0.4*inch))
    elements.append(t)
    doc.build(elements)

    return response
</code>```

This is my URL:

```<code>url(r'^generate_tc/$',views.GenerateTc, name='generate_tc'),
</code>```

This is my HTML template form to call that function in view:

```<code><form action="{% url 'transfer_certificate:generate_tc' %}" id="form_sample_1" class="form-horizontal"
                  method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <input class="form-control" id="studentid" name="studentid" type="hidden" value="">
                <table class="table table-striped table-bordered table-hover table-checkable order-column"
                       id="sample_1">
                    <thead>
                    <tr>
                        <th style="display:none">student ID</th>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Class</th>
                        <th>Section</th>

                        <th>Grant/Generate TC</th>
                    </tr>
                    </thead>
                    <tbody> {% for tc_detail in TCDetailsList %}
                        <tr style="cursor: pointer;">

                            <td style="display:none">{{ tc_detail.student.id }}</td>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ tc_detail.student.first_name }}  {{ tc_detail.student.father_name }}
                                  {{ tc_detail.student.last_name }}</td>
                            <td>{{ tc_detail.student.academic_class_section.class_name }}</td>
                            <td>{{ tc_detail.student.academic_class_section.section_name }}</td>
                            <td><input type='submit' class="buttongenerate btn green btn-block" value='Generate TC'></td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </form>
</code>```

Thanks You.

答:
The function GenerateTc works as expected (I have tested it). When you submit form, page reloads and my guess is that this triggers opening of a new tab (original tab with reloaded template and a new tab for PDF response). I suggest you change overall mechanism of this PDF generation, since all you are submitting is studentid.

Add argument student_id to GenerateTc function

```<code>def GenerateTc(request, student_id):
    ... your code ...
    return response
</code>```

Change url to

```<code>url(r'^generate_tc/(?P<student_id>\w+)/$', views.GenerateTc, name='generate_tc')
</code>```

Finally, remove form and add a link in the template:

```<code><a href="{% url 'transfer_certificate:generate_tc' tc_detail.student.id %}">Generate TC</a>
</code>```

This should work.

Body:
I am using SimpleDocTemplate to genetare and download pdf. My current code generating the PDF corectly but the pdf getting open in another tab of chrome browser with empty page and Its asking for 'Open' or 'Save' in FireFox browser. Where shoud i change my code to directly download the PDF without opening it in another Tab of Chrome. Thanks in advance.
This is the code..

 def GenerateTc(request):

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename = "TC.pdf"'

    doc = SimpleDocTemplate(response,topMargin=20)
    doc.pagesize = landscape(A4)

    elements = []

    data= [

                 ['---OFFICE USE ONLY---'],
                 ['Date :','','ClassTeacher Signature: :',''],
                 ['Principal Signature :','','Accountant Signature :',''],
                 ['Student Name :'+' '+''],
                 ['Remark :','','',''],
          ]
    style =TableStyle([

                            ('SPAN',(2,15),(3,15)),
                            ('SPAN',(0,16),(1,16)),
                            ('SPAN',(2,16),(3,16)),
                            ('SPAN',(0,17),(3,17)),
                            ('SPAN',(0,18),(3,18)),
                    ])
    #Configure style and word wrap
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = 'CJK'
    ps = ParagraphStyle('title', fontSize=15, alignment=TA_CENTER,)
    data2 = [[Paragraph(cell, s) for cell in row] for row in data]
    t=Table(data2)
    t.setStyle(style)
    getSampleStyleSheet()
    elements.append(Paragraph("TRANSFER/DISCONTINUATION ACKNOWLEDGEMENT",ps))
    elements.append(Spacer(1,0.4*inch))
    elements.append(t)
    doc.build(elements)

    return response

This is my URL:

url(r'^generate_tc/$',views.GenerateTc, name='generate_tc'),

This is my HTML template form to call that function in view:

<form action="{% url 'transfer_certificate:generate_tc' %}" id="form_sample_1" class="form-horizontal"
                  method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <input class="form-control" id="studentid" name="studentid" type="hidden" value="">

                        student ID
                        Id
                        Name
                        Class
                        Section

                        Grant/Generate TC

 {% for tc_detail in TCDetailsList %}

                            {{ tc_detail.student.id }}
                            {{ forloop.counter }}
                            {{ tc_detail.student.first_name }}  {{ tc_detail.student.father_name }}
                                  {{ tc_detail.student.last_name }}
                            {{ tc_detail.student.academic_class_section.class_name }}
                            {{ tc_detail.student.academic_class_section.section_name }}
                            <input type='submit' class="buttongenerate btn green btn-block" value='Generate TC'>

                    {% endfor %}

            </form>

Thanks You.

Body:
The function GenerateTc works as expected (I have tested it). When you submit form, page reloads and my guess is that this triggers opening of a new tab (original tab with reloaded template and a new tab for PDF response). I suggest you change overall mechanism of this PDF generation, since all you are submitting is studentid.

Add argument student_id to GenerateTc function

def GenerateTc(request, student_id):
    ... your code ...
    return response

Change url to

url(r'^generate_tc/(?P<student_id>\w+)/$', views.GenerateTc, name='generate_tc')

Finally, remove form and add a link in the template:

<a href="{% url 'transfer_certificate:generate_tc' tc_detail.student.id %}">Generate TC</a>

This should work.


问:
Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
I am trying to use the following matrices and perform a dot product as shown in the code. I checked the size of the matrices and all are (3, 1) but it is throwing me error for the last two dot products.</p>

```<code>coordinate1 = [-7.173, -2.314, 2.811]
coordinate2 = [-5.204, -3.598, 3.323]
coordinate3 = [-3.922, -3.881, 4.044]
coordinate4 = [-2.734, -3.794, 3.085]

import numpy as np
from numpy import matrix
coordinate1i=matrix(coordinate1)
coordinate2i=matrix(coordinate2)
coordinate3i=matrix(coordinate3)
coordinate4i=matrix(coordinate4)

b0 = coordinate1i - coordinate2i
b1 = coordinate3i - coordinate2i
b2 = coordinate4i - coordinate3i

n1 = np.cross(b0, b1)
n2 = np.cross(b2, b1)

n12cross = np.cross(n1,n2)
x1= np.cross(n1,b1)/np.linalg.norm(b1)
print np.shape(x1)
print np.shape(n2)
np.asarray(x1)
np.asarray(n2)

y = np.dot(x1,n2)
x = np.dot(n1,n2)

return np.degrees(np.arctan2(y, x))
</code>```

答:
The column of the first matrix and the row of the second matrix should be equal and the order should be like this only

```<code>column of first matrix = row of second matrix
</code>```

and do not follow the below step

```<code>row of first matrix  = column of second matrix
</code>```

it will throw an error

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use the following matrices and perform a dot product as shown in the code. I checked the size of the matrices and all are (3, 1) but it is throwing me error for the last two dot products.

coordinate1 = [-7.173, -2.314, 2.811]
coordinate2 = [-5.204, -3.598, 3.323]
coordinate3 = [-3.922, -3.881, 4.044]
coordinate4 = [-2.734, -3.794, 3.085]

import numpy as np
from numpy import matrix
coordinate1i=matrix(coordinate1)
coordinate2i=matrix(coordinate2)
coordinate3i=matrix(coordinate3)
coordinate4i=matrix(coordinate4)

b0 = coordinate1i - coordinate2i
b1 = coordinate3i - coordinate2i
b2 = coordinate4i - coordinate3i

n1 = np.cross(b0, b1)
n2 = np.cross(b2, b1)

n12cross = np.cross(n1,n2)
x1= np.cross(n1,b1)/np.linalg.norm(b1)
print np.shape(x1)
print np.shape(n2)
np.asarray(x1)
np.asarray(n2)

y = np.dot(x1,n2)
x = np.dot(n1,n2)

return np.degrees(np.arctan2(y, x))

Body:
The column of the first matrix and the row of the second matrix should be equal and the order should be like this only

column of first matrix = row of second matrix

and do not follow the below step

row of first matrix  = column of second matrix

it will throw an error


问:
SSL_ERROR_PROTOCOL_VERSION_ALERT: Peer reports incompatible or unsupported protocol version
I have access API with CURL working PHP 5.5.12 fine.but if reduce php version below 5.5 so i got error (SSL_ERROR_PROTOCOL_VERSION_ALERT: Peer reports incompatible or unsupported protocol version.) so can you please suggest me. remove this error. and access API below php version 5.5.

答:
We have resolved issue. with out update php version change below curl code

```<code>curl_setopt($ch, CURLOPT_SSLVERSION, 3); // 1, 2 or 3
</code>```

We have already used. please add on curl both line.

```<code>curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
</code>```

– Vinod Kumar Pal

Body:
We have resolved issue. with out update php version change below curl code

curl_setopt($ch, CURLOPT_SSLVERSION, 3); // 1, 2 or 3

We have already used. please add on curl both line.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

– Vinod Kumar Pal


答:
Try something like this:

```<code>select t.start, t.end, t.ticketid,
       CASE WHEN EXTRACT(HOUR from t.validityend::timestamp - t.validitybegin::timestamp + interval '30 second') = 0
       THEN EXTRACT(MINUTE from date_trunc('minute', t.validityend::timestamp - t.validitybegin::timestamp + interval '30 second')) ELSE
              CASE WHEN EXTRACT(HOUR from t.end - t.validitybegin::timestamp + interval '30 second')  = 0
              THEN EXTRACT(MINUTE from date_trunc('minute', t.end - t.validitybegin::timestamp + interval '30 second')) ELSE
                 CASE WHEN  EXTRACT(HOUR from t.validityend::timestamp - t.start + interval '30 second') = 0
                 THEN EXTRACT(MINUTE from date_trunc('minute', t.validityend::timestamp - t.start + interval '30 second')) ELSE 60 END
         END
       END as overlap
from
(
  select i.*, generate_series as start, generate_series + interval '1 hour' as end
  from intervals i
  cross join generate_series
        ( date_trunc('hour', i.validitybegin::timestamp)
        , date_trunc('hour',i.validityend::timestamp)
        , '1 hour'::interval)
) t
</code>```

demo

Result for sample data

```<code>start                   end                     ticketid    overlap
-------------------------------------------------------------------
2017-08-31 12:00:00     2017-08-31 13:00:00     ID1         38
2017-08-31 13:00:00     2017-08-31 14:00:00     ID1         9
2017-08-31 13:00:00     2017-08-31 14:00:00     ID2         51
2017-08-31 14:00:00     2017-08-31 15:00:00     ID2         60
2017-08-31 15:00:00     2017-08-31 16:00:00     ID2         60
2017-08-31 16:00:00     2017-08-31 17:00:00     ID2         47
2017-08-31 13:00:00     2017-08-31 14:00:00     ID3         51
2017-08-31 14:00:00     2017-08-31 15:00:00     ID3         9
</code>```

Title: SQL: Split time interval into intersects of one hour

Body:
I am new to SQL, where I am trying to split time intervals into multiple rows of one hour, together with an indicator of how many minutes the interval overlaps each hour.

My data:

    validitybegin    |     validityend     |     ticketid     |
---------------------+---------------------+------------------+
 2017-08-31 12:22:04 | 2017-08-31 13:08:56 |       ID1        |
 2017-08-31 13:09:02 | 2017-08-31 16:46:51 |       ID2        |
 2017-08-31 13:09:10 | 2017-08-31 14:09:10 |       ID3        |

What I would like:

       start         |        end          |   overlap   |     ticketid     |
---------------------+---------------------+-------------+------------------+
 2017-08-31 12:00:00 | 2017-08-31 13:00:00 |     38      |       ID1        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |      9      |       ID1        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |     51      |       ID2        |
 2017-08-31 14:00:00 | 2017-08-31 15:00:00 |     60      |       ID2        |
 2017-08-31 15:00:00 | 2017-08-31 16:00:00 |     60      |       ID2        |
 2017-08-31 16:00:00 | 2017-08-31 17:00:00 |     47      |       ID2        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |     51      |       ID3        |
 2017-08-31 14:00:00 | 2017-08-31 15:00:00 |      9      |       ID3        |

What would be the easiest/fastest way to do this?

Body:
Try something like this:

select t.start, t.end, t.ticketid,
       CASE WHEN EXTRACT(HOUR from t.validityend::timestamp - t.validitybegin::timestamp + interval '30 second') = 0
       THEN EXTRACT(MINUTE from date_trunc('minute', t.validityend::timestamp - t.validitybegin::timestamp + interval '30 second')) ELSE
              CASE WHEN EXTRACT(HOUR from t.end - t.validitybegin::timestamp + interval '30 second')  = 0
              THEN EXTRACT(MINUTE from date_trunc('minute', t.end - t.validitybegin::timestamp + interval '30 second')) ELSE
                 CASE WHEN  EXTRACT(HOUR from t.validityend::timestamp - t.start + interval '30 second') = 0
                 THEN EXTRACT(MINUTE from date_trunc('minute', t.validityend::timestamp - t.start + interval '30 second')) ELSE 60 END
         END
       END as overlap
from
(
  select i.*, generate_series as start, generate_series + interval '1 hour' as end
  from intervals i
  cross join generate_series
        ( date_trunc('hour', i.validitybegin::timestamp)
        , date_trunc('hour',i.validityend::timestamp)
        , '1 hour'::interval)
) t

demo

Result for sample data

start                   end                     ticketid    overlap
-------------------------------------------------------------------
2017-08-31 12:00:00     2017-08-31 13:00:00     ID1         38
2017-08-31 13:00:00     2017-08-31 14:00:00     ID1         9
2017-08-31 13:00:00     2017-08-31 14:00:00     ID2         51
2017-08-31 14:00:00     2017-08-31 15:00:00     ID2         60
2017-08-31 15:00:00     2017-08-31 16:00:00     ID2         60
2017-08-31 16:00:00     2017-08-31 17:00:00     ID2         47
2017-08-31 13:00:00     2017-08-31 14:00:00     ID3         51
2017-08-31 14:00:00     2017-08-31 15:00:00     ID3         9


问:
How to get and change drawable background color in custom view
I have a custom view which extends TextView and the background is a drawable,

```<code><CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/circile_background" />
</code>```

and want to change the background color in custom view

```<code>public class CustomView extends TextView {

    TypedArray typedArray;

    public CustomView (Context context) {
        super(context);
    }

    public CustomView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setColorLevel(int color) {
       // update color here
    }
}
</code>```

答:
check similar question here How to change colors of a Drawable in Android?</p>

```<code>public void setDangerLevel(int color) {
    Drawable drawable=this.getBackground().getCurrent();
    drawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
    }
</code>```

Body:
I have a custom view which extends TextView and the background is a drawable,

<CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/circile_background" />

and want to change the background color in custom view

public class CustomView extends TextView {

    TypedArray typedArray;

    public CustomView (Context context) {
        super(context);
    }

    public CustomView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setColorLevel(int color) {
       // update color here
    }
}

Body:
check similar question here How to change colors of a Drawable in Android?

public void setDangerLevel(int color) {
    Drawable drawable=this.getBackground().getCurrent();
    drawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
    }


问:
JAVA - File I/O cant get file to read
I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.

```<code>public int readInventory(Automobile[] inventory)
{
    final String FILENAME = "inventory.csv";
    int size = 0;

    Scanner input = new Scanner("inventory.csv");
    try
    {
        input = new Scanner(new File(FILENAME));
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Unable to open file " + FILENAME + ".");
    }
    // ...
    return size;
}
</code>```

Here is the output I'm getting with no syntax errors.

Unable to open file inventory.csv.
```

答:
considering it's in the same folder.

Same folder as what? inventory.csv was not present in the current working directory when you executed your program.

Title: JAVA - File I/O cant get file to read

Body:
I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.

public int readInventory(Automobile[] inventory)
{
    final String FILENAME = "inventory.csv";
    int size = 0;

    Scanner input = new Scanner("inventory.csv");
    try
    {
        input = new Scanner(new File(FILENAME));
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Unable to open file " + FILENAME + ".");
    }
    // ...
    return size;
}

Here is the output I'm getting with no syntax errors.

Unable to open file inventory.csv.


问:
Installing Cython/Statsmodels
I can not for the life of me figure out how to install the package statsmodels for Python 3. It feels like I've tried everything, but nothing is working.

Goal: import statsmodels in python

I start with:

```<code>pip install statsmodels
</code>```

Main error messages:

```<code>Failed bulding wheel for statsmodels.
Cython is required to compile statsmodels from a development branch.
Please install Cython or download a source release of statsmodels.
</code>```

So I try:

```<code>pip install cython
</code>```

Gives:

```<code>Requirement already satisfied: cython in c:users\XXX\appdata\roaming\python\python36\site-packages
</code>```

I installed cython by installing anaconda. I have tried almost all answers I could find by basic googling. But things just don't seem to be working.

Instead of listing the input\output of what I have tried I now only show the first steps, but let me know if you want to see the output of any commands.

How do I continue from here? Any help is appreciated, I've been trying to fix this for several days now and I'm only getting frustrated.

Right now I'm trying:

```<code>easy_install cython
</code>```

This seemed to work, but afterwards pip install statsmodels didn't work.

```<code>Command ... failed with error code 1.
</code>```

I tried:

```<code>git clone https://github.com/statsmodels/statsmodels
cd statsmodels
pip install .
</code>```

And failed with a bunch of errors.

答:
To install statsmodels under anaconda, use

```<code>conda install statsmodels
</code>```

The package is available in the repository of anacondata in version 0.8.0 which is the latest on pip as of now.

anaconda is not "just" a Python installation, it also contains the conda package manager that can install pre-built packages from the main repository of anaconda or from other "channels". It is not advisable to install packages that are available from the anaconda channel with pip, in general.

A comment on the issue of Cython here: to use Cython, your computer needs also a "development environment", that is the availability of a C compiler, of the Python development headers, among others. The C compiler must be compatible with the version of Python for which Cython is installed.

Title: Installing Cython/Statsmodels

Body:
I can not for the life of me figure out how to install the package statsmodels for Python 3. It feels like I've tried everything, but nothing is working.

Goal: import statsmodels in python

I start with:

pip install statsmodels

Main error messages:

Failed bulding wheel for statsmodels.
Cython is required to compile statsmodels from a development branch.
Please install Cython or download a source release of statsmodels.

So I try:

pip install cython

Gives:

Requirement already satisfied: cython in c:users\XXX\appdata\roaming\python\python36\site-packages

I installed cython by installing anaconda. I have tried almost all answers I could find by basic googling. But things just don't seem to be working.

Instead of listing the input\output of what I have tried I now only show the first steps, but let me know if you want to see the output of any commands.

How do I continue from here? Any help is appreciated, I've been trying to fix this for several days now and I'm only getting frustrated.

Right now I'm trying:

easy_install cython

This seemed to work, but afterwards pip install statsmodels didn't work.

Command ... failed with error code 1.

I tried:

git clone https://github.com/statsmodels/statsmodels
cd statsmodels
pip install .

And failed with a bunch of errors.

Body:
To install statsmodels under anaconda, use

conda install statsmodels

The package is available in the repository of anacondata in version 0.8.0 which is the latest on pip as of now.

anaconda is not "just" a Python installation, it also contains the conda package manager that can install pre-built packages from the main repository of anaconda or from other "channels". It is not advisable to install packages that are available from the anaconda channel with pip, in general.

A comment on the issue of Cython here: to use Cython, your computer needs also a "development environment", that is the availability of a C compiler, of the Python development headers, among others. The C compiler must be compatible with the version of Python for which Cython is installed.


问:
Git incorrectly infers "rename"
Git has inferred a "rename" when I had no desire for it to do so (this question is effectively the opposite of, say, How to make git mark a deleted and a new file as a file move?):

I created a new file, and did git add.  (I did not do a git commit, as I have no desire to do so at this stage.)

Later on I did git rm on another file.

Now git status reports renamed: old-file -> new-file.  I have not committed yet.

The two files are in the same directory, have similar-ish names and a certain amount of common content.  However, I deliberately did not do a git mv, as this is not a rename, I want the two files tracked separately.  If I had wanted a rename I would have done a git mv rather than my deliberate git add/git rm.

What about the activity has caused git to decide it's a rename, and can it be told not to try to infer things I don't intend?

答:
The files are similar enough so that git status thinks that it was a rename. Under the hood, it makes no difference at all, but if you want to ensure that it doesn't happen, make separate commits where you add and delete the files:

```<code>git add newfile
git commit
git rm oldfile
git commit
</code>```

Title: Git incorrectly infers "rename"

Body:
The files are similar enough so that git status thinks that it was a rename. Under the hood, it makes no difference at all, but if you want to ensure that it doesn't happen, make separate commits where you add and delete the files:

git add newfile
git commit
git rm oldfile
git commit


问:
How can I retrieve a list of parameters from a stored procedure in SQL Server
Using C# and System.Data.SqlClient, is there a way to retrieve a list of parameters that belong to a stored procedure on a SQL Server before I actually execute it?

I have an a "multi-environment" scenario where there are multiple versions of the same database schema. Examples of environments might be "Development", "Staging", & "Production". "Development" is going to have one version of the stored procedure and "Staging" is going to have another.

All I want to do is validate that a parameter is going to be there before passing it a value and calling the stored procedure. Avoiding that SqlException rather than having to catch it is a plus for me.

Joshua

答:
All of these ADO.NET solutions are are asking the code library to query the database's metadata on your behalf. If you are going to take that performance hit anyhow, maybe you should just write some helper functions that call

```<code>Select count(*) from information_schema.parameters
where ...(proc name =.. param name=...) (pseudo-code)
</code>```

Or maybe even generate your parameters based on the param list you get back. This technique will work with multiple versions of MS SQL and sometimes other ANSI SQL databases.

OwnerDisplayName: Joshua Hayworth

LastEditorDisplayName: Matt Hamilton

Body:
All of these ADO.NET solutions are are asking the code library to query the database's metadata on your behalf. If you are going to take that performance hit anyhow, maybe you should just write some helper functions that call

Select count(*) from information_schema.parameters
where ...(proc name =.. param name=...) (pseudo-code)

Or maybe even generate your parameters based on the param list you get back. This technique will work with multiple versions of MS SQL and sometimes other ANSI SQL databases.

OwnerDisplayName: MatthewMartin


问:
ASP.NET - Page.Form.Action error
On my local development server, I am running version 2.0.50727.4955 on the live server I am running 2.0.50727.42.

On my live server I get:

Compiler Error Message: CS0117: 'System.Web.UI.HtmlControls.HtmlForm' does not contain a definition for 'Action'

On my development server everything works fine. Is this a .NET version issue or something else? Is there a way to make this work on my liver server with its current .Net version? Is there a way to upgrade from 2.0.50727.42 to 2.0.50727.4955?

Thanks

EDIT (Code):

```<code>    if (Request.PathInfo.Length != 0)
    {
        string reqPath = Request.PathInfo;
        string raw = Request.RawUrl;
        string url = Request.Url.ToString();
        if (reqPath.Length > 0)
            url = url.Replace(reqPath, "");
        if (raw.Length > 0)
            url = url.Replace(raw, "");

        litBasePath.Text = "<base href=\"" + url + "\">";
        Page.Form.Attributes["Action"] = raw;
    }
</code>```

EDIT (Local Setup)

This is my local setup. I am not getting any compile errors when i run this locally.

答:
HtmlForm.Action does not exist in the unpatched 2.0 framework.  Only in 2.0 sp2+.  My guess is that your local environment you're building as a 3.5 app and using libraries that do not exist in your live environment.

In order set/change Action, I believe you need to use Page.Form.Attributes["action"] = "Some URL Here"

Or, if it's possible, patch your server (recommended) or install the .NET 3.5 Framework. in your live environment.

Title: ASP.NET - Page.Form.Action error

Body:
On my local development server, I am running version 2.0.50727.4955 on the live server I am running 2.0.50727.42.

On my live server I get:

Compiler Error Message: CS0117: 'System.Web.UI.HtmlControls.HtmlForm' does not contain a definition for 'Action'

On my development server everything works fine. Is this a .NET version issue or something else? Is there a way to make this work on my liver server with its current .Net version? Is there a way to upgrade from 2.0.50727.42 to 2.0.50727.4955?

Thanks

EDIT (Code):

    if (Request.PathInfo.Length != 0)
    {
        string reqPath = Request.PathInfo;
        string raw = Request.RawUrl;
        string url = Request.Url.ToString();
        if (reqPath.Length > 0)
            url = url.Replace(reqPath, "");
        if (raw.Length > 0)
            url = url.Replace(raw, "");

        litBasePath.Text = "<base href=\"" + url + "\">";
        Page.Form.Attributes["Action"] = raw;
    }

EDIT (Local Setup)

This is my local setup. I am not getting any compile errors when i run this locally.


问:
Open a local PDF file on  tag
I'm running create-react-app, and I want to open a local PDF file stored inside my repo with a relative path.

```<code><a href="../file.pdf" target="_blank">
    <button name="Click here" />
</a>
</code>```

After I click it, it takes me to localhost:3000/file.pdf. How do I open up a new window with a PDF?

答:
First, let's make sure that the path to the file.pdf file is correct.
If file's path is true. You write on project from following code.

Actually, you should not use the button again after the  tag. I think you edit your code by this.

```<code><a href="../file.pdf" target="_blank">
    <label>Click here</label>
</a>
</code>```

or

```<code><a href="../file.pdf" target="_blank">
    Click here
</a>
</code>```

Try the above code.

Title: Open a local PDF file on <a> tag

Body:
I'm running create-react-app, and I want to open a local PDF file stored inside my repo with a relative path.

    <button name="Click here" />

After I click it, it takes me to localhost:3000/file.pdf. How do I open up a new window with a PDF?

Body:
First, let's make sure that the path to the file.pdf file is correct.
If file's path is true. You write on project from following code.

Actually, you should not use the button again after the  tag. I think you edit your code by this.

<a href="../file.pdf" target="_blank">
    <label>Click here</label>
</a>

or

<a href="../file.pdf" target="_blank">
    Click here
</a>

Try the above code.


问:
Firebase token.email_verified going weird
Ok so im making a blog which requires users to login through firebase. To post comments, their email has to be verified

I know how to verify the email, and i did so with my test account. When i typed into the console

```<code>firebase.auth().currentUser.emailVerified
</code>```

it returned true, so yes my email was verified.

But the comment .validate rule requires the user to be validated, like so:

```<code>auth.token.email_verified === true
</code>```

However it wasn't working, so i removed it and it began to work again

After a bit of reading, I realized that i had to

```<code>const credentials = firebase.auth.EmailAuthProvider.credential(
  user.email, password);

user.reauthenticateWithCredential(credentials)
  .then(() => { /* ... */ });
</code>```

And that makes it work perfectly. The explanation was it apparantly takes the firebase server some time to update its backend validation, but reauthenticating forces the update immediately.

However, I am stumped on how to ask the user to reauthenticate themselves, as i have the following problem

How do I know when the users is validated (firebase.auth().currentUser.emailValidated), and at the same time the firebase backend is not updated (auth.token.email_verified === true is false) so that i can update my UI and prompt the user to reauthenticate

Basically how can i know when auth.token.email_verified === true is not updated yet on the client side

edit also is there a client side solution without reauthentication that updates the backend validation?

edit I tried user.reload().then(() => window.location.replace('/')) but it didnt work

答:
This is what is likely happening:

firebase.auth().currentUser.emailVerified is updated when firebase.auth().currentUser.reload() is called after verification. However auth.token.email_verified gets its value from the ID token which will not get updated until it gets expired or you force refresh. So you may have to call firebase.auth().currentUser.getIdToken(true) to force refresh to update the token claim which is sent to the Firebase Database backend.

Body:
Ok so im making a blog which requires users to login through firebase. To post comments, their email has to be verified

I know how to verify the email, and i did so with my test account. When i typed into the console

firebase.auth().currentUser.emailVerified

it returned true, so yes my email was verified.

But the comment .validate rule requires the user to be validated, like so:

auth.token.email_verified === true

However it wasn't working, so i removed it and it began to work again

After a bit of reading, I realized that i had to

const credentials = firebase.auth.EmailAuthProvider.credential(
  user.email, password);

user.reauthenticateWithCredential(credentials)
  .then(() => { /* ... */ });

And that makes it work perfectly. The explanation was it apparantly takes the firebase server some time to update its backend validation, but reauthenticating forces the update immediately.

However, I am stumped on how to ask the user to reauthenticate themselves, as i have the following problem

How do I know when the users is validated (firebase.auth().currentUser.emailValidated), and at the same time the firebase backend is not updated (auth.token.email_verified === true is false) so that i can update my UI and prompt the user to reauthenticate

Basically how can i know when auth.token.email_verified === true is not updated yet on the client side

edit also is there a client side solution without reauthentication that updates the backend validation?

edit I tried user.reload().then(() => window.location.replace('/')) but it didnt work


问:
What is .<format> argument for?

Django==1.11

django-extensions==1.9.7

```<code>/api/userprofiles/<pk>/   poinkbackend.apps.userprofiles.api.viewsets.UserProfileViewset  api:userprofile-detail
/api/userprofiles/<pk>\.<format>/ poinkbackend.apps.userprofiles.api.viewsets.UserProfileViewset  api:userprofile-detail
/a
</code>```

Docs say

show_urls - Displays the url routes that are defined in your project. Very crude at this point.

I had searched with format keyword. But the results are not related to my question.

Does it stand for ?format=json argument?

I had tried replacing json by html, xml. I got error in return.

Reference:
http://django-extensions.readthedocs.io/en/latest/command_extensions.html?highlight=show_urls

答:
In that URL pattern, format is a keyword argument in the URL pattern (unlike ?format=json where it's in the querystring). A matching URL would be:

```<code>/api/userprofiles/5.json/
</code>```

Title: What is .<format> argument for?

Body:
Django==1.11

django-extensions==1.9.7

/api/userprofiles/<pk>/   poinkbackend.apps.userprofiles.api.viewsets.UserProfileViewset  api:userprofile-detail
/api/userprofiles/<pk>\.<format>/ poinkbackend.apps.userprofiles.api.viewsets.UserProfileViewset  api:userprofile-detail
/a

Docs say

show_urls - Displays the url routes that are defined in your project. Very crude at this point.

I had searched with format keyword. But the results are not related to my question.

Does it stand for ?format=json argument?

I had tried replacing json by html, xml. I got error in return.

Reference:
http://django-extensions.readthedocs.io/en/latest/command_extensions.html?highlight=show_urls

Body:
In that URL pattern, format is a keyword argument in the URL pattern (unlike ?format=json where it's in the querystring). A matching URL would be:

/api/userprofiles/5.json/


问:
How can I obtain minutes and seconds from iphone compass?
I have an app that uses de iPhone's compass.
I use the CLLocationDirection magneticHeading value.
It is given only in degrees like 234.543, and when I turn the iPhone, for example, it changes to 235.543 236.543 237.543 238.543 and so on.
The point value (.543) doesn't change. I would like obtain more accuracy than degrees, I mean, I want the point value (.543) changes too when I turn the iPhone, or obtain the minutes/seconds value.
Anyone knows how can I have more precision in this value?
Thanks!

答:
I'm not familiar with the iPhone API, but I am familiar with sensors for embedded systems. If it's a magnetic compass sensor, you're probably getting orientation from the sensor with 1 degree resolution. (which is amazing that it can be that accurate, given the relatively small magnetic fields from the Earth)

Try looking at both the magneticHeading and the trueHeading (per the API docs). I'll bet the magnetic deviation is calculated more precisely than in 1 degree increments, and that's why you're seeing the .543; you might see a different number if you travel 100km east or west.


问:
C struct instance overwrites previous instance
I'm new to C, so the answer might be obvious but I just can't get my head around it.

I'm trying to create C++ vector kind of structure in C. I use Windows EnumWindows function to loop through all the windows. In the callback function I create new instance of windowHandle -structure for each window. For some reason however it doesn't seem to create new instance but rather just overwrites the old one. Or maybe it creates new instance, but when I give value to attribute windowHandle->title, it applies that change to every instance of windowHandle?

Callback function:

```<code>BOOL CALLBACK delegate(HWND wnd, LPARAM param){
if (filter(wnd)){ //<- just to make sure it's kind of window that we want.
            char windowName[256] = {};
            GetWindowText(wnd, windowName, sizeof(windowName));
            windowHandle *handle = malloc(sizeof(windowHandle)); //<- create new instance of windowHandle for each window
            handle->hWND = wnd;
            handle->title = windowName;
            insert((windowArray*) param, handle); //<- insert each windowHandle in our 'vector'
        }
// but return true here so that we iterate all windows
return TRUE;
}
</code>```

Call to EnumWindows function:

```<code>windowArray* array = array_init(20);
EnumWindows(&delegate, (LPARAM) array); //<- not quite sure what that '&'-sign does?
</code>```

Structures:

```<code>typedef struct windowHandle{
    HWND hWND;
    char* title;
} windowHandle;

typedef struct windowArray{
    int count;
    int capacity;
    int objectSize;
    windowHandle* windows;
} windowArray;
</code>```

And lastly insert:

```<code>int insert(windowArray* array, void* handle){
    int index = (array->count * array->objectSize);
    if(index > 0){
        printf("\n%s %s\n", "first element's title is: ", array->windows->title); //<- prints to see if new handle overwrite the previous ones
    }
    printf("%s %s %s %p %s %d\n", "Inserted element ", ((windowHandle*)handle)->title, " with pointer ", handle, " on index ", index);
    fflush(stdout); //<- prints info about first & current window
    memcpy(array->windows + (index), (windowHandle*)handle, array->objectSize);
    array->count++;
}
</code>```

Output during insert calls:

```<code>Inserted element  joo - Java - nativeWindowCapture/src/NativeWindowHookImp.c - Eclipse SDK  with pointer  0000000000FB1B90  on index  0

first element's title is:  Komentokehote
Inserted element  Komentokehote  with pointer  0000000000FB1BB0  on index  16

first element's title is:  C struct instance overwrites previous instance - Stack Overflow - Mozilla Firefox
Inserted element  C struct instance overwrites previous instance - Stack Overflow - Mozilla Firefox  with pointer  0000000000FB1BD0  on index  32

first element's title is:  JNI compiler kutsu – Muistio
Inserted element  JNI compiler kutsu – Muistio  with pointer  0000000000FB1BF0  on index  48

first element's title is:  Skype™?
Inserted element  Skype™? with pointer  0000000000FB1C10  on index  64

first element's title is:  eclipse
Inserted element  eclipse  with pointer  0000000000FB1C30  on index  80

first element's title is:  src
Inserted element  src  with pointer  0000000000FBCCE0  on index  96
all added
</code>```

and then if I print the full content of windowArray->windows, I get the following results:

```<code>Getting value  src , at index  0  and pointer  0000000000FBBB80
Getting value  src , at index  16  and pointer  0000000000FBBC80
Getting value  src , at index  32  and pointer  0000000000FBBD80
Getting value  src , at index  48  and pointer  0000000000FBBE80
Getting value  src , at index  64  and pointer  0000000000FBBF80
Getting value  src , at index  80  and pointer  0000000000FBC080
Getting value  src , at index  96  and pointer  0000000000FBC180
</code>```

P.S. I would also like to know why windowArray's windows-attribute's pointers are different from those of *handle-objects created in delegate? That doesn't seem to be very efficient memorywise?

答:
You set handle->title to point to windowName. But as soon as you exit this scope, windowName will cease to exist. So your structure contains a pointer to an array that no longer exists.

```<code>        char windowName[256] = {};
        GetWindowText(wnd, windowName, sizeof(windowName));
        windowHandle *handle = malloc(sizeof(windowHandle)); //<- create new instance of windowHandle for each window
        handle->hWND = wnd;
        handle->title = windowName;
    }
    // when we get here, windowName ceases to exist
    // so why did we store a pointer to it?
</code>```

After you exit the scope, it is an error to follow the title pointer, since it no longer points to any object that is still alive. Perhaps change title from char * to char[256].

Body:
I'm new to C, so the answer might be obvious but I just can't get my head around it.

I'm trying to create C++ vector kind of structure in C. I use Windows EnumWindows function to loop through all the windows. In the callback function I create new instance of windowHandle -structure for each window. For some reason however it doesn't seem to create new instance but rather just overwrites the old one. Or maybe it creates new instance, but when I give value to attribute windowHandle->title, it applies that change to every instance of windowHandle?

Callback function:

BOOL CALLBACK delegate(HWND wnd, LPARAM param){
if (filter(wnd)){ //<- just to make sure it's kind of window that we want.
            char windowName[256] = {};
            GetWindowText(wnd, windowName, sizeof(windowName));
            windowHandle *handle = malloc(sizeof(windowHandle)); //<- create new instance of windowHandle for each window
            handle->hWND = wnd;
            handle->title = windowName;
            insert((windowArray*) param, handle); //<- insert each windowHandle in our 'vector'
        }
// but return true here so that we iterate all windows
return TRUE;
}

Call to EnumWindows function:

windowArray* array = array_init(20);
EnumWindows(&delegate, (LPARAM) array); //<- not quite sure what that '&'-sign does?

Structures:

typedef struct windowHandle{
    HWND hWND;
    char* title;
} windowHandle;

typedef struct windowArray{
    int count;
    int capacity;
    int objectSize;
    windowHandle* windows;
} windowArray;

And lastly insert:

int insert(windowArray* array, void* handle){
    int index = (array->count * array->objectSize);
    if(index > 0){
        printf("\n%s %s\n", "first element's title is: ", array->windows->title); //<- prints to see if new handle overwrite the previous ones
    }
    printf("%s %s %s %p %s %d\n", "Inserted element ", ((windowHandle*)handle)->title, " with pointer ", handle, " on index ", index);
    fflush(stdout); //<- prints info about first & current window
    memcpy(array->windows + (index), (windowHandle*)handle, array->objectSize);
    array->count++;
}

Output during insert calls:

Inserted element  joo - Java - nativeWindowCapture/src/NativeWindowHookImp.c - Eclipse SDK  with pointer  0000000000FB1B90  on index  0

first element's title is:  Komentokehote
Inserted element  Komentokehote  with pointer  0000000000FB1BB0  on index  16

first element's title is:  C struct instance overwrites previous instance - Stack Overflow - Mozilla Firefox
Inserted element  C struct instance overwrites previous instance - Stack Overflow - Mozilla Firefox  with pointer  0000000000FB1BD0  on index  32

first element's title is:  JNI compiler kutsu – Muistio
Inserted element  JNI compiler kutsu – Muistio  with pointer  0000000000FB1BF0  on index  48

first element's title is:  Skype™?
Inserted element  Skype™? with pointer  0000000000FB1C10  on index  64

first element's title is:  eclipse
Inserted element  eclipse  with pointer  0000000000FB1C30  on index  80

first element's title is:  src
Inserted element  src  with pointer  0000000000FBCCE0  on index  96
all added

and then if I print the full content of windowArray->windows, I get the following results:

Getting value  src , at index  0  and pointer  0000000000FBBB80
Getting value  src , at index  16  and pointer  0000000000FBBC80
Getting value  src , at index  32  and pointer  0000000000FBBD80
Getting value  src , at index  48  and pointer  0000000000FBBE80
Getting value  src , at index  64  and pointer  0000000000FBBF80
Getting value  src , at index  80  and pointer  0000000000FBC080
Getting value  src , at index  96  and pointer  0000000000FBC180

P.S. I would also like to know why windowArray's windows-attribute's pointers are different from those of *handle-objects created in delegate? That doesn't seem to be very efficient memorywise?

Body:
You set handle->title to point to windowName. But as soon as you exit this scope, windowName will cease to exist. So your structure contains a pointer to an array that no longer exists.

        char windowName[256] = {};
        GetWindowText(wnd, windowName, sizeof(windowName));
        windowHandle *handle = malloc(sizeof(windowHandle)); //<- create new instance of windowHandle for each window
        handle->hWND = wnd;
        handle->title = windowName;
    }
    // when we get here, windowName ceases to exist
    // so why did we store a pointer to it?

After you exit the scope, it is an error to follow the title pointer, since it no longer points to any object that is still alive. Perhaps change title from char * to char[256].