问:
Azure Cloud Service (Classic) - single instance is missing a root CA / SSL certificate cannot be verified
I have a Cloud Service (Classic) running in Azure that hosts a WCF service. Multiple instances are configured in the Cloud Service thorugh the Scale feature of the Cloud Service. An SSL Wildcard certificate has been provided via Azure Portal and configured in csdef/cscfg in the corresponding Visual Studio Cloud project. Until recently, everything run perfectly, no issues with the certificates, etc. has occurred.

.csdef

```<code><Sites>
  <Site name="Web">
    <Bindings>
      <Binding name="Endpoint2" endpointName="EndpointSSL" />
    </Bindings>
  </Site>
</Sites>
<Endpoints>
  <InputEndpoint name="EndpointSSL" protocol="https" port="443" certificate="SSL" />
</Endpoints>
<Certificates>
  <Certificate name="SSL" storeLocation="LocalMachine" storeName="My" />
</Certificates>
</code>```

.cscfg

```<code><Role name="FR">
  <Instances count="3" />
  <ConfigurationSettings>
    <!-- Settings are set here -->
  </ConfigurationSettings>
  <Certificates>
    <Certificate name="Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" thumbprint="THUMBPRINT_A" thumbprintAlgorithm="sha1" />
    <Certificate name="SSL" thumbprint="THUMBPRINT_B" thumbprintAlgorithm="sha1" />
  </Certificates>
</Role>
</code>```

The certificate gets installed properly, as you can see in the certificate management window in windows. Unfortunately, starting last week, when checking the site via SSL Labs (https://www.ssllabs.com/ssltest/) it started to deliver two certificates in the resulting report, one of them being invalid as the certificate chain seems to be broken. Other services using the same Wildcard certificate do not have this issue.

What I do know so far about this issue:

The certificate in the certificate store on one of the three running instances cannot be verifies by windows itself.

On the other two instances, the certificate is correct and can be verified by windows

The instance with the invalid certificate does not have the corresponding root CA in the "Trusted Root CAs" store in windows.

Redeploying, Reimaging, Restarting, etc. does not help. It might just shift the issue from one instance to another. SO far only one instance was affected at a time.

No changes have been made manually nor was a newer deployment applied recently. It just started to occur out of the blue

Does anybody have any ideas what the issue might be? I also started a support ticket with Microsoft but so far they also have no clue. Are there any settings that I might try out when deploying that forces the certificates to be verified at deployment? Or is there any option to get the missing Root CA from code at startup (as I suspect that this might be the issue why it cannot be verified on the one instance)?

答:
The Microsoft Azure support does also not know the root cause of this behavior, however they came up with a suitable workaround for the time being.

In the Cloud Service, a Startup Task has been added that checks whether the potentially missing Root CA is existing in the list of all Root CAs. If not, the missing one will be installed (via Powershell). After that, the missing Root CA should have been added to the list of Root CAs and the actual SSL Wildcard certificate (that failed to validate) can successfully be verified - checks via SSLLabs will work again.

At least for my problem, this did the trick. I'm not completely satisfied with it as I'd like to know the root cause, but Microsoft seems to be aware of the issue and (from what I understand) is investigating investigating further. If any proper solution (instead of the workaround) comes up, I will try to add it here as well.

CMD File for Startup task:

```<code>SET LOG_FILE="%TEMP%\StartupLog.txt"
SET EXECUTE_PS1=0

IF "%ComputeEmulatorRunning%" == "" (
    SET EXECUTE_PS1=1
)

IF "%ComputeEmulatorRunning%" == "false" (
    SET EXECUTE_PS1=1
)

IF %EXECUTE_PS1% EQU 1 (
    echo "Invoking InstallCertificateSSLConfigure.ps1 on Azure service at %TIME% on %DATE%" >> %LOG_FILE% 2>&1
    PowerShell -ExecutionPolicy Unrestricted .\Startup\InstallCertificate.ps1 >> %LOG_FILE% 2>&1
    IF %ERRORLEVEL% NEQ 0 (EXIT /B %ERRORLEVEL%)
) ELSE (
    echo "Skipping InstallCertificate.ps1 invocation on emulated environment" >> %LOG_FILE% 2>&1
)

EXIT /B 0
</code>```

Powershell script to install certificate (executed from CMD)

```<code>$thumbprint = "THUMBPRINT"
$path = ".\Startup\MISSING ROOT CA.crt"

$cert = Get-ChildItem -Path Cert:\LocalMachine\Root | Where-Object {$_.Thumbprint -eq $thumbprint}

if ( $cert )
{
    Write-Host "The Certificate $($cert.Thumbprint) is installed already"
}
else
{
    Write-Host "The Certificate $thumbprint is not installed"
    Import-Certificate -FilePath $path -CertStoreLocation Cert:\LocalMachine\Root
    Write-Host "installed the Certificate $thumbprint"
}
</code>```

Body:
I have a Cloud Service (Classic) running in Azure that hosts a WCF service. Multiple instances are configured in the Cloud Service thorugh the Scale feature of the Cloud Service. An SSL Wildcard certificate has been provided via Azure Portal and configured in csdef/cscfg in the corresponding Visual Studio Cloud project. Until recently, everything run perfectly, no issues with the certificates, etc. has occurred.

.csdef

<Sites>
  <Site name="Web">
    <Bindings>
      <Binding name="Endpoint2" endpointName="EndpointSSL" />
    </Bindings>
  </Site>
</Sites>
<Endpoints>
  <InputEndpoint name="EndpointSSL" protocol="https" port="443" certificate="SSL" />
</Endpoints>
<Certificates>
  <Certificate name="SSL" storeLocation="LocalMachine" storeName="My" />
</Certificates>

.cscfg

<Role name="FR">
  <Instances count="3" />
  <ConfigurationSettings>

  </ConfigurationSettings>
  <Certificates>
    <Certificate name="Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" thumbprint="THUMBPRINT_A" thumbprintAlgorithm="sha1" />
    <Certificate name="SSL" thumbprint="THUMBPRINT_B" thumbprintAlgorithm="sha1" />
  </Certificates>
</Role>

The certificate gets installed properly, as you can see in the certificate management window in windows. Unfortunately, starting last week, when checking the site via SSL Labs (https://www.ssllabs.com/ssltest/) it started to deliver two certificates in the resulting report, one of them being invalid as the certificate chain seems to be broken. Other services using the same Wildcard certificate do not have this issue.

What I do know so far about this issue:

The certificate in the certificate store on one of the three running instances cannot be verifies by windows itself.

On the other two instances, the certificate is correct and can be verified by windows

The instance with the invalid certificate does not have the corresponding root CA in the "Trusted Root CAs" store in windows.

Redeploying, Reimaging, Restarting, etc. does not help. It might just shift the issue from one instance to another. SO far only one instance was affected at a time.

No changes have been made manually nor was a newer deployment applied recently. It just started to occur out of the blue

Does anybody have any ideas what the issue might be? I also started a support ticket with Microsoft but so far they also have no clue. Are there any settings that I might try out when deploying that forces the certificates to be verified at deployment? Or is there any option to get the missing Root CA from code at startup (as I suspect that this might be the issue why it cannot be verified on the one instance)?

Body:
The Microsoft Azure support does also not know the root cause of this behavior, however they came up with a suitable workaround for the time being.

In the Cloud Service, a Startup Task has been added that checks whether the potentially missing Root CA is existing in the list of all Root CAs. If not, the missing one will be installed (via Powershell). After that, the missing Root CA should have been added to the list of Root CAs and the actual SSL Wildcard certificate (that failed to validate) can successfully be verified - checks via SSLLabs will work again.

At least for my problem, this did the trick. I'm not completely satisfied with it as I'd like to know the root cause, but Microsoft seems to be aware of the issue and (from what I understand) is investigating investigating further. If any proper solution (instead of the workaround) comes up, I will try to add it here as well.

CMD File for Startup task:

SET LOG_FILE="%TEMP%\StartupLog.txt"
SET EXECUTE_PS1=0

IF "%ComputeEmulatorRunning%" == "" (
    SET EXECUTE_PS1=1
)

IF "%ComputeEmulatorRunning%" == "false" (
    SET EXECUTE_PS1=1
)

IF %EXECUTE_PS1% EQU 1 (
    echo "Invoking InstallCertificateSSLConfigure.ps1 on Azure service at %TIME% on %DATE%" >> %LOG_FILE% 2>&1
    PowerShell -ExecutionPolicy Unrestricted .\Startup\InstallCertificate.ps1 >> %LOG_FILE% 2>&1
    IF %ERRORLEVEL% NEQ 0 (EXIT /B %ERRORLEVEL%)
) ELSE (
    echo "Skipping InstallCertificate.ps1 invocation on emulated environment" >> %LOG_FILE% 2>&1
)

EXIT /B 0

Powershell script to install certificate (executed from CMD)

$thumbprint = "THUMBPRINT"
$path = ".\Startup\MISSING ROOT CA.crt"

$cert = Get-ChildItem -Path Cert:\LocalMachine\Root | Where-Object {$_.Thumbprint -eq $thumbprint}

if ( $cert )
{
    Write-Host "The Certificate $($cert.Thumbprint) is installed already"
}
else
{
    Write-Host "The Certificate $thumbprint is not installed"
    Import-Certificate -FilePath $path -CertStoreLocation Cert:\LocalMachine\Root
    Write-Host "installed the Certificate $thumbprint"
}


来源: stackexchange

问:
why i m getting warning: comparison between pointer and integer
I'm getting warning msg saying:

comparison between pointer and integer

```<code>char * replaceWord(const char * str, const char * oldWord, const char * newWord)
{
    char * resultString;
    int i, count = 0;
    int newWordLength = strlen(newWord);
    int oldWordLength = strlen(oldWord);
    //count the no of occurance of word in string in a file
    for (i = 0; str[i] !='\0'; i++)
    {
        if (strstr(str[i], oldWord) == str[i])//i m getting warning here
        {
            count++;

            i = i + oldWordLength - 1;
        }

    }

    // Making a new string to fit in the replaced words
    resultString = (char *)malloc(i + count * (newWordLength - oldWordLength) + 1);

    i = 0;
    while (*str!='\0')
    {
        // Compare the substring with result
        if(strstr(str, oldWord) == str)//here i used same syantax its working but not above
        {
            strcpy(&resultString[i], newWord);
            i += newWordLength;
            str += oldWordLength;
        }
        else{
            resultString[i] = *str;
            i += 1;
            str +=1;
        }
    }
    resultString[i] = '\0';
    return resultString;
}
</code>```

答:
From the man page for strstr():

```<code>#include <string.h>

char *strstr(const char *haystack, const char *needle);
</code>```

So, strstr() returns the substring's char* pointer as the result, and you are comparing it against a char variable (str[i]), thus the error.

ContentLicense: CC BY-SA 4.0

Body:
I'm getting warning msg saying:

comparison between pointer and integer

char * replaceWord(const char * str, const char * oldWord, const char * newWord)
{
    char * resultString;
    int i, count = 0;
    int newWordLength = strlen(newWord);
    int oldWordLength = strlen(oldWord);
    //count the no of occurance of word in string in a file
    for (i = 0; str[i] !='\0'; i++)
    {
        if (strstr(str[i], oldWord) == str[i])//i m getting warning here
        {
            count++;

            i = i + oldWordLength - 1;
        }

    }

    // Making a new string to fit in the replaced words
    resultString = (char *)malloc(i + count * (newWordLength - oldWordLength) + 1);

    i = 0;
    while (*str!='\0')
    {
        // Compare the substring with result
        if(strstr(str, oldWord) == str)//here i used same syantax its working but not above
        {
            strcpy(&resultString[i], newWord);
            i += newWordLength;
            str += oldWordLength;
        }
        else{
            resultString[i] = *str;
            i += 1;
            str +=1;
        }
    }
    resultString[i] = '\0';
    return resultString;
}

Body:
From the man page for strstr():

#include <string.h>

char *strstr(const char *haystack, const char *needle);

So, strstr() returns the substring's char* pointer as the result, and you are comparing it against a char variable (str[i]), thus the error.


问:
MS Access Update with Increment of Prior Record
I have an MS Access 2007 database that I need to create an update for. The table I am trying to update looks like this:

```<code> CarID  WeekOf          NumDataPoints   NumWksZeroPoints
 3AA    May-14-2011     23              0
 7BB    May-14-2011     9               0

 3AA    May-21-2011     35              0
 7BB    May-21-2011     0               1

 3AA    May-28-2011     24
 7BB    May-28-2011     0
</code>```

I am processing the latest recordset of May-28-2011 and the gist is to update each car with the number of weeks its had no data points. I do this by checking the current week number of points and if it does have some points then the #WeeksZeroPoints gets set to zero, and if the current number of points is zero then i take the prior weeks count and increment by one. For my last week I would have input

```<code>  0
  2
</code>```

So I have tried something like

```<code>UPDATE tblCars
SET NumWksZeroPoints = IIF(NumDataPoints<>0, 0, (SELECT MAX(NumWksZeroPoints) AS wzp
                                                 FROM tblCars AS f
                                                 WHERE f.CarID=tblCars.CarID AND
                                                       f.WeekEnding=#5/21/2011#) + 1
                       )
WHERE WeekOf=#5/28/2011#;
</code>```

Unfortunately this doesn't work like I thought it would. I think I have the concept down and most of the SQL, I just cant seem to make it work. This is against MS Access so some of the other tricks I know just don't work. Any help appreciated.

答:
Using your sample data I ran the following

```<code>UPDATE tblcar AS c
       INNER JOIN tblcar AS previous
         ON c.carid = previous.carid
SET    c.numwkszeropoints = Iif([previous].[NumWksZeroPoints] = 0, 0,
                                   [previous].[NumWksZeroPoints] + 1)
WHERE c.weekof =#5/28/2011 #
         AND previous.weekof =#5/21/2011#;
</code>```

The table afterwards looked like this

```<code>CarID WeekOf     NumDataPoints NumWksZeroPoints
----- ---------- ------------- -----------------
3AA   05/14/2011 23            0
7BB   05/14/2011 9             0
3AA   05/21/2011 35            0
7BB   05/21/2011 0             1
3AA   05/28/2011 24            0
7BB   05/28/2011 0             2
</code>```

Basically the query does a self join back to the previous week, and the update the current week to the previous week's value + 1 if its not zero.

ContentLicense: CC BY-SA 3.0

Body:
I have an MS Access 2007 database that I need to create an update for. The table I am trying to update looks like this:

 CarID  WeekOf          NumDataPoints   NumWksZeroPoints
 3AA    May-14-2011     23              0
 7BB    May-14-2011     9               0

 3AA    May-21-2011     35              0
 7BB    May-21-2011     0               1

 3AA    May-28-2011     24
 7BB    May-28-2011     0

I am processing the latest recordset of May-28-2011 and the gist is to update each car with the number of weeks its had no data points. I do this by checking the current week number of points and if it does have some points then the #WeeksZeroPoints gets set to zero, and if the current number of points is zero then i take the prior weeks count and increment by one. For my last week I would have input

  0
  2

So I have tried something like

UPDATE tblCars
SET NumWksZeroPoints = IIF(NumDataPoints<>0, 0, (SELECT MAX(NumWksZeroPoints) AS wzp
                                                 FROM tblCars AS f
                                                 WHERE f.CarID=tblCars.CarID AND
                                                       f.WeekEnding=#5/21/2011#) + 1
                       )
WHERE WeekOf=#5/28/2011#;

Unfortunately this doesn't work like I thought it would. I think I have the concept down and most of the SQL, I just cant seem to make it work. This is against MS Access so some of the other tricks I know just don't work. Any help appreciated.

Body:
Using your sample data I ran the following

UPDATE tblcar AS c
       INNER JOIN tblcar AS previous
         ON c.carid = previous.carid
SET    c.numwkszeropoints = Iif([previous].[NumWksZeroPoints] = 0, 0,
                                   [previous].[NumWksZeroPoints] + 1)
WHERE c.weekof =#5/28/2011 #
         AND previous.weekof =#5/21/2011#;

The table afterwards looked like this

CarID WeekOf     NumDataPoints NumWksZeroPoints
----- ---------- ------------- -----------------
3AA   05/14/2011 23            0
7BB   05/14/2011 9             0
3AA   05/21/2011 35            0
7BB   05/21/2011 0             1
3AA   05/28/2011 24            0
7BB   05/28/2011 0             2

Basically the query does a self join back to the previous week, and the update the current week to the previous week's value + 1 if its not zero.


问:
JS Regex returning -1 & 0
I was tasked with the following:

take a string

print each of the vowels on a new line (in order) then...

print each of the consonants on a new line (in order)

The problem I found was with the regex. I originally used...

/[aeiouAEIOU\s]/g```
</div>
</div>
</p>

<p>But this would return 0 with a vowel and -1 with a consonant (so everything happened in reverse).
I really struggled to understand why and couldn't for the life of me find the answer. In the end it was simple enough to just invert the string but I want to know why this is happening the way it is. Can anyone help?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let i;
let vowels = /[^aeiouAEIOU\s]/g;
let array = [];
function vowelsAndConsonants(s) {
    for(i=0;i<s.length;i++){
        //if char is vowel then push to array
        if(s[i].search(vowels)){
           array.push(s[i]);
        }

    }
    for(i=0;i<s.length;i++){
        //if char is cons then push to array
        if(!s[i].search(vowels)){
           array.push(s[i]);
        }
    }
    for(i=0;i<s.length;i++){
        console.log(array[i]);
    }
}

vowelsAndConsonants("javascript");</code>```

答:
if(vowels.test(s[i])){ which will return true or false if it matches, or

if(s[i].search(vowels) !== -1){ and if(s[i].search(vowels) === -1){

is what you want if you want to fix your code.

-1 is not falsey so your if statement will not function correctly.  -1 is what search returns if it doesn't find a match.  It has to do this because search() returns the index position of the match, and the index could be anywhere from 0 to Infinity, so only negative numbers are available to indicate non-existent index:

MDN search() reference

Below is a RegEx that matches vowel OR any letter OR other, effectively separating out vowel, consonant, everything else into 3 capture groups.  This makes it so you don't need to test character by character and separate them out manually.

Then iterates and pushes them into their respective arrays with a for-of loop.

const consonants = [], vowels = [], other = [];

const str = ";bat cat set rat. let ut cut mut,";

for(const [,cons,vow,etc] of str.matchAll(/([aeiouAEIOU])|([a-zA-Z])|(.)/g))
  cons&&consonants.push(cons) || vow&&vowels.push(vow) || typeof etc === 'string'&&other.push(etc)

console.log(
consonants.join('') + '\n' + vowels.join('') + '\n' + other.join('')
)```

Title: JS Regex returning -1 & 0

Body:
I was tasked with the following:

take a string

print each of the vowels on a new line (in order) then...

print each of the consonants on a new line (in order)

The problem I found was with the regex. I originally used...

/[aeiouAEIOU\s]/g

But this would return 0 with a vowel and -1 with a consonant (so everything happened in reverse).
I really struggled to understand why and couldn't for the life of me find the answer. In the end it was simple enough to just invert the string but I want to know why this is happening the way it is. Can anyone help?

let i;
let vowels = /[^aeiouAEIOU\s]/g;
let array = [];
function vowelsAndConsonants(s) {
    for(i=0;i<s.length;i++){
        //if char is vowel then push to array
        if(s[i].search(vowels)){
           array.push(s[i]);
        }

    }
    for(i=0;i<s.length;i++){
        //if char is cons then push to array
        if(!s[i].search(vowels)){
           array.push(s[i]);
        }
    }
    for(i=0;i<s.length;i++){
        console.log(array[i]);
    }
}

vowelsAndConsonants("javascript");


问:
Group dataframe by columns containing specific value R
I have a dataframe which looks like the following:

```<code>Type    June 23   June 24   July 23    July 24    August 23    August 24
 A         8        2          20         20           30         25
 B         8        2          20         20           30         25
</code>```

Now I want to have the sum over the columns per month (so disregarding the week number). So, the result should look like this

```<code>Type    June   July   August
 A       10     40      55
 B       10     40      55
</code>```

I try do this this using dplyr, but I do not know how to match only the first part of the column names. Does anyone have an idea how to do this?

答:
In base R, you can use split.default to split data based on similar part of column names.

In your example, if we remove numbers from column names we get the month name, pass it to split.default and sum each part using rowSums.

```<code>cbind(df[1],sapply(split.default(df[-1], sub('\\d+', '',names(df[-1]))), rowSums))

#  Type August July June
#1    A     55   40   10
#2    B     55   40   10
</code>```

data

```<code>df <- structure(list(Type = c("A", "B"), June23 = c(8L, 8L), June24 = c(2L,
2L), July23 = c(20L, 20L), July24 = c(20L, 20L), August23 = c(30L,
30L), August24 = c(25L, 25L)), class = "data.frame", row.names = c(NA, -2L))
</code>```

Body:
I have a dataframe which looks like the following:

Type    June 23   June 24   July 23    July 24    August 23    August 24
 A         8        2          20         20           30         25
 B         8        2          20         20           30         25

Now I want to have the sum over the columns per month (so disregarding the week number). So, the result should look like this

Type    June   July   August
 A       10     40      55
 B       10     40      55

I try do this this using dplyr, but I do not know how to match only the first part of the column names. Does anyone have an idea how to do this?

Body:
In base R, you can use split.default to split data based on similar part of column names.

In your example, if we remove numbers from column names we get the month name, pass it to split.default and sum each part using rowSums.

cbind(df[1],sapply(split.default(df[-1], sub('\\d+', '',names(df[-1]))), rowSums))

#  Type August July June
#1    A     55   40   10
#2    B     55   40   10

data

df <- structure(list(Type = c("A", "B"), June23 = c(8L, 8L), June24 = c(2L,
2L), July23 = c(20L, 20L), July24 = c(20L, 20L), August23 = c(30L,
30L), August24 = c(25L, 25L)), class = "data.frame", row.names = c(NA, -2L))


问:
R: Aggregate (from stats v3.6.2) does not work properly
I have a data frame with two columns. The first one identifies the document and is called "doc_id". The second column contains text that I have assembled from several columns and is called "text". The assembled text contains several sentences. There is noting else in the data frame. A sample could look like this:

My Problem is, that when I use the aggregate function (from stats v3.6.2), it doesn´t aggregate properly. Some lines are not aggregated or sometimes they are aggregated as a list and not as a single string.

Starting Situation:

```<code>    doc_id           text
1   1015328_1999     aaa aaa aaa.
2   1015328_2000     bbb bbb bbb.
3   1015328_2003     ccc ccc ccc.
4   1015328_2004     ddd ddd ddd.
5   1015328_2005     eee eee eee.
6   1015328_2006     fff fff fff.
7   1015328_2006     ggg ggg ggg.
8   1015328_2006     hhh hhh hhh.
9   1015328_2006     iii iii iii.
10  1015328_2006     jjj jjj jjj.
</code>```

Result I want to obtain:

```<code>    doc_id           text
1   1015328_1999     aaa aaa aaa.
2   1015328_2000     bbb bbb bbb.
3   1015328_2003     ccc ccc ccc.
4   1015328_2004     ddd ddd ddd.
5   1015328_2005     eee eee eee.
6   1015328_2006     fff fff fff. ggg ggg ggg. hhh hhh hhh. iii iii iii. jjj jjj jjj.
</code>```

I tried to used the following code:

```<code>> mydataframe <- aggregate(text ~ doc_id, data = mydataframe, paste, collapse = " ")
</code>```

But this is what I get instead:

```<code>    doc_id           text
1   1015328_1999     aaa aaa aaa.
2   1015328_2000     bbb bbb bbb.
3   1015328_2003     ccc ccc ccc.
4   1015328_2004     ddd ddd ddd.
5   1015328_2005     eee eee eee.
6   1015328_2006
</code>```

Although there should be data for aggregation, the code does not. Sometimes it aggregates correctly, sometimes it aggregates but puts a list in a row instead of a string, and sometimes the values are missing completely.

Any help would be highly appreciated!
Thank you very much in advance.

EDIT:
Test data as code:

```<code>library(tidyverse)
test <- tribble(
  ~doc_id,      ~text,
  "1015328_1999", "aaa aaa aaa.",
  "1015328_2000", "bbb bbb bbb.",
  "1015328_2003", "ccc ccc ccc.",
  "1015328_2004", "ddd ddd ddd.",
  "1015328_2005", "eee eee eee.",
  "1015328_2006", "fff fff fff.",
  "1015328_2006", "ggg ggg ggg.",
  "1015328_2006", "hhh hhh hhh.",
  "1015328_2006", "iii iii iii.",
  "1015328_2006", "jjj jjj jjj.",)
</code>```

答:
I've come up with a solution based on tidyverse not stats. If that is a problem or solution doesn't meet what you're trying to do, please let me know

```<code>library(tidyverse)
test <- tribble(
  ~doc_id,      ~text,
  "1015328_1999", "aaa aaa aaa.",
  "1015328_2000", "bbb bbb bbb.",
  "1015328_2003", "ccc ccc ccc.",
  "1015328_2004", "ddd ddd ddd.",
  "1015328_2005", "eee eee eee.",
  "1015328_2006", "fff fff fff.",
  "1015328_2006", "ggg ggg ggg.",
  "1015328_2006", "hhh hhh hhh.",
  "1015328_2006", "iii iii iii.",
  "1015328_2006", "jjj jjj jjj.",)

group_by(test, doc_id) %>% summarise(text = paste(text, collapse = " "))
</code>```

Output:

```<code># A tibble: 6 x 2
  doc_id       text
  <chr>        <chr>
1 1015328_1999 aaa aaa aaa.
2 1015328_2000 bbb bbb bbb.
3 1015328_2003 ccc ccc ccc.
4 1015328_2004 ddd ddd ddd.
5 1015328_2005 eee eee eee.
6 1015328_2006 fff fff fff. ggg ggg ggg. hhh hhh hhh. iii iii iii. jjj jjj jjj.
</code>```

Body:
I have a data frame with two columns. The first one identifies the document and is called "doc_id". The second column contains text that I have assembled from several columns and is called "text". The assembled text contains several sentences. There is noting else in the data frame. A sample could look like this:

My Problem is, that when I use the aggregate function (from stats v3.6.2), it doesn´t aggregate properly. Some lines are not aggregated or sometimes they are aggregated as a list and not as a single string.

Starting Situation:

    doc_id           text
1   1015328_1999     aaa aaa aaa.
2   1015328_2000     bbb bbb bbb.
3   1015328_2003     ccc ccc ccc.
4   1015328_2004     ddd ddd ddd.
5   1015328_2005     eee eee eee.
6   1015328_2006     fff fff fff.
7   1015328_2006     ggg ggg ggg.
8   1015328_2006     hhh hhh hhh.
9   1015328_2006     iii iii iii.
10  1015328_2006     jjj jjj jjj.

Result I want to obtain:

    doc_id           text
1   1015328_1999     aaa aaa aaa.
2   1015328_2000     bbb bbb bbb.
3   1015328_2003     ccc ccc ccc.
4   1015328_2004     ddd ddd ddd.
5   1015328_2005     eee eee eee.
6   1015328_2006     fff fff fff. ggg ggg ggg. hhh hhh hhh. iii iii iii. jjj jjj jjj.

I tried to used the following code:

> mydataframe <- aggregate(text ~ doc_id, data = mydataframe, paste, collapse = " ")

But this is what I get instead:

    doc_id           text
1   1015328_1999     aaa aaa aaa.
2   1015328_2000     bbb bbb bbb.
3   1015328_2003     ccc ccc ccc.
4   1015328_2004     ddd ddd ddd.
5   1015328_2005     eee eee eee.
6   1015328_2006

Although there should be data for aggregation, the code does not. Sometimes it aggregates correctly, sometimes it aggregates but puts a list in a row instead of a string, and sometimes the values are missing completely.

Any help would be highly appreciated!
Thank you very much in advance.

EDIT:
Test data as code:

library(tidyverse)
test <- tribble(
  ~doc_id,      ~text,
  "1015328_1999", "aaa aaa aaa.",
  "1015328_2000", "bbb bbb bbb.",
  "1015328_2003", "ccc ccc ccc.",
  "1015328_2004", "ddd ddd ddd.",
  "1015328_2005", "eee eee eee.",
  "1015328_2006", "fff fff fff.",
  "1015328_2006", "ggg ggg ggg.",
  "1015328_2006", "hhh hhh hhh.",
  "1015328_2006", "iii iii iii.",
  "1015328_2006", "jjj jjj jjj.",)

Body:
I've come up with a solution based on tidyverse not stats. If that is a problem or solution doesn't meet what you're trying to do, please let me know

library(tidyverse)
test <- tribble(
  ~doc_id,      ~text,
  "1015328_1999", "aaa aaa aaa.",
  "1015328_2000", "bbb bbb bbb.",
  "1015328_2003", "ccc ccc ccc.",
  "1015328_2004", "ddd ddd ddd.",
  "1015328_2005", "eee eee eee.",
  "1015328_2006", "fff fff fff.",
  "1015328_2006", "ggg ggg ggg.",
  "1015328_2006", "hhh hhh hhh.",
  "1015328_2006", "iii iii iii.",
  "1015328_2006", "jjj jjj jjj.",)

group_by(test, doc_id) %>% summarise(text = paste(text, collapse = " "))

Output:

# A tibble: 6 x 2
  doc_id       text
  <chr>        <chr>
1 1015328_1999 aaa aaa aaa.
2 1015328_2000 bbb bbb bbb.
3 1015328_2003 ccc ccc ccc.
4 1015328_2004 ddd ddd ddd.
5 1015328_2005 eee eee eee.
6 1015328_2006 fff fff fff. ggg ggg ggg. hhh hhh hhh. iii iii iii. jjj jjj jjj.


问:
How to make a custom view for the following layout?
I have several tiles in my home_activity.xml and I want to make a custom view for the tile so that I don't have to code every attribute for every tile independently.

Here is the code snippet for adding the components in every tile in the home activity which I want to make a custom view for. I have included examples of two such tiles.

```<code>                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="12dp"
                    android:clipToPadding="false"
                    android:gravity="center"
                    android:orientation="vertical"
                    app:layout_column="0"
                    android:paddingBottom="@dimen/home_card_elev"
                    app:layout_columnWeight="1"
                    app:layout_gravity="fill_horizontal"
                    app:layout_row="0">

                    <androidx.constraintlayout.widget.ConstraintLayout
                        android:id="@+id/contact_tracer_tile"
                        android:layout_width="150dp"
                        android:layout_height="match_parent"
                        android:background="@drawable/buttonback2"
                        android:clickable="true"
                        android:elevation="@dimen/home_card_elev"
                        app:layout_column="0"
                        app:layout_row="1">

                        <ImageButton
                            android:id="@+id/image_button3"
                            style="@android:style/Widget.Material.Light.ImageButton"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/imgbut_text3"
                            android:layout_alignParentStart="true"
                            android:layout_alignParentEnd="true"
                            android:layout_alignParentBottom="true"
                            android:layout_marginBottom="2dp"
                            android:background="#FFFFFF"
                            android:clickable="false"
                            android:contentDescription="Card Image"
                            app:layout_constraintBottom_toBottomOf="parent"
                            app:layout_constraintEnd_toEndOf="parent"
                            app:layout_constraintStart_toStartOf="parent"
                            app:layout_constraintTop_toBottomOf="@+id/imgbut_text3"
                            app:layout_constraintVertical_bias="0.0"
                            app:srcCompat="@drawable/ic_symptom_tracker" />

                        <TextView
                            android:id="@+id/imgbut_text3"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="4dp"
                            android:fontFamily="@font/mukta_semibold"
                            android:text="@string/social_distancing_tile"
                            android:textAlignment="center"
                            android:textColor="@color/blackcolor"
                            android:textSize="@dimen/home_card_font"
                            app:layout_constraintTop_toTopOf="parent" />

                    </androidx.constraintlayout.widget.ConstraintLayout>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="12dp"
                    android:clipToPadding="false"
                    android:gravity="center"
                    android:paddingBottom="@dimen/home_card_elev"
                    android:orientation="vertical"
                    app:layout_column="1"
                    app:layout_columnWeight="1"
                    app:layout_gravity="fill_horizontal"
                    app:layout_row="0">

                    <androidx.constraintlayout.widget.ConstraintLayout
                        android:id="@+id/onair_tile"
                        android:layout_width="150dp"
                        android:layout_height="match_parent"
                        android:background="@drawable/buttonback2"
                        android:clickable="true"
                        android:elevation="@dimen/home_card_elev"
                        app:layout_column="1"
                        app:layout_row="0">

                        <ImageButton
                            android:id="@+id/image_button4"
                            style="@android:style/Widget.Material.Light.ImageButton"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/imgbut_text4"
                            android:layout_alignParentStart="true"
                            android:layout_alignParentEnd="true"
                            android:layout_alignParentBottom="true"
                            android:layout_marginBottom="2dp"
                            android:background="#FFFFFF"
                            android:clickable="false"
                            android:contentDescription="Card Image"
                            app:layout_constraintBottom_toBottomOf="parent"
                            app:layout_constraintEnd_toEndOf="parent"
                            app:layout_constraintStart_toStartOf="parent"
                            app:layout_constraintTop_toBottomOf="@+id/imgbut_text4"
                            app:srcCompat="@drawable/ic_onair" />

                        <TextView
                            android:id="@+id/imgbut_text4"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="4dp"
                            android:fontFamily="@font/mukta_semibold"
                            android:text="@string/onair_tile"
                            android:textAlignment="center"
                            android:textColor="@color/blackcolor"
                            android:textSize="@dimen/home_card_font"
                            app:layout_constraintTop_toTopOf="parent" />

                    </androidx.constraintlayout.widget.ConstraintLayout>

                </LinearLayout>
</code>```

答:
try use include tag in home_activity.xml file (or where you need include).

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <include
        android:id="@+id/included_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        layout="@layout/include_tiles_layout"/>

</RelativeLayout>
</code>```

p.s] make mutiple includes.

for example, in home_activity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:padding="100dp"
    >
    <include
        android:id="@+id/include_layout"     <!-- 아이디 설정 가능 -->
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/custom_timeset"      <!-- xml을 적는데 주의점 android빼고 -->
        />
    <include
        android:id="@+id/include_layout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/custom_timeset"
        />
    <include
        android:id="@+id/include_layout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/custom_timeset"
        />
</LinearLayout>
</code>```

and in java file,

```<code>View include01 = findViewById(R.id.include_layout);
View include02 = findViewById(R.id.include_layout2);
View include03 = findViewById(R.id.include_layout3);

TextView tv1 = (TextView) include01.findViewById(R.id.txt_startTime);
TextView tv2 = (TextView) include01.findViewById(R.id.txt_endTime);
TextView tv3 = (TextView) include02.findViewById(R.id.txt_startTime);
TextView tv4 = (TextView) include02.findViewById(R.id.txt_endTime);
TextView tv5 = (TextView) include03.findViewById(R.id.txt_startTime);
TextView tv6 = (TextView) include03.findViewById(R.id.txt_endTime);
</code>```

this make sepearate views.

Body:
I have several tiles in my home_activity.xml and I want to make a custom view for the tile so that I don't have to code every attribute for every tile independently.

Here is the code snippet for adding the components in every tile in the home activity which I want to make a custom view for. I have included examples of two such tiles.

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="12dp"
                    android:clipToPadding="false"
                    android:gravity="center"
                    android:orientation="vertical"
                    app:layout_column="0"
                    android:paddingBottom="@dimen/home_card_elev"
                    app:layout_columnWeight="1"
                    app:layout_gravity="fill_horizontal"
                    app:layout_row="0">

                    <androidx.constraintlayout.widget.ConstraintLayout
                        android:id="@+id/contact_tracer_tile"
                        android:layout_width="150dp"
                        android:layout_height="match_parent"
                        android:background="@drawable/buttonback2"
                        android:clickable="true"
                        android:elevation="@dimen/home_card_elev"
                        app:layout_column="0"
                        app:layout_row="1">

                        <ImageButton
                            android:id="@+id/image_button3"
                            style="@android:style/Widget.Material.Light.ImageButton"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/imgbut_text3"
                            android:layout_alignParentStart="true"
                            android:layout_alignParentEnd="true"
                            android:layout_alignParentBottom="true"
                            android:layout_marginBottom="2dp"
                            android:background="#FFFFFF"
                            android:clickable="false"
                            android:contentDescription="Card Image"
                            app:layout_constraintBottom_toBottomOf="parent"
                            app:layout_constraintEnd_toEndOf="parent"
                            app:layout_constraintStart_toStartOf="parent"
                            app:layout_constraintTop_toBottomOf="@+id/imgbut_text3"
                            app:layout_constraintVertical_bias="0.0"
                            app:srcCompat="@drawable/ic_symptom_tracker" />

                        <TextView
                            android:id="@+id/imgbut_text3"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="4dp"
                            android:fontFamily="@font/mukta_semibold"
                            android:text="@string/social_distancing_tile"
                            android:textAlignment="center"
                            android:textColor="@color/blackcolor"
                            android:textSize="@dimen/home_card_font"
                            app:layout_constraintTop_toTopOf="parent" />

                    </androidx.constraintlayout.widget.ConstraintLayout>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="12dp"
                    android:clipToPadding="false"
                    android:gravity="center"
                    android:paddingBottom="@dimen/home_card_elev"
                    android:orientation="vertical"
                    app:layout_column="1"
                    app:layout_columnWeight="1"
                    app:layout_gravity="fill_horizontal"
                    app:layout_row="0">

                    <androidx.constraintlayout.widget.ConstraintLayout
                        android:id="@+id/onair_tile"
                        android:layout_width="150dp"
                        android:layout_height="match_parent"
                        android:background="@drawable/buttonback2"
                        android:clickable="true"
                        android:elevation="@dimen/home_card_elev"
                        app:layout_column="1"
                        app:layout_row="0">

                        <ImageButton
                            android:id="@+id/image_button4"
                            style="@android:style/Widget.Material.Light.ImageButton"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/imgbut_text4"
                            android:layout_alignParentStart="true"
                            android:layout_alignParentEnd="true"
                            android:layout_alignParentBottom="true"
                            android:layout_marginBottom="2dp"
                            android:background="#FFFFFF"
                            android:clickable="false"
                            android:contentDescription="Card Image"
                            app:layout_constraintBottom_toBottomOf="parent"
                            app:layout_constraintEnd_toEndOf="parent"
                            app:layout_constraintStart_toStartOf="parent"
                            app:layout_constraintTop_toBottomOf="@+id/imgbut_text4"
                            app:srcCompat="@drawable/ic_onair" />

                        <TextView
                            android:id="@+id/imgbut_text4"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="4dp"
                            android:fontFamily="@font/mukta_semibold"
                            android:text="@string/onair_tile"
                            android:textAlignment="center"
                            android:textColor="@color/blackcolor"
                            android:textSize="@dimen/home_card_font"
                            app:layout_constraintTop_toTopOf="parent" />

                    </androidx.constraintlayout.widget.ConstraintLayout>

                </LinearLayout>

Body:
try use include tag in home_activity.xml file (or where you need include).

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <include
        android:id="@+id/included_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        layout="@layout/include_tiles_layout"/>

</RelativeLayout>

p.s] make mutiple includes.

for example, in home_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:padding="100dp"
    >
    <include
        android:id="@+id/include_layout"     <!-- 아이디 설정 가능 -->
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/custom_timeset"      <!-- xml을 적는데 주의점 android빼고 -->
        />
    <include
        android:id="@+id/include_layout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/custom_timeset"
        />
    <include
        android:id="@+id/include_layout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/custom_timeset"
        />
</LinearLayout>

and in java file,

View include01 = findViewById(R.id.include_layout);
View include02 = findViewById(R.id.include_layout2);
View include03 = findViewById(R.id.include_layout3);

TextView tv1 = (TextView) include01.findViewById(R.id.txt_startTime);
TextView tv2 = (TextView) include01.findViewById(R.id.txt_endTime);
TextView tv3 = (TextView) include02.findViewById(R.id.txt_startTime);
TextView tv4 = (TextView) include02.findViewById(R.id.txt_endTime);
TextView tv5 = (TextView) include03.findViewById(R.id.txt_startTime);
TextView tv6 = (TextView) include03.findViewById(R.id.txt_endTime);

this make sepearate views.


问:
Password encryption Python Flask
Currently I'm working on a project where I made a registration form which is connected to a MySQL database. The project is written in Python with Flask.

I have figured out how send information to the DB, and how to hash the passwords chosen on the registerpage. However, I'm struggling to find out how to log in with an account with an hashed password.

If I try to log in with an account with a hashed password, I first need to login with the unhashed password, which is then hashed, and compared to the hashed password in the database.
But this doesn't work.

From my understanding, this is where you find the username and password, which are filled out on the login page:

```<code>username = request.form['username']
password = request.form['password']
</code>```

So, after this step you should encrypt it to match the hashed password in the DB:

```<code>password = b'password'

hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
</code>```

Then, you should compare it:

```<code>if bcrypt.checkpw(password, hashed_password):
    print("It matches!")
    return redirect(url_for('home'))
else:
    print("Didn't match")
</code>```

But this is not working. I can't log in with the given password, only with a hashed password. Where is the mistake made in the encryption? Full snippet code:

```<code>def login():
# Output message if something goes wrong...
msg = ''

# Check if "username" and "password" POST requests exist (user submitted form)
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
    # Create variables for easy access
    username = request.form['username']
    password = request.form['password']

    password = b'password'

    hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())

    # Check if account exists using MySQL
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s', (username, hashed_password))
    # Fetch one record and return result
    account = cursor.fetchone()
    # If account exists in accounts table in our database
    if account:
        # Create session data, we can access this data in other routes
        session['loggedin'] = True
        session['id'] = account['id']
        session['username'] = account['username']
        # Redirect to home page
        return redirect(url_for('home'))
    else:
        # Account doesnt exist or username/password incorrect
        msg = 'Incorrect username/password!'
# Show the login form with message (if any)
return render_template('index.html', msg=msg)
</code>```

答:
As you are using MySQL, I would suggest you rather use md5 to verify the user from the table in the database.
Change the following code:

```<code>cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = md5(%s)', (username, hashed_password))
</code>```

and to convert all the unencrypted plain texts password run following query:

```<code>UPDATE accounts SET password = MD5(password);
</code>```

Title: Password encryption Python Flask

Body:
Currently I'm working on a project where I made a registration form which is connected to a MySQL database. The project is written in Python with Flask.

I have figured out how send information to the DB, and how to hash the passwords chosen on the registerpage. However, I'm struggling to find out how to log in with an account with an hashed password.

If I try to log in with an account with a hashed password, I first need to login with the unhashed password, which is then hashed, and compared to the hashed password in the database.
But this doesn't work.

From my understanding, this is where you find the username and password, which are filled out on the login page:

username = request.form['username']
password = request.form['password']

So, after this step you should encrypt it to match the hashed password in the DB:

password = b'password'

hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())

Then, you should compare it:

if bcrypt.checkpw(password, hashed_password):
    print("It matches!")
    return redirect(url_for('home'))
else:
    print("Didn't match")

But this is not working. I can't log in with the given password, only with a hashed password. Where is the mistake made in the encryption? Full snippet code:

def login():
# Output message if something goes wrong...
msg = ''

# Check if "username" and "password" POST requests exist (user submitted form)
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
    # Create variables for easy access
    username = request.form['username']
    password = request.form['password']

    password = b'password'

    hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())

    # Check if account exists using MySQL
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s', (username, hashed_password))
    # Fetch one record and return result
    account = cursor.fetchone()
    # If account exists in accounts table in our database
    if account:
        # Create session data, we can access this data in other routes
        session['loggedin'] = True
        session['id'] = account['id']
        session['username'] = account['username']
        # Redirect to home page
        return redirect(url_for('home'))
    else:
        # Account doesnt exist or username/password incorrect
        msg = 'Incorrect username/password!'
# Show the login form with message (if any)
return render_template('index.html', msg=msg)

Body:
As you are using MySQL, I would suggest you rather use md5 to verify the user from the table in the database.
Change the following code:

cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = md5(%s)', (username, hashed_password))

and to convert all the unencrypted plain texts password run following query:

UPDATE accounts SET password = MD5(password);


问:
Simulating the number of contract to maintain constant value
I have a set of say 10,000 contracts ( Loan account numbers). The contracts are for specific durations say 24,48,84 months. My pool consists of a mix of these contracts for a different duration. Assume that at the start of this month I have 100 contracts amounting to 10,000 USD . After 2 months a few accounts/contracts are closed prematurely (early pay off) and few are extended. I need to simulate the data to maintain a constant value (amount of 10,000 USD). It means I need to know how many new contracts that I need to add say 2 months from now so that the value of my portfolio remains at 10,000 USD. Can someone help me if there is any technique to simulate this? Preferably in R, Python or SAS

答:
Add a payoff date element to each contract object. Then, do:</p>

```<code>need = 0
for c in contracts:
    need += int( (date today + 2 mo) > c.payoff_date or c.paid_off == True)
print 10000 - len(contracts) + need
</code>```

Body:
Add a payoff date element to each contract object. Then, do:

need = 0
for c in contracts:
    need += int( (date today + 2 mo) > c.payoff_date or c.paid_off == True)
print 10000 - len(contracts) + need


问:
ERROR: extra data after last expected column in postgres table
I am working on a project where I need to create a new table, then import data from a CSV. I've read many similar questions ("extra data after last expected column") and answers on StackOverflow, but I still haven't found the culprit.

```<code>CREATE TABLE colleges2014_15 (
unitid integer,
intsnm text,
city text,
stabbr text,
zip_clean char,
control integer,
latitude float,
longitude float,
tutionfee_in float,
tuitionfee_out float,
pctpell float,
inc_pct_lo float,
dep_stat_pct_ind float,
dep_debt_mdn float,
ind_debt_mdn float,
pell_debt_mdn float,
ugds_men float,
ubds_women float,
locale integer,
PRIMARY KEY(unitid)
);
</code>```

The table is created successfully with the 19 different columns. Then I go try to import the data into the new table.

```<code>COPY colleges2014_15(
unitid,
intsnm,
city,
stabbr,
zip_clean,
control,
latitude,
longitude,
tutionfee_in,
tuitionfee_out,
pctpell,
inc_pct_lo,
dep_stat_pct_ind,
dep_debt_mdn,
ind_debt_mdn,
pell_debt_mdn,
ugds_men,
ubds_women,
locale
)
FROM '/Users/compose/Downloads/CollegeScorecard_Raw_Data x/MERGED2014_15_cleaned.csv' CSV HEADER
;
</code>```

And I get the error message. I've done the following in the CSV:

Made sure it's saved as UTF-8 CSV (working on a Mac)

Already cleaned out all commas in every row

Cleaned out all NULL values

Confirmed that all the data types (integer, float, text, etc.) are correct

I've tried to simply COPY only the first column, unitid; it failed. I've tried importing only the second column (intsnm) and it failed with the same error.

The full error message when trying to COPY over all 19 columns is as follows:

An error occurred when executing the SQL command: COPY
  colleges2014_15( unitid,  intsnm,  city,  stabbr,  zip_clean,
  control,  latitude,  longitude,  tutionfee_in,  tuitionfee_out,
  pctpell, inc_pct_...

ERROR: extra data after last expected column   Where: COPY
  colleges2014_15, line 2: "100654,Alabama A & M
  University,Normal,AL,35762,35762,1,34.783368,-86.568502,9096,16596,0.7356,0.651..."
  1 statement failed.

Execution time: 0.03s

The full error message when trying to copy simply the first column only is:

An error occurred when executing the SQL command: COPY
  colleges2014_15( unitid ) FROM
  '/Users/compose/Downloads/CollegeScorecard_Raw_Data
  x/MERGED2014_15_cleaned.csv' CSV HEADER

ERROR: extra data after last expected column   Where: COPY
  colleges2014_15, line 2: "100654,Alabama A & M
  University,Normal,AL,35762,35762,1,34.783368,-86.568502,9096,16596,0.7356,0.651..."
  1 statement failed.

Execution time: 0.01s

Hugely appreciate any help.

答:
It took me a while to figure out what was wrong searching on the error so have posted my problem to help others. My issue was inexperience with pgAdmin as
pgAdmin requires the table to be created WITH columns before the data is imported. I had expected that the headers would be used from the .csv file, most other packages I have used worked this way.

If you are working with a GIS system using PostGIS there is an easy solution. I am using QGIS 3.4, with Postgres and PostGIS installed.

In QGIS

    Select Database menu option

    Select DBManager

    On left - choose location for table
    Select Import Layer/File
    On the next window select the following

        Input - choose file

        Table - enter table name

        OK

Body:
I am working on a project where I need to create a new table, then import data from a CSV. I've read many similar questions ("extra data after last expected column") and answers on StackOverflow, but I still haven't found the culprit.

CREATE TABLE colleges2014_15 (
unitid integer,
intsnm text,
city text,
stabbr text,
zip_clean char,
control integer,
latitude float,
longitude float,
tutionfee_in float,
tuitionfee_out float,
pctpell float,
inc_pct_lo float,
dep_stat_pct_ind float,
dep_debt_mdn float,
ind_debt_mdn float,
pell_debt_mdn float,
ugds_men float,
ubds_women float,
locale integer,
PRIMARY KEY(unitid)
);

The table is created successfully with the 19 different columns. Then I go try to import the data into the new table.

COPY colleges2014_15(
unitid,
intsnm,
city,
stabbr,
zip_clean,
control,
latitude,
longitude,
tutionfee_in,
tuitionfee_out,
pctpell,
inc_pct_lo,
dep_stat_pct_ind,
dep_debt_mdn,
ind_debt_mdn,
pell_debt_mdn,
ugds_men,
ubds_women,
locale
)
FROM '/Users/compose/Downloads/CollegeScorecard_Raw_Data x/MERGED2014_15_cleaned.csv' CSV HEADER
;

And I get the error message. I've done the following in the CSV:

Made sure it's saved as UTF-8 CSV (working on a Mac)

Already cleaned out all commas in every row

Cleaned out all NULL values

Confirmed that all the data types (integer, float, text, etc.) are correct

I've tried to simply COPY only the first column, unitid; it failed. I've tried importing only the second column (intsnm) and it failed with the same error.

The full error message when trying to COPY over all 19 columns is as follows:

An error occurred when executing the SQL command: COPY
  colleges2014_15( unitid,  intsnm,  city,  stabbr,  zip_clean,
  control,  latitude,  longitude,  tutionfee_in,  tuitionfee_out,
  pctpell, inc_pct_...

ERROR: extra data after last expected column   Where: COPY
  colleges2014_15, line 2: "100654,Alabama A & M
  University,Normal,AL,35762,35762,1,34.783368,-86.568502,9096,16596,0.7356,0.651..."
  1 statement failed.

Execution time: 0.03s

The full error message when trying to copy simply the first column only is:

An error occurred when executing the SQL command: COPY
  colleges2014_15( unitid ) FROM
  '/Users/compose/Downloads/CollegeScorecard_Raw_Data
  x/MERGED2014_15_cleaned.csv' CSV HEADER

ERROR: extra data after last expected column   Where: COPY
  colleges2014_15, line 2: "100654,Alabama A & M
  University,Normal,AL,35762,35762,1,34.783368,-86.568502,9096,16596,0.7356,0.651..."
  1 statement failed.

Execution time: 0.01s

Hugely appreciate any help.


问:
How to update slice of struct in recursive fashion
For following code, I'm expecting output of {"NewName" [{"NewName" []}]} but it's not updating child structs. How can we make sure it updates every struct in hierarchy.

```<code>package main

import (
    "fmt"
)

type red struct {
    Name string
    Child []red
}

func (r *red) setName(nameString string){
    r.Name = nameString
    for _, child := range r.Child{
        child.setName(nameString)
    }
}

func main() {
    obj := red{Name:"NameA",Child:[]red{red{Name: "NameB"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("NewName")
    //Expectation {"NewName" [{"NewName" []}]}
    fmt.Print(obj)
}
</code>```

答:
You need not to use pointers everywhere as suggested by others answers.

The problem in your code is that when you iterate the child, you get a value by copy for each item, you then set the name on the copy.

But as you do not copy back the modified value into the slice, the changes are not retained.

```<code>package main

import (
    "fmt"
)

type red struct {
    Name  string
    Child []red
}

func (r *red) setName(s string) {
    r.Name = s
    for i, ch := range r.Child {
        ch.setName(s) // ch is not a ptr to r.Child[i], it is a value copy
        r.Child[i] = ch // so you must re assign the copy into the slice!
    }
}

func main() {
    obj := red{Name: "A", Child: []red{red{Name: "B"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("X")
    //Expectation {X [{X []}]}
    fmt.Print(obj)
}
</code>```

Body:
For following code, I'm expecting output of {"NewName" [{"NewName" []}]} but it's not updating child structs. How can we make sure it updates every struct in hierarchy.

package main

import (
    "fmt"
)

type red struct {
    Name string
    Child []red
}

func (r *red) setName(nameString string){
    r.Name = nameString
    for _, child := range r.Child{
        child.setName(nameString)
    }
}

func main() {
    obj := red{Name:"NameA",Child:[]red{red{Name: "NameB"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("NewName")
    //Expectation {"NewName" [{"NewName" []}]}
    fmt.Print(obj)
}

Body:
You need not to use pointers everywhere as suggested by others answers.

The problem in your code is that when you iterate the child, you get a value by copy for each item, you then set the name on the copy.

But as you do not copy back the modified value into the slice, the changes are not retained.

package main

import (
    "fmt"
)

type red struct {
    Name  string
    Child []red
}

func (r *red) setName(s string) {
    r.Name = s
    for i, ch := range r.Child {
        ch.setName(s) // ch is not a ptr to r.Child[i], it is a value copy
        r.Child[i] = ch // so you must re assign the copy into the slice!
    }
}

func main() {
    obj := red{Name: "A", Child: []red{red{Name: "B"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("X")
    //Expectation {X [{X []}]}
    fmt.Print(obj)
}


问:
When is the gcc flag -nostartfiles used?
I can't seem to figure out the purpose of the flag -nostartfiles.  It prevents main() from being called immediately, and typically you'd also specify the program entry point.  However, why would I want to do that?  I have written a kernel that required it, since everything was up to me to get started, but other than that, is there a non-OS reason to specify a different program entry point?

答:
I think that with -nostartfiles command line arguments will not be passed to main() and environment variables will not be available to the executable, among other things. Docker uses -nostartfiles in an example where a single binary is run within a simple container, i.e., where the container is run like a single binary: https://docs.docker.com/develop/develop-images/baseimages/, so that is another use case.

Slightly related is Source for 'startup files' in gcc/mingw, which lists functions that are linked into to the code if -nostartfiles option is not used.


问:
split a string on newlines in .NET
I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?</p>

答:
Based on Guffa's answer, in an extension class, use:</p>

```<code>public static string[] Lines(this string source) {
    return source.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}
</code>```

Title: split a string on newlines in .NET

Body:
Based on Guffa's answer, in an extension class, use:

public static string[] Lines(this string source) {
    return source.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}


问:
Can NSInputStream be used to read chunks of data with offset to be able to upload large files
I’d like to know if there is a way to use NSInputStream to read chunk of data with some offset. For example there is a file with size 100MB, I need chunks with size of 10MB but I need the 5th chunk before the 1st chunk.

The goal is to be able to upload large files to a server. The backend expects chunks of data, that can be sent at once. The idea is to use NSOperationQueue and to set maxConcurrentOperationCount to 5 for example. Each of the tasks will need different chunk to send. I know about - (NSData *)subdataWithRange:(NSRange)range - but this will require the whole NSData to be in the memory all the time. Which won’t work with large files, so I’d prefer to use NSInputStream. Can the chunks be read out of order with NSInputStream and how or should another approach be used?

答: You can open file-based NSInputStream and then specify required offset using NSStreamFileCurrentOffsetKey property. At the same time, in case of implementing upload upon NSURLRequiest with NSInputStream inside, the size of the chunk is not under your control. Its value hardcoded in CFNetworking framework.


问:
Wagtail: How to validate m2m inline model?
I have a custom form inheriting from WagtailAdminPageForm and I want to validate an m2m model field (ClusterableModel). Right now I am using the clean() method on my form class.

```<code>def clean(self):
    cleaned_data = super().clean()
    my_field_total_sum = 0
    for form in self.formsets['my_field'].forms:

        if form.is_valid():
            cleaned_form_data = form.clean()
            my_field_total_sum += cleaned_form_data.get('my_value')

            if total_sum > 100:
                form.add_error('my_value', 'More then 100 is not allowed')

    return cleaned_data
</code>```

This works fine until I add and/or remove some inline panels in the admin interface and save my page as a draft and try to validate again. Because self.formsets['my_field'].forms still contains already removed forms and never gets reset to the actual amount of inline panels in the admin.

So, is it possible to (re-)set self.formsets['my_field'].forms to the actual amount inline panels visible in the admin interface? Or should I validate elsewhere anyways?

答:
After more digging I found the answer. Checking for the "DELETE" key in a  forms cleaned_data dict is the key. So my clean method from above needs to look like this:

```<code>def clean(self):
    cleaned_data = super().clean()
    my_field_total_sum = 0
    for form in self.formsets['my_field'].forms:

        # simply check, if "DELETE" is not true
        if form.is_valid() and not form.cleaned_data.get("DELETE"):
            cleaned_form_data = form.clean()
            my_field_total_sum += cleaned_form_data.get('my_value')

    # this check needs to be outside the loop ;-)
    if my_field_total_sum > 100:
        form.add_error('my_value', 'More then 100 is not allowed')

    return cleaned_data
</code>```

Body:
I have a custom form inheriting from WagtailAdminPageForm and I want to validate an m2m model field (ClusterableModel). Right now I am using the clean() method on my form class.

def clean(self):
    cleaned_data = super().clean()
    my_field_total_sum = 0
    for form in self.formsets['my_field'].forms:

        if form.is_valid():
            cleaned_form_data = form.clean()
            my_field_total_sum += cleaned_form_data.get('my_value')

            if total_sum > 100:
                form.add_error('my_value', 'More then 100 is not allowed')

    return cleaned_data

This works fine until I add and/or remove some inline panels in the admin interface and save my page as a draft and try to validate again. Because self.formsets['my_field'].forms still contains already removed forms and never gets reset to the actual amount of inline panels in the admin.

So, is it possible to (re-)set self.formsets['my_field'].forms to the actual amount inline panels visible in the admin interface? Or should I validate elsewhere anyways?

Body:
After more digging I found the answer. Checking for the "DELETE" key in a  forms cleaned_data dict is the key. So my clean method from above needs to look like this:

def clean(self):
    cleaned_data = super().clean()
    my_field_total_sum = 0
    for form in self.formsets['my_field'].forms:

        # simply check, if "DELETE" is not true
        if form.is_valid() and not form.cleaned_data.get("DELETE"):
            cleaned_form_data = form.clean()
            my_field_total_sum += cleaned_form_data.get('my_value')

    # this check needs to be outside the loop ;-)
    if my_field_total_sum > 100:
        form.add_error('my_value', 'More then 100 is not allowed')

    return cleaned_data


问:
How can I keep output shown in the IPython notebook?
I have a Jupyter notebook that runs correctly. I want to keep the output cell inside of the notebook to see output without running again. I noticed that when I run the notebook cell by cell, it doesn’t show out[] after each In[] cell.

How can I have an save my notebook in a way that all outputs show without re-running?

Thank You.

答:
Thanks, but even for this small example, I don’t have out[] structure when I run the cell.

In my case, I want to show my output for diagrams inside of the notebook.
I used figure.show() or display(figure), I can see the result but every time I open the notebook I should run again to see the figures, otherwise, it's a white cell in output.


问:
MS ACCESS 2010 - trying to write a query to avoid duplication in a linking table
This is my first question so I'm going to be very thorough. Bear with me.

I am building a database for beers and have created a linking table that allows me to suggest similar beers (either by taste or some other quality). The original table uses beerID as the primary key and in the linking table I've created a composite primary key from the foreign keys beerID1 and beerID2 by loading in the beerID twice. It's working well so far, except that when I select:

beerID1 = Dechutes IPA, beerID2 = Rogue IPA

-and then in another row-

beerID1 = Rogue IPA, beerID2 = Dechutes IPA

As you can see I have a problem with duplicate data and I'm not too familiar with SQL to get down to the nitty gritty in how to fix this. Any ideas that a layman can use? I'm thinking of some form of validation or query... but can't seem to navigate too far along.

答:
You actually want to normalise that a little more. Check out http://en.wikipedia.org/wiki/First_normal_form

I think what your are doing is:

```<code>Beer
BeerID  BeerName  BeerManufacturer
------  --------  ----------------
1       Beer1     Brewer 1
2       Beer2     Brewer 1
3       Beer3     Brewer 2
4       Beer4     Brewer 3

AltBeer
AltBeerID  BeerID  BeerID1  BeerID2  BeerID3
---------  ------  -------  -------  -------
1          1       3        4
2          2       5
3          4       7
</code>```

Instead you want to have just one column for Alternate Beers. In this case, AltBeer becomes

```<code>AltBeer
AltBeerID  BeerID  AltBeer
---------  ------  -------
1          1       3
1          1       4
2          2       5
3          4       7
</code>```

Then doing a join on Beer and AltBeer (based on BeerID) will give you a list of BeersID that are similar to the original beer. You can the details of the Alternate beers by joining with Beer again (based on BeerID and AltBeer)

```<code>SELECT beer.beermanufacturer,
       beer.beername,
       beer_1.beername         AS recbeer,
       beer_1.beermanufacturer AS recbeerman
FROM   (altbeer
       INNER JOIN beer
         ON altbeer.beerid = beer.beerid)
       INNER JOIN beer AS beer_1
         ON altbeer.altbeer = beer_1.beerid;
</code>```

The result being something like this (no dups, guarenteed)

```<code>BeerName    BeerManufacturer   RecBeer     RecBeerMan
--------    ----------------   -------     -----------
Beer1       BeerMan1           Beer3       BeerMan2
Beer1       BeerMan1           Beer4       BeerMan3
</code>```

(Of course, if we were normalising this all correctly, we've also split Beer Manufacturer into its own table since there's a many-to-1 relationship between beer and manufacturer.)

Body:
You actually want to normalise that a little more. Check out http://en.wikipedia.org/wiki/First_normal_form

I think what your are doing is:

Beer
BeerID  BeerName  BeerManufacturer
------  --------  ----------------
1       Beer1     Brewer 1
2       Beer2     Brewer 1
3       Beer3     Brewer 2
4       Beer4     Brewer 3

AltBeer
AltBeerID  BeerID  BeerID1  BeerID2  BeerID3
---------  ------  -------  -------  -------
1          1       3        4
2          2       5
3          4       7

Instead you want to have just one column for Alternate Beers. In this case, AltBeer becomes

AltBeer
AltBeerID  BeerID  AltBeer
---------  ------  -------
1          1       3
1          1       4
2          2       5
3          4       7

Then doing a join on Beer and AltBeer (based on BeerID) will give you a list of BeersID that are similar to the original beer. You can the details of the Alternate beers by joining with Beer again (based on BeerID and AltBeer)

SELECT beer.beermanufacturer,
       beer.beername,
       beer_1.beername         AS recbeer,
       beer_1.beermanufacturer AS recbeerman
FROM   (altbeer
       INNER JOIN beer
         ON altbeer.beerid = beer.beerid)
       INNER JOIN beer AS beer_1
         ON altbeer.altbeer = beer_1.beerid;

The result being something like this (no dups, guarenteed)

BeerName    BeerManufacturer   RecBeer     RecBeerMan
--------    ----------------   -------     -----------
Beer1       BeerMan1           Beer3       BeerMan2
Beer1       BeerMan1           Beer4       BeerMan3

(Of course, if we were normalising this all correctly, we've also split Beer Manufacturer into its own table since there's a many-to-1 relationship between beer and manufacturer.)


问:
Jaspersoft : use UUID in mongoDB query (filter by id)
I try to make a findQuery for mongoDB in jaspersoft studio but when I try to use a UUID in the process, I always have 0 results.

Example query :

```<code>{
  'collectionName' : 'Orders',
  'findQuery' : {
    "_id" :  UUID("4925b1a6-5cd6-6d19-9f2a-7a0083a7bb9a")
  }
}
</code>```

Is there something wrong in my query in your opinion ?

Thanks for your help

答:
I found how to use a UUID in a mongo query.

You should first convert your UUID in base64, to do so I used 2 online converters, the first one gave me the 12 first base64 caracters, the second one the 12 last

(yes, this is strange).

To give you a concrete example :

Basic UUID : 41e73145-2489-54e1-d2fc-d400bea5e9b1

Site 1 https://www.fileformat.info/tool/guid-base64.htm : QecxRSSJVOHS/AAA1AC+pQ

Site 2 https://toolslick.com/conversion/data/guid : RTHnQYkk4VTS/NQAvqXpsQ==

Final base64 result :  QecxRSSJVOHS/NQAvqXpsQ==

Then to use it in Jasper, you'll need this syntax :

_id: new BinData(4,"QecxRSSJVOHS/NQAvqXpsQ==")

Body:
I try to make a findQuery for mongoDB in jaspersoft studio but when I try to use a UUID in the process, I always have 0 results.

Example query :

{
  'collectionName' : 'Orders',
  'findQuery' : {
    "_id" :  UUID("4925b1a6-5cd6-6d19-9f2a-7a0083a7bb9a")
  }
}

Is there something wrong in my query in your opinion ?

Thanks for your help


问:
Python: 'object in list' checks and '__cmp__' overflow
this is my first time at stack overflow so I'm sorry if the format doesn't fit quite right with the site.
I just recently started learning programming, almost 2 weeks have passed since.  I'm learning python from http://openbookproject.net/thinkcs/python/english3e/index.html  and everything had been quite nice until now, where I just got stuck for hours.
I googled a lot but couldn't find a proper solution to my problem so here I am.

I'm trying to get the OldMaidGame() run without problems as explained on CH17. http://openbookproject.net/thinkcs/python/english3e/ch17.html
- Most of the code also comes from the previous chapter.

What I've found out is I can't get the Deck.remove, Hand.remove_matches, or any other kind of remove function to work.  After some debugging I found out
that the problem occurs when the program checks if the given card is present in the deck/hand/etc.  It can't ever make a match.  Then after some looking back on
the chapter, (in ch16), I found out that 'if card in deck/hand/etc: remove(card)' etc looks up the .cmp() of the object to determine if the card actually exists in the deck/hand/etc.  This is my version of the cmp after doing the additions for 'ace's on the given code from the e-book.

```<code>def __cmp__(self, other):
    """ Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
    # check the suits
    if self.suit > other.suit: return 1
    if self.suit < other.suit: return -1
    # suits are the same... check ranks
    # check for aces first.
    if self.rank == 1 and other.rank == 1: return 0
    if self.rank == 1 and other.rank != 1: return 1
    if self.rank != 1 and other.rank == 1: return -1
    # check for non-aces.
    if self.rank > other.rank: return 1
    if self.rank < other.rank: return -1
    # ranks are the same... it's a tie
    return 0
</code>```

The cmp itself seems fine afaik, ofc I could use some tips on how to make it better (like with ace checks).
So I have no idea why the card in deck/hand checks always return false.
This was the given remove function:

```<code>class Deck:
    ...
    def remove(self, card):
        if card in self.cards:
            self.cards.remove(card)
            return True
        else:
            return False
</code>```

Desperately trying to get it to work, I came up with this:

```<code>class Deck:
    ...
    def remove(self, card):
        """ Removes the card from the deck, returns true if successful """
        for lol in self.cards:
            if lol.__cmp__(card) == 0:
                self.cards.remove(lol)
                return True
        return False
</code>```

Seemed to work fine, until I moved on to the other non-working remove functions:

```<code>class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            if match in self.cards:
                self.cards.remove(card)
                self.cards.remove(match)
                print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                count = count + 1
        return count
</code>```

I again made some adjustments:

```<code>class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            for lol in self.cards:
                if lol.__cmp__(match) == 0:
                    self.cards.remove(card)
                    self.cards.remove(match)
                    print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                    count = count + 1
        return count
</code>```

The removing worked fine for the card, but it would give an error (x not in list) when I tried to remove match.  Another our or so, I might've been able to make that work too, but since it already feels like I'm on the wrong road since I can't fix the original 'card in deck/hand/etc' etc, I came here looking for some answers/tips.

Thanks for reading and I greatly appreciate any help you can give :)

--------------------- EDIT 1 *>

This is my current code:
http://pastebin.com/g77Y4Tjr

--------------------- EDIT 2 *>

I've tried every single cmp advised here, and I still can't get it to find a card with 'in'.

```<code>>>> a = Card(0, 5)
>>> b = Card(0, 1)
>>> c = Card(3, 1)
>>> hand = Hand('Baris')
>>> hand.add(a)
>>> hand.add(b)
>>> hand.add(c)
>>> d = Card(3, 1)
>>> print(hand)
Hand Baris contains
5 of Clubs
 Ace of Clubs
  Ace of Spades
>>> d in hand.cards
False
>>>
</code>```

I've also tried the card.py @DSM has used successfully, and I get errors there too, like at the sort function it says it cant compare the two card objects.

So I was wondering, maybe it is a problem with Python 3.2, or maybe the syntax has changed somewhere?

答:
I can't seem to reproduce the problem with not being able to remove cards via Deck.remove.  If I start with the card.py at the thinkpython site and add the remove function you've posted up there, it seems to work:

```<code>>>> deck = Deck()
>>> str(deck).split('\n')
['Ace of Clubs', '2 of Clubs', '3 of Clubs', '4 of Clubs', '5 of Clubs', '6 of Clubs', '7 of Clubs', '8 of Clubs', '9 of Clubs', '10 of Clubs', 'Jack of Clubs', 'Queen of Clubs', 'King of Clubs', 'Ace of Diamonds', '2 of Diamonds', '3 of Diamonds', '4 of Diamonds', '5 of Diamonds', '6 of Diamonds', '7 of Diamonds', '8 of Diamonds', '9 of Diamonds', '10 of Diamonds', 'Jack of Diamonds', 'Queen of Diamonds', 'King of Diamonds', 'Ace of Hearts', '2 of Hearts', '3 of Hearts', '4 of Hearts', '5 of Hearts', '6 of Hearts', '7 of Hearts', '8 of Hearts', '9 of Hearts', '10 of Hearts', 'Jack of Hearts', 'Queen of Hearts', 'King of Hearts', 'Ace of Spades', '2 of Spades', '3 of Spades', '4 of Spades', '5 of Spades', '6 of Spades', '7 of Spades', '8 of Spades', '9 of Spades', '10 of Spades', 'Jack of Spades', 'Queen of Spades', 'King of Spades']
>>> len(deck.cards)
52
>>> c = Card(suit=0, rank=8)
>>> str(c)
'8 of Clubs'
>>> c in deck.cards
True
>>> deck.remove(c)
True
>>> len(deck.cards)
51
>>> c in deck.cards
False
>>> str(deck).split('\n')
['Ace of Clubs', '2 of Clubs', '3 of Clubs', '4 of Clubs', '5 of Clubs', '6 of Clubs', '7 of Clubs', '9 of Clubs', '10 of Clubs', 'Jack of Clubs', 'Queen of Clubs', 'King of Clubs', 'Ace of Diamonds', '2 of Diamonds', '3 of Diamonds', '4 of Diamonds', '5 of Diamonds', '6 of Diamonds', '7 of Diamonds', '8 of Diamonds', '9 of Diamonds', '10 of Diamonds', 'Jack of Diamonds', 'Queen of Diamonds', 'King of Diamonds', 'Ace of Hearts', '2 of Hearts', '3 of Hearts', '4 of Hearts', '5 of Hearts', '6 of Hearts', '7 of Hearts', '8 of Hearts', '9 of Hearts', '10 of Hearts', 'Jack of Hearts', 'Queen of Hearts', 'King of Hearts', 'Ace of Spades', '2 of Spades', '3 of Spades', '4 of Spades', '5 of Spades', '6 of Spades', '7 of Spades', '8 of Spades', '9 of Spades', '10 of Spades', 'Jack of Spades', 'Queen of Spades', 'King of Spades']
</code>```

It seems to work if I replace the __cmp__ by yours, too:

```<code>>>> deck = Deck()
>>> c = Card(suit=0,rank=1)
>>> c in deck.cards
True
>>> deck.remove(c)
True
>>> len(deck.cards)
51
</code>```

So something must be different.  Could you dump your entire code -- and some code demonstrating the bug -- somewhere (pastebin, gist, etc.)?

(FWIW, my ace-over-king cmp looks like this:

```<code>def __cmp__(self, other):
    def aceshigh(r): return 14 if r==1 else r
    t1 = self.suit, aceshigh(self.rank)
    t2 = other.suit, aceshigh(other.rank)
    return cmp(t1, t2)
</code>```

Exercise: remove the magic numbers.)

Body:
this is my first time at stack overflow so I'm sorry if the format doesn't fit quite right with the site.
I just recently started learning programming, almost 2 weeks have passed since.  I'm learning python from http://openbookproject.net/thinkcs/python/english3e/index.html  and everything had been quite nice until now, where I just got stuck for hours.
I googled a lot but couldn't find a proper solution to my problem so here I am.

I'm trying to get the OldMaidGame() run without problems as explained on CH17. http://openbookproject.net/thinkcs/python/english3e/ch17.html
- Most of the code also comes from the previous chapter.

What I've found out is I can't get the Deck.remove, Hand.remove_matches, or any other kind of remove function to work.  After some debugging I found out
that the problem occurs when the program checks if the given card is present in the deck/hand/etc.  It can't ever make a match.  Then after some looking back on
the chapter, (in ch16), I found out that 'if card in deck/hand/etc: remove(card)' etc looks up the .cmp() of the object to determine if the card actually exists in the deck/hand/etc.  This is my version of the cmp after doing the additions for 'ace's on the given code from the e-book.

def __cmp__(self, other):
    """ Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
    # check the suits
    if self.suit > other.suit: return 1
    if self.suit < other.suit: return -1
    # suits are the same... check ranks
    # check for aces first.
    if self.rank == 1 and other.rank == 1: return 0
    if self.rank == 1 and other.rank != 1: return 1
    if self.rank != 1 and other.rank == 1: return -1
    # check for non-aces.
    if self.rank > other.rank: return 1
    if self.rank < other.rank: return -1
    # ranks are the same... it's a tie
    return 0

The cmp itself seems fine afaik, ofc I could use some tips on how to make it better (like with ace checks).
So I have no idea why the card in deck/hand checks always return false.
This was the given remove function:

class Deck:
    ...
    def remove(self, card):
        if card in self.cards:
            self.cards.remove(card)
            return True
        else:
            return False

Desperately trying to get it to work, I came up with this:

class Deck:
    ...
    def remove(self, card):
        """ Removes the card from the deck, returns true if successful """
        for lol in self.cards:
            if lol.__cmp__(card) == 0:
                self.cards.remove(lol)
                return True
        return False

Seemed to work fine, until I moved on to the other non-working remove functions:

class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            if match in self.cards:
                self.cards.remove(card)
                self.cards.remove(match)
                print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                count = count + 1
        return count

I again made some adjustments:

class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            for lol in self.cards:
                if lol.__cmp__(match) == 0:
                    self.cards.remove(card)
                    self.cards.remove(match)
                    print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                    count = count + 1
        return count

The removing worked fine for the card, but it would give an error (x not in list) when I tried to remove match.  Another our or so, I might've been able to make that work too, but since it already feels like I'm on the wrong road since I can't fix the original 'card in deck/hand/etc' etc, I came here looking for some answers/tips.

Thanks for reading and I greatly appreciate any help you can give :)

--------------------- EDIT 1 *>

This is my current code:
http://pastebin.com/g77Y4Tjr

--------------------- EDIT 2 *>

I've tried every single cmp advised here, and I still can't get it to find a card with 'in'.

>>> a = Card(0, 5)
>>> b = Card(0, 1)
>>> c = Card(3, 1)
>>> hand = Hand('Baris')
>>> hand.add(a)
>>> hand.add(b)
>>> hand.add(c)
>>> d = Card(3, 1)
>>> print(hand)
Hand Baris contains
5 of Clubs
 Ace of Clubs
  Ace of Spades
>>> d in hand.cards
False
>>>

I've also tried the card.py @DSM has used successfully, and I get errors there too, like at the sort function it says it cant compare the two card objects.

So I was wondering, maybe it is a problem with Python 3.2, or maybe the syntax has changed somewhere?

Body:
I can't seem to reproduce the problem with not being able to remove cards via Deck.remove.  If I start with the card.py at the thinkpython site and add the remove function you've posted up there, it seems to work:

>>> deck = Deck()
>>> str(deck).split('\n')
['Ace of Clubs', '2 of Clubs', '3 of Clubs', '4 of Clubs', '5 of Clubs', '6 of Clubs', '7 of Clubs', '8 of Clubs', '9 of Clubs', '10 of Clubs', 'Jack of Clubs', 'Queen of Clubs', 'King of Clubs', 'Ace of Diamonds', '2 of Diamonds', '3 of Diamonds', '4 of Diamonds', '5 of Diamonds', '6 of Diamonds', '7 of Diamonds', '8 of Diamonds', '9 of Diamonds', '10 of Diamonds', 'Jack of Diamonds', 'Queen of Diamonds', 'King of Diamonds', 'Ace of Hearts', '2 of Hearts', '3 of Hearts', '4 of Hearts', '5 of Hearts', '6 of Hearts', '7 of Hearts', '8 of Hearts', '9 of Hearts', '10 of Hearts', 'Jack of Hearts', 'Queen of Hearts', 'King of Hearts', 'Ace of Spades', '2 of Spades', '3 of Spades', '4 of Spades', '5 of Spades', '6 of Spades', '7 of Spades', '8 of Spades', '9 of Spades', '10 of Spades', 'Jack of Spades', 'Queen of Spades', 'King of Spades']
>>> len(deck.cards)
52
>>> c = Card(suit=0, rank=8)
>>> str(c)
'8 of Clubs'
>>> c in deck.cards
True
>>> deck.remove(c)
True
>>> len(deck.cards)
51
>>> c in deck.cards
False
>>> str(deck).split('\n')
['Ace of Clubs', '2 of Clubs', '3 of Clubs', '4 of Clubs', '5 of Clubs', '6 of Clubs', '7 of Clubs', '9 of Clubs', '10 of Clubs', 'Jack of Clubs', 'Queen of Clubs', 'King of Clubs', 'Ace of Diamonds', '2 of Diamonds', '3 of Diamonds', '4 of Diamonds', '5 of Diamonds', '6 of Diamonds', '7 of Diamonds', '8 of Diamonds', '9 of Diamonds', '10 of Diamonds', 'Jack of Diamonds', 'Queen of Diamonds', 'King of Diamonds', 'Ace of Hearts', '2 of Hearts', '3 of Hearts', '4 of Hearts', '5 of Hearts', '6 of Hearts', '7 of Hearts', '8 of Hearts', '9 of Hearts', '10 of Hearts', 'Jack of Hearts', 'Queen of Hearts', 'King of Hearts', 'Ace of Spades', '2 of Spades', '3 of Spades', '4 of Spades', '5 of Spades', '6 of Spades', '7 of Spades', '8 of Spades', '9 of Spades', '10 of Spades', 'Jack of Spades', 'Queen of Spades', 'King of Spades']

It seems to work if I replace the __cmp__ by yours, too:

>>> deck = Deck()
>>> c = Card(suit=0,rank=1)
>>> c in deck.cards
True
>>> deck.remove(c)
True
>>> len(deck.cards)
51

So something must be different.  Could you dump your entire code -- and some code demonstrating the bug -- somewhere (pastebin, gist, etc.)?

(FWIW, my ace-over-king cmp looks like this:

def __cmp__(self, other):
    def aceshigh(r): return 14 if r==1 else r
    t1 = self.suit, aceshigh(self.rank)
    t2 = other.suit, aceshigh(other.rank)
    return cmp(t1, t2)

Exercise: remove the magic numbers.)


问:
Property 'forRoot' does not exist on type 'typeof NgxJsonLdModule'
I have installed this package @ngx-lite/json-ld. In an attempt to make my SEO schema.org dynamic. On importing the module as specified on this Tutorial I get this error:

ERROR in src/app/app.module.ts(18,21): error TS2339: Property 'forRoot' does not exist on type 'typeof NgxJsonLdModule'.

Here is my app.module

```<code>import { NgtUniversalModule } from "@ng-toolkit/universal";
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

// Third Party library
import { NgxJsonLdModule } from "@ngx-lite/json-ld";

import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app-routing.module";
@NgModule({
  declarations: [AppComponent],
  imports: [
     AppRoutingModule,
     NgtUniversalModule,
     NgxJsonLdModule.forRoot()
  ],
  providers: []
})
export class AppModule {}
</code>```

I'm using angular 6.1.9 and Angular Universal.

答:
maybe change .forRoot by .withConfig</p>

```<code>@NgModule({
  imports: [
    ...
    NgxMapboxGLModule.withConfig({
      accessToken: 'TOKEN', // Optional, can also be set per map (accessToken input of mgl-map)
      geocoderAccessToken: 'TOKEN' // Optional, specify if different from the map access token, can also be set per mgl-geocoder (accessToken input of mgl-geocoder)
    })
  ]
})
</code>```

Body:
I have installed this package @ngx-lite/json-ld. In an attempt to make my SEO schema.org dynamic. On importing the module as specified on this Tutorial I get this error:

ERROR in src/app/app.module.ts(18,21): error TS2339: Property 'forRoot' does not exist on type 'typeof NgxJsonLdModule'.

Here is my app.module

import { NgtUniversalModule } from "@ng-toolkit/universal";
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

// Third Party library
import { NgxJsonLdModule } from "@ngx-lite/json-ld";

import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app-routing.module";
@NgModule({
  declarations: [AppComponent],
  imports: [
     AppRoutingModule,
     NgtUniversalModule,
     NgxJsonLdModule.forRoot()
  ],
  providers: []
})
export class AppModule {}

I'm using angular 6.1.9 and Angular Universal.

Body:
maybe change .forRoot by .withConfig

@NgModule({
  imports: [
    ...
    NgxMapboxGLModule.withConfig({
      accessToken: 'TOKEN', // Optional, can also be set per map (accessToken input of mgl-map)
      geocoderAccessToken: 'TOKEN' // Optional, specify if different from the map access token, can also be set per mgl-geocoder (accessToken input of mgl-geocoder)
    })
  ]
})


问:
Variables across Azure Pipeline stages
I saw the changes went in to allow us to consume variable outputs from previous stages. Has anyone got it working? Release info: https://learn.microsoft.com/en-us/azure/devops/release-notes/2020/sprint-168-update#jobs-can-access-output-variables-from-previous-stages

I tried this:

```<code>trigger:
- master

resources:
- repo: self

pool:
  vmImage: 'ubuntu-16.04'

variables:
  MyVar: 'MyVal'

stages:
- stage: Save_Variable

  jobs:
  - job: Save_Variable
    steps:
      - pwsh: Write-Host "##vso[task.setvariable variable=MyVar;]NewVal"
        name: MyOutputVar

- stage: Read_Variables
  dependsOn: Save_Variable

  jobs:
    - job: Read_Variable
      variables:
        prevStageVar: $[stageDependencies.Save_Variable.Save_Variable.outputs['MyOutputVar.MyVar']]
      steps:
      - powershell: 'Write-Host "Get Stage variable: $(prevStageVar)"'
</code>```

Mentioned here https://www.razorspoint.com/2020/05/05/azure-devops-sprint-update-cross-staging-variables-supported-natively/ But I wasn't able to get it working.

Any luck from others?

答:
All good, it just needs the ;isOutput=true

https://www.reddit.com/r/azuredevops/comments/gvo3ml/variables_across_stages/

Title: Variables across Azure Pipeline stages

Body:
I saw the changes went in to allow us to consume variable outputs from previous stages. Has anyone got it working? Release info: https://learn.microsoft.com/en-us/azure/devops/release-notes/2020/sprint-168-update#jobs-can-access-output-variables-from-previous-stages

I tried this:

trigger:
- master

resources:
- repo: self

pool:
  vmImage: 'ubuntu-16.04'

variables:
  MyVar: 'MyVal'

stages:
- stage: Save_Variable

  jobs:
  - job: Save_Variable
    steps:
      - pwsh: Write-Host "##vso[task.setvariable variable=MyVar;]NewVal"
        name: MyOutputVar

- stage: Read_Variables
  dependsOn: Save_Variable

  jobs:
    - job: Read_Variable
      variables:
        prevStageVar: $[stageDependencies.Save_Variable.Save_Variable.outputs['MyOutputVar.MyVar']]
      steps:
      - powershell: 'Write-Host "Get Stage variable: $(prevStageVar)"'

Mentioned here https://www.razorspoint.com/2020/05/05/azure-devops-sprint-update-cross-staging-variables-supported-natively/ But I wasn't able to get it working.

Any luck from others?


问:
Get system folder paths in Go?
Is it possible to get the path of system folders in Go, in a cross-platform way? eg. temp folders, "document" folders, etc.

I found ioutil.TempFolder/File but they do something different. Any idea?

答:
In the year 2020, I am trying to get similar things, but only for temporary directory cross-platform. When I found this thread and read some answers, I almost make a conclusion that it is not possible.

But after a few further research, I found that go already have it. Just like pointed by the accepted answer, it stands inside os package. Based on this documentation: https://golang.org/pkg/os/#TempDir, we can get it by calling: TempDir() function.

If someone trying to look at another OS system directories path, and stumbled upon in this thread, my suggestion, please just try to have a few further research. Looks like currently go have more complete functions regarding OS system directories.

Title: Get system folder paths in Go?


问:
CSS unordered list with dotted full block width underline
How i can make an ordered list like the one in the screenshot?
What is important is to have a full width dotted underline per item.

Thank you
Sample ordered list

答:
You can simply add border-bottom to each li item.

ul li {
  border-bottom: 1px dashed #000;
}
```

<p>Furthermore, you can add a bit of padding:</p>

<pre class="lang-css prettyprint-override"><code>ul li {
  padding: 1em 0;
  border-bottom: 1px dashed #000;
}
</code>```

Body:
You can simply add border-bottom to each li item.

ul li {
  border-bottom: 1px dashed #000;
}

Furthermore, you can add a bit of padding:

ul li {
  padding: 1em 0;
  border-bottom: 1px dashed #000;
}