问:
RSA Decryption from c++ Windows Crypto API to Golang
I have encrypted a string with RSA public key using the Windows Crypto API, but I'm not able to decrypt it using the RSA private key with Go.
The following code is the encryption using C++

HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hKey = NULL;
DWORD dwPublicKeyLen = 0;
DWORD dwDataLen = 0;
DWORD dwEncryptedLen = 0;
BYTE* pbPublicKey = NULL;
BYTE* pbData = NULL;
HANDLE hPublicKeyFile = NULL;
HANDLE hEncryptedFile = NULL;
HANDLE hPlainFile = NULL;
DWORD lpNumberOfBytesWritten = 0;

BYTE derPubKey[2048];
DWORD derPubKeyLen = 2048;
CERT_PUBLIC_KEY_INFO* publicKeyInfo = NULL;
DWORD publicKeyInfoLen = 0;
HANDLE hFile = NULL;

if (!CryptAcquireContextW(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
{
    printf("CryptAcquireContext error 0x%x\n", GetLastError());
    return 1;
}

std::string pempubkeyS = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNoGP0DHZA9RyZlQETr3NGr6hoxn9oHFiFeJwCUooz+qP38vQ53Cs7VtisfEl/FmkwRCz9l0bKU9MZ00Z1/WLTa+48dqGMNL2+um1za0Z0fyxXmYEwy3zvFaswtgzHfXlN+pcay6DsaBXXSvQpC6sz50DvcIw4YsMPqSSBk++LSQIDAQAB";
std::wstring pempubkey = std::wstring(pempubkeyS.begin(), pempubkeyS.end());

if (!CryptStringToBinaryW(pempubkey.c_str(), 0, CRYPT_STRING_BASE64, derPubKey, &derPubKeyLen, NULL, NULL))
{
    printf("CryptStringToBinary failed. Err: %d\n", GetLastError());
    return -1;
}

/*
 * Decode from DER format to CERT_PUBLIC_KEY_INFO
 */
if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, X509_PUBLIC_KEY_INFO, derPubKey, derPubKeyLen, CRYPT_ENCODE_ALLOC_FLAG, NULL, &publicKeyInfo, &publicKeyInfoLen))
{
    printf("CryptDecodeObjectEx 1 failed. Err: %x\n", GetLastError());
    return -1;
}

/*
 * Import the public key using the context
 */
if (!CryptImportPublicKeyInfo(hCryptProv, X509_ASN_ENCODING, publicKeyInfo, &hKey))
{
    printf("CryptImportPublicKeyInfo failed. error: %d\n", GetLastError());
    return -1;
}

LocalFree(publicKeyInfo);

std::string cleartext = "This is a test!";
int len = cleartext.length();

// Get lenght for encrypted data
if (!CryptEncrypt(hKey, NULL, TRUE, CRYPT_OAEP, NULL, &dwEncryptedLen, 0))
{
    // Error
    printf("CryptEncrypt error 0x%x\n", GetLastError());
    return 1;
}
cleartext.resize(len + dwEncryptedLen);

// Encrypt data
if (!CryptEncrypt(hKey, NULL, TRUE, 0, (BYTE*)&cleartext[0], &dwDataLen, dwEncryptedLen))
{
    // Error
    printf("CryptEncrypt error 0x%x\n", GetLastError());
    return 1;
}

std::string cleartextbase64 = "";
cleartext.resize(dwDataLen);
Base64Encode(cleartext, &cleartextbase64);
std::cout << cleartextbase64 << std::endl;
// HkCebflDgmxJ33hmLTrqGsPyyyPKP74MePHedzrB8jiI6AOJhIw06WD93HggIRCgm/A6CqRYYgHe749Z6uTAqsh2dY9bvGMfNGLAQ7g5YFYlK+MWUEyFB1yRH6cDJKloP+J1UhIibGa3R+cwY9EHfDNCZfeTL0zYPHFKun9OBZ0=
```
<p>The following code is the decryption using Go</p>
<pre class="lang-go prettyprint-override"><code>keyRaw, err := base64.StdEncoding.DecodeString("LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlDWHdJQkFBS0JnUUROb0dQMERIWkE5UnlabFFFVHIzTkdyNmhveG45b0hGaUZlSndDVW9veitxUDM4dlE1CjNDczdWdGlzZkVsL0Zta3dSQ3o5bDBiS1U5TVowMFoxL1dMVGErNDhkcUdNTkwyK3VtMXphMFowZnl4WG1ZRXcKeTN6dkZhc3d0Z3pIZlhsTitwY2F5NkRzYUJYWFN2UXBDNnN6NTBEdmNJdzRZc01QcVNTQmsrK0xTUUlEQVFBQgpBb0dCQUtia3J6dTlnWjFuVkRjelFSU0JLc2NNZTF2UEFFbTMrQUVjeTBMM1MwUzFBYkNWZUxRZGh0azZ1OUlECmJvTy81TkJRQlZRdUhEN0xtbU16bjlUVVBBaDRRWUxSUGxVQWFRVTM5eThxTDdIbWdoR0lRN0JrZWxPS3hYQjkKNEtBUTFiRksxZ2hwZEFEeDhtTVh5SWZjTG5JSnRJT1ZibWloRjNxdUt4UzBuRlNCQWtFQTE2TlRPeWpKWW9aUQpoaG9XSFJHcXlDU1ZKbGRwaUxSaENxNFAwRVNER2NaTFRlMVVSVXRhRWlZeHk4cGdoQmkxVHpkU1ZVM3h2bk10ClZOeEtoc0tHblFKQkFQUWRXUzdXYUFvWHJYODZ1alJNd1VxcW4zcVJwMWVGM29hdzZ0TWtWZHpDcTZoRzlyRjUKU2pzekhjUkJ4WlNyeklWeXN1T2pBYS9ta0JtbmZtV3Y0WjBDUVFDMy9DMXVvMzA0S0J1YVg3V1FkZHQrU3VCTApSM2ZPNFFDUGFUWXEzOW52NnVXamhxUkpQMktKYTdjL0J0eFV1UFF4czZUM0RicitZUzFEWTNYZkJ5aHRBa0VBCjZwZ05yYkpFZDNaN3VDb3k2YkhkaTZqZTdBWnZuKys1Z3cwZ0RscjczTlNEN0lxTjVzNGQ1VGhoWWNxbld4R2kKMFpnQmpEdUprb1pyY3d3QXJ5NVFEUUpCQUt0Uk1LbmJnZFR3TWRQbTMwQWErQk50UGNwckN4VXFFWHpCT2lZSQpXVVBZOTBCdmxGSzkvK3VVWktOQzhoK1Ntc2F3ekFaKzZUVzlEWUFuSWZ1UkExZz0KLS0tLS1FTkQgUlNBIFBSSVZBVEUgS0VZLS0tLS0K")
if err != nil {
    panic(err)
}

block, _ := pem.Decode(keyRaw)
configPrivateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
    panic(err)
}
encodedEncrypted := `HkCebflDgmxJ33hmLTrqGsPyyyPKP74MePHedzrB8jiI6AOJhIw06WD93HggIRCgm/A6CqRYYgHe749Z6uTAqsh2dY9bvGMfNGLAQ7g5YFYlK+MWUEyFB1yRH6cDJKloP+J1UhIibGa3R+cwY9EHfDNCZfeTL0zYPHFKun9OBZ0=`
cipherText, err := base64.StdEncoding.DecodeString(encodedEncrypted)
if err != nil {
    panic(err)
}

cleartextMessage, err := rsa.DecryptPKCS1v15(rand.Reader, configPrivateKey, cipherText)
//cleartextMessage, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, configPrivateKey, cipherText, nil)
if  err != nil {
    panic(err) // panic: crypto/rsa: decryption error
}
fmt.Println(string(cleartextMessage))
</code>```

As you can see I've got a panic: crypto/rsa: decryption error. Any ideas? Thanks in advance!

答:
There are the following issues:

CryptEncrypt() returns the result in little endian format, so in the Go code the ciphertext must be reversed, e.g. (see here):

...
for i, j := 0, len(cipherText)-1; i < j; i, j = i+1, j-1 {
    cipherText[i], cipherText[j] = cipherText[j], cipherText[i]
}
...
```

On encryption (2nd CryptEncrypt() call) the 6th parameter is &dwDataLen, where dwDataLen is 0. According to the documentation, the 6th parameter contains on entry the plaintext length (and on exit the ciphertext length). Because here the 6th parameter on entry is 0, an empty string is encrypted. This is probably not intended and must be fixed accordingly (i.e. dwDataLen must be set to the plaintext length)!

On encryption (2nd CryptEncrypt() call) the 4th parameter is 0, so PKCS#1 v1.5 padding is applied. Therefore, in the Go code, rsa.DecryptPKCS1v15() must be used, which is currently the case (rsa.DecryptOAEP() is commented out). Note that when determining the length of the encrypted data (1st CryptEncrypt() call), the CRYPT_OAEP flag is set, which is inconsistent, but probably has no effect. This point has already been addressed in the comments.

If the ciphertext is reversed, the decryption works and returns an empty string as result because of dwDataLen equals 0.

Body:
I have encrypted a string with RSA public key using the Windows Crypto API, but I'm not able to decrypt it using the RSA private key with Go.
The following code is the encryption using C++

HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hKey = NULL;
DWORD dwPublicKeyLen = 0;
DWORD dwDataLen = 0;
DWORD dwEncryptedLen = 0;
BYTE* pbPublicKey = NULL;
BYTE* pbData = NULL;
HANDLE hPublicKeyFile = NULL;
HANDLE hEncryptedFile = NULL;
HANDLE hPlainFile = NULL;
DWORD lpNumberOfBytesWritten = 0;

BYTE derPubKey[2048];
DWORD derPubKeyLen = 2048;
CERT_PUBLIC_KEY_INFO* publicKeyInfo = NULL;
DWORD publicKeyInfoLen = 0;
HANDLE hFile = NULL;

if (!CryptAcquireContextW(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
{
    printf("CryptAcquireContext error 0x%x\n", GetLastError());
    return 1;
}

std::string pempubkeyS = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNoGP0DHZA9RyZlQETr3NGr6hoxn9oHFiFeJwCUooz+qP38vQ53Cs7VtisfEl/FmkwRCz9l0bKU9MZ00Z1/WLTa+48dqGMNL2+um1za0Z0fyxXmYEwy3zvFaswtgzHfXlN+pcay6DsaBXXSvQpC6sz50DvcIw4YsMPqSSBk++LSQIDAQAB";
std::wstring pempubkey = std::wstring(pempubkeyS.begin(), pempubkeyS.end());

if (!CryptStringToBinaryW(pempubkey.c_str(), 0, CRYPT_STRING_BASE64, derPubKey, &derPubKeyLen, NULL, NULL))
{
    printf("CryptStringToBinary failed. Err: %d\n", GetLastError());
    return -1;
}

/*
 * Decode from DER format to CERT_PUBLIC_KEY_INFO
 */
if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, X509_PUBLIC_KEY_INFO, derPubKey, derPubKeyLen, CRYPT_ENCODE_ALLOC_FLAG, NULL, &publicKeyInfo, &publicKeyInfoLen))
{
    printf("CryptDecodeObjectEx 1 failed. Err: %x\n", GetLastError());
    return -1;
}

/*
 * Import the public key using the context
 */
if (!CryptImportPublicKeyInfo(hCryptProv, X509_ASN_ENCODING, publicKeyInfo, &hKey))
{
    printf("CryptImportPublicKeyInfo failed. error: %d\n", GetLastError());
    return -1;
}

LocalFree(publicKeyInfo);

std::string cleartext = "This is a test!";
int len = cleartext.length();

// Get lenght for encrypted data
if (!CryptEncrypt(hKey, NULL, TRUE, CRYPT_OAEP, NULL, &dwEncryptedLen, 0))
{
    // Error
    printf("CryptEncrypt error 0x%x\n", GetLastError());
    return 1;
}
cleartext.resize(len + dwEncryptedLen);

// Encrypt data
if (!CryptEncrypt(hKey, NULL, TRUE, 0, (BYTE*)&cleartext[0], &dwDataLen, dwEncryptedLen))
{
    // Error
    printf("CryptEncrypt error 0x%x\n", GetLastError());
    return 1;
}

std::string cleartextbase64 = "";
cleartext.resize(dwDataLen);
Base64Encode(cleartext, &cleartextbase64);
std::cout << cleartextbase64 << std::endl;
// HkCebflDgmxJ33hmLTrqGsPyyyPKP74MePHedzrB8jiI6AOJhIw06WD93HggIRCgm/A6CqRYYgHe749Z6uTAqsh2dY9bvGMfNGLAQ7g5YFYlK+MWUEyFB1yRH6cDJKloP+J1UhIibGa3R+cwY9EHfDNCZfeTL0zYPHFKun9OBZ0=

The following code is the decryption using Go

keyRaw, err := base64.StdEncoding.DecodeString("LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlDWHdJQkFBS0JnUUROb0dQMERIWkE5UnlabFFFVHIzTkdyNmhveG45b0hGaUZlSndDVW9veitxUDM4dlE1CjNDczdWdGlzZkVsL0Zta3dSQ3o5bDBiS1U5TVowMFoxL1dMVGErNDhkcUdNTkwyK3VtMXphMFowZnl4WG1ZRXcKeTN6dkZhc3d0Z3pIZlhsTitwY2F5NkRzYUJYWFN2UXBDNnN6NTBEdmNJdzRZc01QcVNTQmsrK0xTUUlEQVFBQgpBb0dCQUtia3J6dTlnWjFuVkRjelFSU0JLc2NNZTF2UEFFbTMrQUVjeTBMM1MwUzFBYkNWZUxRZGh0azZ1OUlECmJvTy81TkJRQlZRdUhEN0xtbU16bjlUVVBBaDRRWUxSUGxVQWFRVTM5eThxTDdIbWdoR0lRN0JrZWxPS3hYQjkKNEtBUTFiRksxZ2hwZEFEeDhtTVh5SWZjTG5JSnRJT1ZibWloRjNxdUt4UzBuRlNCQWtFQTE2TlRPeWpKWW9aUQpoaG9XSFJHcXlDU1ZKbGRwaUxSaENxNFAwRVNER2NaTFRlMVVSVXRhRWlZeHk4cGdoQmkxVHpkU1ZVM3h2bk10ClZOeEtoc0tHblFKQkFQUWRXUzdXYUFvWHJYODZ1alJNd1VxcW4zcVJwMWVGM29hdzZ0TWtWZHpDcTZoRzlyRjUKU2pzekhjUkJ4WlNyeklWeXN1T2pBYS9ta0JtbmZtV3Y0WjBDUVFDMy9DMXVvMzA0S0J1YVg3V1FkZHQrU3VCTApSM2ZPNFFDUGFUWXEzOW52NnVXamhxUkpQMktKYTdjL0J0eFV1UFF4czZUM0RicitZUzFEWTNYZkJ5aHRBa0VBCjZwZ05yYkpFZDNaN3VDb3k2YkhkaTZqZTdBWnZuKys1Z3cwZ0RscjczTlNEN0lxTjVzNGQ1VGhoWWNxbld4R2kKMFpnQmpEdUprb1pyY3d3QXJ5NVFEUUpCQUt0Uk1LbmJnZFR3TWRQbTMwQWErQk50UGNwckN4VXFFWHpCT2lZSQpXVVBZOTBCdmxGSzkvK3VVWktOQzhoK1Ntc2F3ekFaKzZUVzlEWUFuSWZ1UkExZz0KLS0tLS1FTkQgUlNBIFBSSVZBVEUgS0VZLS0tLS0K")
if err != nil {
    panic(err)
}

block, _ := pem.Decode(keyRaw)
configPrivateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
    panic(err)
}
encodedEncrypted := `HkCebflDgmxJ33hmLTrqGsPyyyPKP74MePHedzrB8jiI6AOJhIw06WD93HggIRCgm/A6CqRYYgHe749Z6uTAqsh2dY9bvGMfNGLAQ7g5YFYlK+MWUEyFB1yRH6cDJKloP+J1UhIibGa3R+cwY9EHfDNCZfeTL0zYPHFKun9OBZ0=`
cipherText, err := base64.StdEncoding.DecodeString(encodedEncrypted)
if err != nil {
    panic(err)
}

cleartextMessage, err := rsa.DecryptPKCS1v15(rand.Reader, configPrivateKey, cipherText)
//cleartextMessage, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, configPrivateKey, cipherText, nil)
if  err != nil {
    panic(err) // panic: crypto/rsa: decryption error
}
fmt.Println(string(cleartextMessage))

As you can see I've got a panic: crypto/rsa: decryption error. Any ideas? Thanks in advance!

Body:
There are the following issues:

CryptEncrypt() returns the result in little endian format, so in the Go code the ciphertext must be reversed, e.g. (see here):

...
for i, j := 0, len(cipherText)-1; i < j; i, j = i+1, j-1 {
    cipherText[i], cipherText[j] = cipherText[j], cipherText[i]
}
...

On encryption (2nd CryptEncrypt() call) the 6th parameter is &dwDataLen, where dwDataLen is 0. According to the documentation, the 6th parameter contains on entry the plaintext length (and on exit the ciphertext length). Because here the 6th parameter on entry is 0, an empty string is encrypted. This is probably not intended and must be fixed accordingly (i.e. dwDataLen must be set to the plaintext length)!

On encryption (2nd CryptEncrypt() call) the 4th parameter is 0, so PKCS#1 v1.5 padding is applied. Therefore, in the Go code, rsa.DecryptPKCS1v15() must be used, which is currently the case (rsa.DecryptOAEP() is commented out). Note that when determining the length of the encrypted data (1st CryptEncrypt() call), the CRYPT_OAEP flag is set, which is inconsistent, but probably has no effect. This point has already been addressed in the comments.

If the ciphertext is reversed, the decryption works and returns an empty string as result because of dwDataLen equals 0.


来源: stackexchange

问:
Say The Numbers - Sololearn Go Challenge
I'm currently learning Go using the SoloLearn App.

The Challenge was :
 Taking 3 numbers in the range of 0-10 as input and output the corresponding texts in English.

Test Case #1, Test Case #3, Test Case #4 and #Test Case #5 were successful.

But I have problems concluding Test Case #2 and Test Case #6.

Thank you in advance for any help.

```<code>package main
import "fmt"

func main() {

   for i:=0;i<3;i++ {
   var x int
   fmt.Scanln(&x)

   if (x>=0 && x<10) {

       switch x {
          case 0:
            fmt.Print("Zero")
          case 1:
            fmt.Print("One")
          case 2:
            fmt.Print("Two")
          case 3:
            fmt.Print("Three")
          case 4:
            fmt.Print("Four")
          case 5:
            fmt.Print("Five")
          case 6:
            fmt.Print("Six")
          case 7:
            fmt.Print("Seven")
          case 8:
            fmt.Print("Eight")
          case 9:
            fmt.Print("Nine")
          case 10:
            fmt.Print("Ten")
          default:
            fmt.Println("This is not a number or a number between 0 and 10")
         }
        }
        if i<2 {
           fmt.Println("")
        }
       }

  }
</code>```

答:
Maybe by sharing the test cases would be easier for us to understand whats happening.

But at a first sight I would replace the x<10 with x<=10 and all the fmt.Print with fmt.Println and remove this parts.

```<code>    if i<2 {
       fmt.Println("")
    }
</code>```

If you keep the condition that validates that the input number is between 0 and 10 the message of the default case would never be printed.

And also let me share you another approach of the solution, is the same but with a couple of good practices:

```<code>package main

import "fmt"

var validWrittenNumbers = map[int]string{
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four",
    5: "Five",
    6: "Six",
    7: "Seven",
    8: "Eight",
    9: "Nine",
    10: "Ten",
}

func printValidWrittenNumber(candidateNumber int) {
    if stringNumber, ok := validWrittenNumbers[candidateNumber]; ok {
        fmt.Println(stringNumber)
    }
}

func main() {
    inputTimes := 3

    for index := 0; index < inputTimes; index++ {
        var candidateNumber int
        _, _ = fmt.Scanln(&candidateNumber)

        printValidWrittenNumber(candidateNumber)
    }
}
</code>```

I hope this works and sorry for not being more helpful!

ContentLicense: CC BY-SA 4.0

Body:
I'm currently learning Go using the SoloLearn App.

The Challenge was :
 Taking 3 numbers in the range of 0-10 as input and output the corresponding texts in English.

Test Case #1, Test Case #3, Test Case #4 and #Test Case #5 were successful.

But I have problems concluding Test Case #2 and Test Case #6.

Thank you in advance for any help.

package main
import "fmt"

func main() {

   for i:=0;i<3;i++ {
   var x int
   fmt.Scanln(&x)

   if (x>=0 && x<10) {

       switch x {
          case 0:
            fmt.Print("Zero")
          case 1:
            fmt.Print("One")
          case 2:
            fmt.Print("Two")
          case 3:
            fmt.Print("Three")
          case 4:
            fmt.Print("Four")
          case 5:
            fmt.Print("Five")
          case 6:
            fmt.Print("Six")
          case 7:
            fmt.Print("Seven")
          case 8:
            fmt.Print("Eight")
          case 9:
            fmt.Print("Nine")
          case 10:
            fmt.Print("Ten")
          default:
            fmt.Println("This is not a number or a number between 0 and 10")
         }
        }
        if i<2 {
           fmt.Println("")
        }
       }

  }

Body:
Maybe by sharing the test cases would be easier for us to understand whats happening.

But at a first sight I would replace the x<10 with x<=10 and all the fmt.Print with fmt.Println and remove this parts.

    if i<2 {
       fmt.Println("")
    }

If you keep the condition that validates that the input number is between 0 and 10 the message of the default case would never be printed.

And also let me share you another approach of the solution, is the same but with a couple of good practices:

package main

import "fmt"

var validWrittenNumbers = map[int]string{
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four",
    5: "Five",
    6: "Six",
    7: "Seven",
    8: "Eight",
    9: "Nine",
    10: "Ten",
}

func printValidWrittenNumber(candidateNumber int) {
    if stringNumber, ok := validWrittenNumbers[candidateNumber]; ok {
        fmt.Println(stringNumber)
    }
}

func main() {
    inputTimes := 3

    for index := 0; index < inputTimes; index++ {
        var candidateNumber int
        _, _ = fmt.Scanln(&candidateNumber)

        printValidWrittenNumber(candidateNumber)
    }
}

I hope this works and sorry for not being more helpful!


问:
Webpack 5 import images and fonts, rewrite url in prod
I need to copy the image and font files to the appropriate folder in the dist directory, the problem is that in the final css file I get the wrong url path. I tried to disable url css-loader then files are not copied at all. Tried adding ~ to url .
I need to use asset/resource to copy and paste the correct path in the stylesheet. Various other outdated solutions won't work for me.

My webpack 5 config

I import file less to main.js.

My folder structure

答:
I solved my problem by adding publicPath: ".", why is there a dot in quotes? Because I have the path ./ in the url itself, so I add a dot and I can exit the directory.

For fonts, I created a generator that creates a separate folder, paths work on the same principle.

output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: ".",
    assetModuleFilename: "./img/[name].[ext]",
    clean: true,
  },

  {
        test: /\.(jpe?g|png|gif|svg)$/i,
        type: "asset/resource",
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: "asset/resource",
        generator: {
          filename: "./fonts/[name][ext]",
        },
      },```


问:
Create dictionary where values are keys transformed to strings
G is a graph object and sorted(G) returns a list of nodes:

```<code>[0,1,2...1860]
</code>```

I need to rename those nodes mapping from a dictionary, like so:

```<code>mapping = {0: "0_cereb", 1: "1_cereb", 2: "2_cereb",..., 1860: "1860_cereb"}
</code>```

And then I can apply dict to a method that relabels my graph:

```<code>import networkx as nx
Gnew = nx.relabel_nodes(G, mapping)
</code>```

and sorted(Gnew)returns:

```<code>[0_cereb, 2_cereb, ..., 1860_cereb]
</code>```

How do I create this mapping dict?

答:
The answer would be dict comprehension

```<code>mapping = {k: f"{k}_cereb" for k in sorted(G)}
</code>```

will run through list and create key value pairs

Body:
G is a graph object and sorted(G) returns a list of nodes:

[0,1,2...1860]

I need to rename those nodes mapping from a dictionary, like so:

mapping = {0: "0_cereb", 1: "1_cereb", 2: "2_cereb",..., 1860: "1860_cereb"}

And then I can apply dict to a method that relabels my graph:

import networkx as nx
Gnew = nx.relabel_nodes(G, mapping)

and sorted(Gnew)returns:

[0_cereb, 2_cereb, ..., 1860_cereb]

How do I create this mapping dict?

Body:
The answer would be dict comprehension

mapping = {k: f"{k}_cereb" for k in sorted(G)}

will run through list and create key value pairs


问:
Would there be compatibility issues upgrading rails 2 to rails 3?
Im considering upgrading a rails 2 app to rails 3 for a number of reasons (rails 3 features, certain plugins require rails 3 etc.)

Obviously ill have to update/grade some of the plugins as well. But concerning the code itself, should there be any compatibility issues when upgrading to 3? I know rails 3 changes a lot of helpers and syntax to make things easier, but do the older and more complicated ways still work (ex. gems in envioronment.rb, not Gemfile).

Also, anyone know a good tutorial on how to do it?

答:
I have written a blogpost about it, where I point to the standard resources, but also handle some more deeper problems I encountered.

Hope this helps.

ContentLicense: CC BY-SA 3.0


问:
Navigate to new page once upload is done
i'd like to naviagte to a new page to display the uploaded image , I've created custom function 'navigateToNewPage' to navigate , but I get this error

This expression has a type of 'void' so its value can't be used. Try
checking to see if you're using the correct API; there might be a
function or call that returns void you didn't expect. Also check type
parameters and variables which might also be void.

code :

```<code>  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Pick Image Camera"),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Card(
                child: (imageFile == null)
                    ? Text("Choose Image")
                    : navigateToNewPage() // here's the problem
,
              ),
              MaterialButton(
                textColor: Colors.white,
                color: Colors.pink,
                onPressed: () {
                  _showChoiceDialog(context);
                },
                child: Text("Select Image"),
              )
            ],
          ),
        ),
      ),
    );
  }

  void _openGallery(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
    );
    setState(() {
      imageFile = pickedFile!;
    });

    Navigator.pop(context);
  }

  void _openCamera(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.camera,
    );
    setState(() {
      imageFile = pickedFile!;
    });
    Navigator.pop(context);
  }

  void navigateToNewPage() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => second()),
    );
  }
</code>```

答:
You are trying to put a void Function in place of a Widget. That doesn't work. Navigator.push() opens a new Widget on the screen. In your case second(). You need to run this inside a function that gets executed once imageFile is no longer null. If you want second in place of the Text widget replace the code with this:

Card(
  child: (imageFile == null)
    ? Text("Choose Image")
    : second(), // here's the problem
),
```

Body:
i'd like to naviagte to a new page to display the uploaded image , I've created custom function 'navigateToNewPage' to navigate , but I get this error

This expression has a type of 'void' so its value can't be used. Try
checking to see if you're using the correct API; there might be a
function or call that returns void you didn't expect. Also check type
parameters and variables which might also be void.

code :

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Pick Image Camera"),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Card(
                child: (imageFile == null)
                    ? Text("Choose Image")
                    : navigateToNewPage() // here's the problem
,
              ),
              MaterialButton(
                textColor: Colors.white,
                color: Colors.pink,
                onPressed: () {
                  _showChoiceDialog(context);
                },
                child: Text("Select Image"),
              )
            ],
          ),
        ),
      ),
    );
  }

  void _openGallery(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
    );
    setState(() {
      imageFile = pickedFile!;
    });

    Navigator.pop(context);
  }

  void _openCamera(BuildContext context) async {
    final pickedFile = await ImagePicker().getImage(
      source: ImageSource.camera,
    );
    setState(() {
      imageFile = pickedFile!;
    });
    Navigator.pop(context);
  }

  void navigateToNewPage() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => second()),
    );
  }


问:
Visual Studio Community 2022 v17.0.1: .NET MAUI option is not available
When I setup Visual Studio 2022 v17.0.1, these are the options available:

But in this YouTube video, it is showing the following:

In my copy of Visual Studio 2022 v17.0.1, the option like shown in the YouTube video is not showing up. Is there something wrong with my Visual Studio setup?

答: Change version to preview instead of other versions</p>


问:
std::cin don't break program when reading incorrect int
I have a program I made that will check your age and gender. I am using visual studio 2022 to see what happens when debugging.

If I put random letters for the age it skips the cin > gender part which is so weird and the locals shows that age is set to 0 but gender is -52'' . What can I do so it still atleast takes your gender, even if you put weird stuff in for age?

```<code>#include <iostream>
using namespace std;
int main()
{
    // prompt user for age AND gender
    //age is int, gender is character
    int age;
    char gender;
    cout << "What is your age? \n" << endl;
    cin >> age;
    cout << "What is your gender? \n" << endl;
    cin >> gender;

    if (gender == 'f' || gender == 'F')
    {
        bool result = (age > 60);
        switch (result)
        {
        case 0:
            cout << "You do not qualify for discount need to be over 60";
            break;
        case 1:
            cout << "You qualify for discount";
            break;
        }
    }
    else if (gender == 'm' || gender == 'M')
    {
        cout << "You do not qualify you need to be female and over 60 \n" << endl;
    }
    else {
        cout << "Wrong gender either use male or female Exiting... \n" << endl;
        return -1;
        exit;
    }

    return 0;
}
</code>```

This is a picture of the visual studio locals area

答:
When you type bad data for the age and the conversion fails, cin enters an error state.  When it's in an error state, it refuses to read anything.  The simplest fix would be to just clear the stream after the first

```<code>cout << "What is your age? \n" << endl;
cin >> age;
cin.clear();  // But now, the bad integer will become the gender
cout << "What is your gender? \n" << endl;
cin >> gender;
</code>```

Far better would be to check cin after the first read, and do some error handling, perhaps printing a message and setting the age to some known value.

```<code>cin >> age;
if(!cin.good()) {
    // Handle bad input here
}
</code>```

Note: after the integer read fails, the non-integer data is still in the input stream.  If you just clear, that will be the next thing read.

Body:
I have a program I made that will check your age and gender. I am using visual studio 2022 to see what happens when debugging.

If I put random letters for the age it skips the cin > gender part which is so weird and the locals shows that age is set to 0 but gender is -52'' . What can I do so it still atleast takes your gender, even if you put weird stuff in for age?

#include <iostream>
using namespace std;
int main()
{
    // prompt user for age AND gender
    //age is int, gender is character
    int age;
    char gender;
    cout << "What is your age? \n" << endl;
    cin >> age;
    cout << "What is your gender? \n" << endl;
    cin >> gender;

    if (gender == 'f' || gender == 'F')
    {
        bool result = (age > 60);
        switch (result)
        {
        case 0:
            cout << "You do not qualify for discount need to be over 60";
            break;
        case 1:
            cout << "You qualify for discount";
            break;
        }
    }
    else if (gender == 'm' || gender == 'M')
    {
        cout << "You do not qualify you need to be female and over 60 \n" << endl;
    }
    else {
        cout << "Wrong gender either use male or female Exiting... \n" << endl;
        return -1;
        exit;
    }

    return 0;
}

This is a picture of the visual studio locals area

Body:
When you type bad data for the age and the conversion fails, cin enters an error state.  When it's in an error state, it refuses to read anything.  The simplest fix would be to just clear the stream after the first

cout << "What is your age? \n" << endl;
cin >> age;
cin.clear();  // But now, the bad integer will become the gender
cout << "What is your gender? \n" << endl;
cin >> gender;

Far better would be to check cin after the first read, and do some error handling, perhaps printing a message and setting the age to some known value.

cin >> age;
if(!cin.good()) {
    // Handle bad input here
}

Note: after the integer read fails, the non-integer data is still in the input stream.  If you just clear, that will be the next thing read.


问:
Unable To Scrape url from page using Python and BeautifulSoup. Any ideas?
As the title suggests. I'm playing around with a Twitter bot that scrapes rss feeds and tweets the title of the article and a link.

For some reason when I run the below code it runs without errors but doesn't retrieve the url link. Any suggestions are gratefully recieved.

```<code>from bs4 import BeautifulSoup
import requests

url = "https://www.kdnuggets.com/feed"
resp = requests.get(url)
soup = BeautifulSoup(resp.content)
items = soup.findAll('item')
item = items[1]

print(item.title.text)
print(item.link.text)
</code>```

The title prints fine but the link is nowhere to be found. For reference, below is a copy of the html that is returned for this item.

```<code><item>
<title>An Overview of Logistic Regression</title>
<link/>https://www.kdnuggets.com/2022/02/overview-logistic-regression.html
                                        <comments>https://www.kdnuggets.com/2022/02/overview-logistic-regression.html#disqus_thread</comments>
<dc:creator><![CDATA[Matt Mayo Editor]]></dc:creator>
<pubdate>Fri, 04 Feb 2022 13:00:11 +0000</pubdate>
<category><![CDATA[2022 Feb Tutorials, Overviews]]></category>
<category><![CDATA[Machine Learning]]></category>
<guid ispermalink="false">https://www.kdnuggets.com/?p=137943</guid>
<description><![CDATA[Logistic regression is an extension of linear regression to solve classification problems. Read more on the specifics of this algorithm here.]]></description>
<wfw:commentrss>https://www.kdnuggets.com/2022/02/overview-logistic-regression.html/feed</wfw:commentrss>
<slash:comments>0</slash:comments>
</item>
</code>```

Thanks in advance.

答:
Try this one. I think you need to loop throught the "item" to get all links.</p>
```<code>from bs4 import BeautifulSoup
import requests

url = "https://www.kdnuggets.com/feed"
resp = requests.get(url)
soup = BeautifulSoup(resp.content)
items = soup.findAll('item')
item = items[1]

links = []
for link in item:
    links.append(link.text)
print(item.title.text)
print(links)
</code>```

Body:
As the title suggests. I'm playing around with a Twitter bot that scrapes rss feeds and tweets the title of the article and a link.

For some reason when I run the below code it runs without errors but doesn't retrieve the url link. Any suggestions are gratefully recieved.

from bs4 import BeautifulSoup
import requests

url = "https://www.kdnuggets.com/feed"
resp = requests.get(url)
soup = BeautifulSoup(resp.content)
items = soup.findAll('item')
item = items[1]

print(item.title.text)
print(item.link.text)

The title prints fine but the link is nowhere to be found. For reference, below is a copy of the html that is returned for this item.

<item>
<title>An Overview of Logistic Regression</title>
<link/>https://www.kdnuggets.com/2022/02/overview-logistic-regression.html
                                        <comments>https://www.kdnuggets.com/2022/02/overview-logistic-regression.html#disqus_thread</comments>
<dc:creator><![CDATA[Matt Mayo Editor]]></dc:creator>
<pubdate>Fri, 04 Feb 2022 13:00:11 +0000</pubdate>
<category><![CDATA[2022 Feb Tutorials, Overviews]]></category>
<category><![CDATA[Machine Learning]]></category>
<guid ispermalink="false">https://www.kdnuggets.com/?p=137943</guid>
<description><![CDATA[Logistic regression is an extension of linear regression to solve classification problems. Read more on the specifics of this algorithm here.]]></description>
<wfw:commentrss>https://www.kdnuggets.com/2022/02/overview-logistic-regression.html/feed</wfw:commentrss>
<slash:comments>0</slash:comments>
</item>

Thanks in advance.

Body:
Try this one. I think you need to loop throught the "item" to get all links.

from bs4 import BeautifulSoup
import requests

url = "https://www.kdnuggets.com/feed"
resp = requests.get(url)
soup = BeautifulSoup(resp.content)
items = soup.findAll('item')
item = items[1]

links = []
for link in item:
    links.append(link.text)
print(item.title.text)
print(links)


问:
Finding in elements in a tuple and filtering them
Assuming I have a tuple like:

```<code>[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
</code>```

I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:

```<code>[('img-1','iii'), ('img-2','jjj')]
</code>```

Thanks!

答:
Just another way with generator expression (it could make some difference on large lists)</p>

```<code>>>> l = [('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
>>> (x for x in l if x[0].find('img') == 0)
0: <generator object <genexpr> at 0x917a00>
>>> gen = (x for x in l if x[0].find('img') == 0)
>>> list(gen)
1: [('img-1', 'iii'), ('img-2', 'jjj')]
</code>```

Body:
Assuming I have a tuple like:

[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]

I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:

[('img-1','iii'), ('img-2','jjj')]

Thanks!

Body:
Just another way with generator expression (it could make some difference on large lists)

>>> l = [('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
>>> (x for x in l if x[0].find('img') == 0)
0: <generator object <genexpr> at 0x917a00>
>>> gen = (x for x in l if x[0].find('img') == 0)
>>> list(gen)
1: [('img-1', 'iii'), ('img-2', 'jjj')]


问:
MongoDB Query Multiple Specific Documents
I would like to make a single query to my backend database to retrieve a list of results. These results will have a unique "product_id" and they will also have a "variant_id". Items may share product IDs but must have unique variant IDs.
For Example

```<code>{
  product_id:"123",
  variant_id:"000"
}

{
  product_id:"123",
  variant_id:"111"
}

{
  product_id:"987",
  variant_id:"000"
}
</code>```

Is it possible to write a single query that would only find

the Product with an ID of "123" and variant "000"

And the product with ID "987" and variant "000"

```<code>{
  product_id:"123",
  variant_id:"111"
}

{
  product_id:"987",
  variant_id:"000"
}
</code>```

I have search this issue and only found answers related to the $in operator. but I don't think that will allow me to do what I need here? could someone point me in the right direction or let me know if this is even possible. I'm trying to avoid making individual request the the database for each item.

答:
Simple $or can do the job:

```<code>db.collection.find({
$or: [
 {
  "product_id": "123",
  "variant_id": "000"
 },
 {
  "product_id": "987",
  "variant_id": "000"
 }
]
})
</code>```

playground

Body:
I would like to make a single query to my backend database to retrieve a list of results. These results will have a unique "product_id" and they will also have a "variant_id". Items may share product IDs but must have unique variant IDs.
For Example

{
  product_id:"123",
  variant_id:"000"
}

{
  product_id:"123",
  variant_id:"111"
}

{
  product_id:"987",
  variant_id:"000"
}

Is it possible to write a single query that would only find

the Product with an ID of "123" and variant "000"

And the product with ID "987" and variant "000"

{
  product_id:"123",
  variant_id:"111"
}

{
  product_id:"987",
  variant_id:"000"
}

I have search this issue and only found answers related to the $in operator. but I don't think that will allow me to do what I need here? could someone point me in the right direction or let me know if this is even possible. I'm trying to avoid making individual request the the database for each item.

Body:
Simple $or can do the job:

db.collection.find({
$or: [
 {
  "product_id": "123",
  "variant_id": "000"
 },
 {
  "product_id": "987",
  "variant_id": "000"
 }
]
})

playground


问:
How to sort data into new columns based on information in other columns
I have data on fiddler crabs that includes which of its claws are dominate (L or R) (listed as handedness), and the length of specific walking legs (the merus) on each side, which are again sorted by L and R.

Merus_L
Merus_R
Handedness

13.300
10.950
R

9.980
12.250
L

8.750
12.150
L

What I want is to have a column (or a way) to sort these merus values by whether they were on the same side as the major claw (aka dominate claw). for example, if you go back to the above table, the first crab is right handed, so I would like the Merus_R data to be listed under a column called "Major_merus", and the data from Merus_L to be listed under "Minor_merus".
the correct sorting is shown below:

Major_merus
Minor_merus
Handedness

10.950
13.300
R

9.980
12.250
L

8.750
12.150
L

I've already tried the ifelse command recommended by my professor, but I don't know how to use the new data, or why only the Major_merus is correct now.

```<code>Morphdata$Major_merus<-ifelse(Morphdata$Handedness=="L","Merus_L","Merus_R")
Morphdata$Minor_merus<-ifelse(Morphdata$Handedness=="R","Merus_R","Merus_L")
</code>```

Major_merus
Minor_merus

Merus_R
Merus_R

Merus_L
Merus_L

Merus_L
Merus_L

Sorry if this formatting is incorrect, it's my first post!

答:
I modified the solution, I guess this one is more straight forward:

For Major_mercus column, I first created a customized name with paste0 by concatenating Merus_ with the value of Handedness in every row. Then I retrieve the value with get function

For Minor_mercus I basically did the same but I used ifelse to first swap the R and L value in each row and then retrieve the desired value

```<code>library(dplyr)

df %>%
  rowwise() %>%
  mutate(Major_mercus = get(paste0("Merus_", Handedness)),
         Minor_mercus = get(paste0("Merus_", ifelse(Handedness == "R", "L", "R")))) %>%
  select(ends_with("mercus"), Handedness)

# A tibble: 3 x 3
# Rowwise:
  Major_mercus Minor_mercus Handedness
         <dbl>        <dbl> <chr>
1        11.0          13.3 R
2         9.98         12.2 L
3         8.75         12.2 L
</code>```

Body:
I have data on fiddler crabs that includes which of its claws are dominate (L or R) (listed as handedness), and the length of specific walking legs (the merus) on each side, which are again sorted by L and R.

Merus_L
Merus_R
Handedness

13.300
10.950
R

9.980
12.250
L

8.750
12.150
L

What I want is to have a column (or a way) to sort these merus values by whether they were on the same side as the major claw (aka dominate claw). for example, if you go back to the above table, the first crab is right handed, so I would like the Merus_R data to be listed under a column called "Major_merus", and the data from Merus_L to be listed under "Minor_merus".
the correct sorting is shown below:

Major_merus
Minor_merus
Handedness

10.950
13.300
R

9.980
12.250
L

8.750
12.150
L

I've already tried the ifelse command recommended by my professor, but I don't know how to use the new data, or why only the Major_merus is correct now.

Morphdata$Major_merus<-ifelse(Morphdata$Handedness=="L","Merus_L","Merus_R")
Morphdata$Minor_merus<-ifelse(Morphdata$Handedness=="R","Merus_R","Merus_L")

Major_merus
Minor_merus

Merus_R
Merus_R

Merus_L
Merus_L

Merus_L
Merus_L

Sorry if this formatting is incorrect, it's my first post!

Body:
I modified the solution, I guess this one is more straight forward:

For Major_mercus column, I first created a customized name with paste0 by concatenating Merus_ with the value of Handedness in every row. Then I retrieve the value with get function

For Minor_mercus I basically did the same but I used ifelse to first swap the R and L value in each row and then retrieve the desired value

library(dplyr)

df %>%
  rowwise() %>%
  mutate(Major_mercus = get(paste0("Merus_", Handedness)),
         Minor_mercus = get(paste0("Merus_", ifelse(Handedness == "R", "L", "R")))) %>%
  select(ends_with("mercus"), Handedness)

# A tibble: 3 x 3
# Rowwise:
  Major_mercus Minor_mercus Handedness
         <dbl>        <dbl> <chr>
1        11.0          13.3 R
2         9.98         12.2 L
3         8.75         12.2 L


问:
Eclipse running previous program
It is a new problem. I copy paste a program and try to run it in eclipse. But the eclipse keeps running an older program. I have no idea what is going on. ( I saved the program as someone on the internet suggested) In the run button, there are only old programs. So I goes into the run configuration option and double clicked the java application option and somehow the one I am working on right now appeared. And I am able to compile and run the current one. So technically I solved the problem, but I would like an explanation, what was going on?

答:
It just copies path of the server from old project.
It has the TWO solutions :

1) you can simply click on your Tomcat->Modules (Web Modules)-> Edit

And simply change the path with you project name or just put "/".

OR

2) You can right click on your project -> Properties-> Web Prjoect Settings

edit Context root, just simply put "/"

Thank you

Title: Eclipse running previous program


问:
Rollup/Svelte is not producing chunkfiles for dynamic imports. How to make Components to lazy loadable chunks?
I want to lazy load some components in svelte.
No Svelte-kit, just in pure svelte.

I want to dynamically import a Svelte-Component and use it when required:

const About = () => import("../Pages/About.svelte");
```
<p>The import works. The component displays.
But there is no lazy loading or chunk files generated on build nor will there be any lazy fetched requests for the component.</p>
<p>Everything gets bundled in the main.js instead of beeing splitted accordingly.</p>
<p>here is my Rollup config:</p>
<pre class="lang-js prettyprint-override"><code>export default {
    input: 'src/main.ts',
    output: {
        sourcemap: true,
        format: 'esm', // added this to allow modules
        name: 'app',
        dir: 'public/build/',
        inlineDynamicImports: true, //Added this to allow dynamic imports
        chunkFileNames: '[name].[hash].js' // though this would help
    },
    plugins: [
        svelte({
            preprocess: sveltePreprocess({ sourceMap: !production }),
            compilerOptions: {
                // have routing and need hydration maybe this is a issue with chunking?
                hydratable: true,
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),
        scss({
            failOnError: true,
            include: ['src/**/*.css', 'src/**/*.scss', 'src/**/*.sass'],
        }),
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs({

        }),
        // I use typescript mabye this could be an issue?
        typescript({
            sourceMap: !production,
            inlineSources: !production,
            include: ['src/**/*.ts', 'src/**/*.js'],
        }),
        copy({
            targets: [
                { src: 'public/index.html', dest: 'public', rename: '200.html' }
            ]
        }),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

</code>```

Did I miss something in my config?
Or how should I set up Svelte component code splitting/lazy loaded components ?

EDIT: This is how my build directory looks like after running build

As you can see, there is no chunks. Only one main.js.

答:
I needed to remove the inline imports acually...

It sounds wierd:
But my config now looks like this:

export default {
    input: 'src/main.ts',
    output: {
        sourcemap: true,
        format: 'esm',
        name: 'app',
        dir: 'public/build/',
        // inlineDynamicImports: true, <- removed this
        chunkFileNames: '[name].chunk.js',
    },
    plugins: [
        svelte({
            preprocess: sveltePreprocess({ sourceMap: !production }),
            compilerOptions: {
                // have routing and need hydration maybe this is a issue with chunking?
                hydratable: true,
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),
        scss({
            failOnError: true,
            include: ['src/**/*.css', 'src/**/*.scss', 'src/**/*.sass'],
        }),
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs({

        }),
        // I use typescript mabye this could be an issue?
        typescript({
            sourceMap: !production,
            inlineSources: !production,
            include: ['src/**/*.ts', 'src/**/*.js'],
        }),
        copy({
            targets: [
                { src: 'public/index.html', dest: 'public', rename: '200.html' }
            ]
        }),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

```

the result is:

Body:
I want to lazy load some components in svelte.
No Svelte-kit, just in pure svelte.

I want to dynamically import a Svelte-Component and use it when required:

const About = () => import("../Pages/About.svelte");

The import works. The component displays.
But there is no lazy loading or chunk files generated on build nor will there be any lazy fetched requests for the component.

Everything gets bundled in the main.js instead of beeing splitted accordingly.

here is my Rollup config:

export default {
    input: 'src/main.ts',
    output: {
        sourcemap: true,
        format: 'esm', // added this to allow modules
        name: 'app',
        dir: 'public/build/',
        inlineDynamicImports: true, //Added this to allow dynamic imports
        chunkFileNames: '[name].[hash].js' // though this would help
    },
    plugins: [
        svelte({
            preprocess: sveltePreprocess({ sourceMap: !production }),
            compilerOptions: {
                // have routing and need hydration maybe this is a issue with chunking?
                hydratable: true,
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),
        scss({
            failOnError: true,
            include: ['src/**/*.css', 'src/**/*.scss', 'src/**/*.sass'],
        }),
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs({

        }),
        // I use typescript mabye this could be an issue?
        typescript({
            sourceMap: !production,
            inlineSources: !production,
            include: ['src/**/*.ts', 'src/**/*.js'],
        }),
        copy({
            targets: [
                { src: 'public/index.html', dest: 'public', rename: '200.html' }
            ]
        }),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

Did I miss something in my config?
Or how should I set up Svelte component code splitting/lazy loaded components ?

EDIT: This is how my build directory looks like after running build

As you can see, there is no chunks. Only one main.js.

Body:
I needed to remove the inline imports acually...

It sounds wierd:
But my config now looks like this:

export default {
    input: 'src/main.ts',
    output: {
        sourcemap: true,
        format: 'esm',
        name: 'app',
        dir: 'public/build/',
        // inlineDynamicImports: true, <- removed this
        chunkFileNames: '[name].chunk.js',
    },
    plugins: [
        svelte({
            preprocess: sveltePreprocess({ sourceMap: !production }),
            compilerOptions: {
                // have routing and need hydration maybe this is a issue with chunking?
                hydratable: true,
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),
        scss({
            failOnError: true,
            include: ['src/**/*.css', 'src/**/*.scss', 'src/**/*.sass'],
        }),
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs({

        }),
        // I use typescript mabye this could be an issue?
        typescript({
            sourceMap: !production,
            inlineSources: !production,
            include: ['src/**/*.ts', 'src/**/*.js'],
        }),
        copy({
            targets: [
                { src: 'public/index.html', dest: 'public', rename: '200.html' }
            ]
        }),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

the result is:


问:
How can I map a \\wsl$\ type unc path to a windows drive letter?
I'm using eclipse on windows to connect to files on a wsl, and I have run into what is apparently an eclipse bug which file names such as \wsl$\folder1\pom.xml get mangled.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=577938

A comment in the bug report suggests a possible workaround

```<code>A workaround is to map the UNC path to a drive letter, but this shouldn't be necessary
</code>```

How would I do that?

答:
I did it this way (drive j: was available)

```<code>net use j: \\wsl$\Ubuntu
</code>```

Note that this is persistent, and if not deleted can cause wsl2 to restart by itself.  After doing this I was able to access files on the Ubuntu distro from windows emacs.

to delete it:

```<code>net use /del j:
</code>```

Body:
I'm using eclipse on windows to connect to files on a wsl, and I have run into what is apparently an eclipse bug which file names such as \wsl$\folder1\pom.xml get mangled.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=577938

A comment in the bug report suggests a possible workaround

A workaround is to map the UNC path to a drive letter, but this shouldn't be necessary

How would I do that?

Body:
I did it this way (drive j: was available)

net use j: \\wsl$\Ubuntu

Note that this is persistent, and if not deleted can cause wsl2 to restart by itself.  After doing this I was able to access files on the Ubuntu distro from windows emacs.

to delete it:

net use /del j:


问:
Room: How to automigrate DB for new table?
I want to do a simple change on my room database: adding a new table.

My room version is: 2.4.1

According to https://medium.com/androiddevelopers/room-auto-migrations-d5370b0ca6eb, this task should be easy using an auto-migration.

Here is what the relevant part of my DB class looks before the migration:

```<code>@Database(
    entities = [FlashCard::class, Pool::class],
    version = 2
)
abstract class DB : RoomDatabase() {
 ...
</code>```

For the migration, I changed that part to:

```<code>@Database(
    entities = [FlashCard::class, Pool::class, FlashCardRunEvent::class],
    version = 3,
    autoMigrations = [
        AutoMigration (from = 2, to = 3)
    ]
)
abstract class DB : RoomDatabase() {
...
</code>```

It all compiles fine. The app runs until the first interaction with the database.

Then, the app crashes and I get this in my log:

```<code>Caused by: java.lang.IllegalStateException: Migration didn't properly handle: FlashCardRunEvent(com.ravenala.flashy.room.FlashCardRunEvent).
     Expected:
    TableInfo{name='FlashCardRunEvent', columns={newBox=Column{name='newBox', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, flashCardId=Column{name='flashCardId', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, timeStampInSeconds=Column{name='timeStampInSeconds', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, oldBox=Column{name='oldBox', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}
     Found:
    TableInfo{name='FlashCardRunEvent', columns={}, foreignKeys=[], indices=[]}
</code>```

I do not know what to make out of this. What's up with that difference between "Expected" and "Found". I had hoped room would simply see the new table, generate a scheme out of it and create the table. Are the times of writing SQL statements for simple migrations as this one not over?

答:
What's up with that difference between "Expected" and "Found"

Expected is the schema according to Room's processing of the classes defined via the entities argument in the @Database annotation.

Found is the schema found in the database when opening it, in your case after the auto migration.

Reporting that it  found TableInfo{name='FlashCardRunEvent', columns={}, foreignKeys=[], indices=[]} indicates that the FlasCardRunEvent table does not exist after the AutoMigration.

I had hoped room would simply see the new table, generate a scheme out of it and create the table. Are the times of writing SQL statements for simple migrations as this one not over?

Why is not apparent from the code you have presented. Certainly AutoMigration has the ability to create new tables (have tested this with a simple scenario).

It all compiles fine.

Did you check the build log for any warnings? These, if any could be a clue as to what is happening.

Why Room is not creating the table

A Guess :-

You haven't inadvertently bypassed migration by forgetting something (such as not adding the FlashCardRunEvent entity to the entities defined in the list of entities in the @Database annotation) run and thus increased the version to version 3; then corrected the omission and run while still at version 3?

Perhaps try adding an AutoMigration from 3-4 and and then running.

Otherwise I'm unsure. Look at the generated java (visible via Android View) e.g. :-

This should be something like :-

```<code>class AppDatabase_AutoMigration_2_3_Impl extends Migration {
  public AppDatabase_AutoMigration_2_3_Impl() {
    super(2, 3);
  }

  @Override
  public void migrate(@NonNull SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE IF NOT EXISTS `FlashCardRunEvent` (`id` INTEGER, `newBox` INTEGER NOT NULL, `flashCardId` INTEGER NOT NULL, `timeStampInSeconds` INTEGER NOT NULL, `oldBox` INTEGER NOT NULL, PRIMARY KEY(`id`))");
  }
}
</code>```

you would expect ONLY the single execSQL as you are just adding the single table.

Additionally in the generated java you would expect in the class that is DB_Impl for the createAllTables method to also include a CREATE TABLE for the FlashCardRunEvent table.

As can be seen the above,  code is derived from a test albeit it different initial tables but with migration 2-3 adding the FlashCardRunEvent table ( by building the entity class from the expected) i.e. :-

```<code>@Entity
data class FlashCardRunEvent(
    /*
        TableInfo{name='FlashCardRunEvent',
        columns={
            newBox=Column{name='newBox', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'},
            flashCardId=Column{name='flashCardId', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'},
            timeStampInSeconds=Column{name='timeStampInSeconds', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'},
            id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'},
            oldBox=Column{name='oldBox', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}},
            foreignKeys=[], indices=[]}
     */
    @PrimaryKey
    val id: Long?,
    val newBox: Long,
    val flashCardId: Long,
    val timeStampInSeconds: Long,
    val oldBox: Long
)
</code>```

The test successfully creates the table. The one noticeable difference being that I have coded exportSchema = true in the @Database annotation rather than rely upon it to default to true.

Running the test and the FlasCardRunEvent table is created :-

Body:
I want to do a simple change on my room database: adding a new table.

My room version is: 2.4.1

According to https://medium.com/androiddevelopers/room-auto-migrations-d5370b0ca6eb, this task should be easy using an auto-migration.

Here is what the relevant part of my DB class looks before the migration:

@Database(
    entities = [FlashCard::class, Pool::class],
    version = 2
)
abstract class DB : RoomDatabase() {
 ...

For the migration, I changed that part to:

@Database(
    entities = [FlashCard::class, Pool::class, FlashCardRunEvent::class],
    version = 3,
    autoMigrations = [
        AutoMigration (from = 2, to = 3)
    ]
)
abstract class DB : RoomDatabase() {
...

It all compiles fine. The app runs until the first interaction with the database.

Then, the app crashes and I get this in my log:

Caused by: java.lang.IllegalStateException: Migration didn't properly handle: FlashCardRunEvent(com.ravenala.flashy.room.FlashCardRunEvent).
     Expected:
    TableInfo{name='FlashCardRunEvent', columns={newBox=Column{name='newBox', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, flashCardId=Column{name='flashCardId', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, timeStampInSeconds=Column{name='timeStampInSeconds', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, oldBox=Column{name='oldBox', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}
     Found:
    TableInfo{name='FlashCardRunEvent', columns={}, foreignKeys=[], indices=[]}

I do not know what to make out of this. What's up with that difference between "Expected" and "Found". I had hoped room would simply see the new table, generate a scheme out of it and create the table. Are the times of writing SQL statements for simple migrations as this one not over?

Body:
What's up with that difference between "Expected" and "Found"

Expected is the schema according to Room's processing of the classes defined via the entities argument in the @Database annotation.

Found is the schema found in the database when opening it, in your case after the auto migration.

Reporting that it  found TableInfo{name='FlashCardRunEvent', columns={}, foreignKeys=[], indices=[]} indicates that the FlasCardRunEvent table does not exist after the AutoMigration.

I had hoped room would simply see the new table, generate a scheme out of it and create the table. Are the times of writing SQL statements for simple migrations as this one not over?

Why is not apparent from the code you have presented. Certainly AutoMigration has the ability to create new tables (have tested this with a simple scenario).

It all compiles fine.

Did you check the build log for any warnings? These, if any could be a clue as to what is happening.

Why Room is not creating the table

A Guess :-

You haven't inadvertently bypassed migration by forgetting something (such as not adding the FlashCardRunEvent entity to the entities defined in the list of entities in the @Database annotation) run and thus increased the version to version 3; then corrected the omission and run while still at version 3?

Perhaps try adding an AutoMigration from 3-4 and and then running.

Otherwise I'm unsure. Look at the generated java (visible via Android View) e.g. :-

This should be something like :-

class AppDatabase_AutoMigration_2_3_Impl extends Migration {
  public AppDatabase_AutoMigration_2_3_Impl() {
    super(2, 3);
  }

  @Override
  public void migrate(@NonNull SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE IF NOT EXISTS `FlashCardRunEvent` (`id` INTEGER, `newBox` INTEGER NOT NULL, `flashCardId` INTEGER NOT NULL, `timeStampInSeconds` INTEGER NOT NULL, `oldBox` INTEGER NOT NULL, PRIMARY KEY(`id`))");
  }
}

you would expect ONLY the single execSQL as you are just adding the single table.

Additionally in the generated java you would expect in the class that is DB_Impl for the createAllTables method to also include a CREATE TABLE for the FlashCardRunEvent table.

As can be seen the above,  code is derived from a test albeit it different initial tables but with migration 2-3 adding the FlashCardRunEvent table ( by building the entity class from the expected) i.e. :-

@Entity
data class FlashCardRunEvent(
    /*
        TableInfo{name='FlashCardRunEvent',
        columns={
            newBox=Column{name='newBox', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'},
            flashCardId=Column{name='flashCardId', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'},
            timeStampInSeconds=Column{name='timeStampInSeconds', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'},
            id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'},
            oldBox=Column{name='oldBox', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}},
            foreignKeys=[], indices=[]}
     */
    @PrimaryKey
    val id: Long?,
    val newBox: Long,
    val flashCardId: Long,
    val timeStampInSeconds: Long,
    val oldBox: Long
)

The test successfully creates the table. The one noticeable difference being that I have coded exportSchema = true in the @Database annotation rather than rely upon it to default to true.

Running the test and the FlasCardRunEvent table is created :-


问:
C# implementation of T-SQL round function
I'm trying to reproduce in C# the behavior of the T-SQL Round function when a truncate function is used.

This is the SQL behavior I'm trying to reproduce in C#:

```<code>SELECT ROUND(150.757,2,0) -- 150.76
SELECT ROUND(150.757,2,1) -- 150.75

SELECT ROUND(150.747,2,0) -- 150.75
SELECT ROUND(150.747,2,1) -- 150.74
</code>```

In System.Math there are two methods that I tried to use.

The first one, Math.Truncate truncates to the whole part only, so it won't help me.

The other method is Math.Round.

This method has 2 interesting overloads.

```<code>Math.Round(decimal,int)
Math.Round(decimal,int,System.MidpointRounding)
</code>```

The MidpointRounding enumeration options are:

```<code>System.MidpointRounding.AwayFromZero
// When a number is halfway between two others,
// it is rounded toward the nearest number that is away from zero.

System.MidpointRounding.ToEven
// When a number is halfway between two others,
// it is rounded toward the nearest even number.
</code>```

Executing the two overloads of Math.Round with the same data as SQL I've got the following result:

```<code>Math.Round(150.757, 2, MidpointRounding.AwayFromZero) // 150.76
Math.Round(150.757, 2, MidpointRounding.ToEven) // 150.76

Math.Round(150.747, 2, MidpointRounding.AwayFromZero) // 150.75
Math.Round(150.747, 2, MidpointRounding.ToEven) // 150.75
</code>```

Given that none of the MidpointRounding solve my problem, what is the best way to reproducte the T-SQL function in C#?

Update:

After implementing Paul's answer I noticed one extra odd behavior from T-SQL ROUND function:

```<code>SELECT ROUND(150.747,-2,1) // 100
SELECT ROUND(150.747,-2) // 200
</code>```

I edited Paul's answer to include support for this edge case.

答:
I've elaborated a bit on Paul's answer so that his method provides the same behavior as TSQL's round (btw I didn't make my version an extension method):</p>

```<code>    using System;

    namespace TestTSql
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(TSqlRound(150.757, 2, false));    // 150.76
                Console.WriteLine(TSqlRound(150.757, 2, true));     // 150.75
                Console.WriteLine(TSqlRound(150.747, 2, false));    // 150.75
                Console.WriteLine(TSqlRound(150.747, 2, true));     // 150.74
                Console.ReadKey();
            }

            public static double TSqlRound(double input, int length, bool truncate = false)
            {
                if (truncate)
                {
                    double factor = Math.Pow(10, length);
                    return Math.Truncate(input * factor) / factor;
                }
                else return Math.Round(input, length);
            }
        }
    }
</code>```

Body:
I'm trying to reproduce in C# the behavior of the T-SQL Round function when a truncate function is used.

This is the SQL behavior I'm trying to reproduce in C#:

SELECT ROUND(150.757,2,0) -- 150.76
SELECT ROUND(150.757,2,1) -- 150.75

SELECT ROUND(150.747,2,0) -- 150.75
SELECT ROUND(150.747,2,1) -- 150.74

In System.Math there are two methods that I tried to use.

The first one, Math.Truncate truncates to the whole part only, so it won't help me.

The other method is Math.Round.

This method has 2 interesting overloads.

Math.Round(decimal,int)
Math.Round(decimal,int,System.MidpointRounding)

The MidpointRounding enumeration options are:

System.MidpointRounding.AwayFromZero
// When a number is halfway between two others,
// it is rounded toward the nearest number that is away from zero.

System.MidpointRounding.ToEven
// When a number is halfway between two others,
// it is rounded toward the nearest even number.

Executing the two overloads of Math.Round with the same data as SQL I've got the following result:

Math.Round(150.757, 2, MidpointRounding.AwayFromZero) // 150.76
Math.Round(150.757, 2, MidpointRounding.ToEven) // 150.76

Math.Round(150.747, 2, MidpointRounding.AwayFromZero) // 150.75
Math.Round(150.747, 2, MidpointRounding.ToEven) // 150.75

Given that none of the MidpointRounding solve my problem, what is the best way to reproducte the T-SQL function in C#?

Update:

After implementing Paul's answer I noticed one extra odd behavior from T-SQL ROUND function:

SELECT ROUND(150.747,-2,1) // 100
SELECT ROUND(150.747,-2) // 200

I edited Paul's answer to include support for this edge case.

Body:
I've elaborated a bit on Paul's answer so that his method provides the same behavior as TSQL's round (btw I didn't make my version an extension method):

    using System;

    namespace TestTSql
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(TSqlRound(150.757, 2, false));    // 150.76
                Console.WriteLine(TSqlRound(150.757, 2, true));     // 150.75
                Console.WriteLine(TSqlRound(150.747, 2, false));    // 150.75
                Console.WriteLine(TSqlRound(150.747, 2, true));     // 150.74
                Console.ReadKey();
            }

            public static double TSqlRound(double input, int length, bool truncate = false)
            {
                if (truncate)
                {
                    double factor = Math.Pow(10, length);
                    return Math.Truncate(input * factor) / factor;
                }
                else return Math.Round(input, length);
            }
        }
    }


问:
firebase admin SDK create user and send verification email
How can I send a verification email after I create a user with firebase admin SDK?
I am trying to combine createUser function and sendEmailVerification function
could somebody indicate a hint or an answer? thanks

update:

the user creation is being done by an admin user who is already signed in in the app, so the admin user is just creating users on the dashboad. This is completely different from the registeration methods.

update 2:

I tried to follow bojeil's answer, I am still stuck with the step that user signs in with the custom token. It gets into conflict with my current admin user session, the admin users gets kicked out and instead the new user is signed in and even when I sign out the new user, the admin user is still out and needs to sign in to get back into the app.

here is my code inside the app after I get the custom token:

```<code>$http.post('/.custom-token', {uid: $scope.data.data.uid})
        .then(function (response) {
            console.log("custom token here:", response.data.token);
            firebase.auth().signInWithCustomToken(response.data.token)
                .then(function (firebaseUser) {
                    firebaseUser.sendEmailVerification();
                    firebase.auth().signOut().then(function() {
                        // Sign-out successful.
                        console.log("signed out success");
                    }, function(error) {
                        // An error happened.
                    });
                })

                .catch(function(error) {
                    // Handle Errors here.
                    var errorCode = error.code;
                    var errorMessage = error.message;
                    // ...
                });

        });
</code>```

so, I get the token, sign in the new user, send the email verification link, and then, sign out the new user.
But my admin user who is doing all of this gets signed out as well.
what am I missing here?

答:
Here's bojeil's steps in code, which work in a NodeJS Firebase Cloud Function. Assuming that 'admin' is your Firebase Admin SDK instance, and 'firebase' is your Firebase Client SDK instance.

```<code>var userId = "YOURUSERIDHERE";
admin.auth()
        .createCustomToken(userId)
        .then((customToken) => {
            return firebase.auth().signInWithCustomToken(customToken)
        })
        .then((data) => {
            return data.user.sendEmailVerification({url: "http://YOURREDIRECTURL"});
        }).then((result) => {
            console.log("success");
        }).catch((error) => {
            console.log("faillure");
        });
</code>```

Make sure that you've setup the Admin SDK properly, by creating a service account and initialising it in the Admin SDK configuration snippet.

Body:
How can I send a verification email after I create a user with firebase admin SDK?
I am trying to combine createUser function and sendEmailVerification function
could somebody indicate a hint or an answer? thanks

update:

the user creation is being done by an admin user who is already signed in in the app, so the admin user is just creating users on the dashboad. This is completely different from the registeration methods.

update 2:

I tried to follow bojeil's answer, I am still stuck with the step that user signs in with the custom token. It gets into conflict with my current admin user session, the admin users gets kicked out and instead the new user is signed in and even when I sign out the new user, the admin user is still out and needs to sign in to get back into the app.

here is my code inside the app after I get the custom token:

$http.post('/.custom-token', {uid: $scope.data.data.uid})
        .then(function (response) {
            console.log("custom token here:", response.data.token);
            firebase.auth().signInWithCustomToken(response.data.token)
                .then(function (firebaseUser) {
                    firebaseUser.sendEmailVerification();
                    firebase.auth().signOut().then(function() {
                        // Sign-out successful.
                        console.log("signed out success");
                    }, function(error) {
                        // An error happened.
                    });
                })

                .catch(function(error) {
                    // Handle Errors here.
                    var errorCode = error.code;
                    var errorMessage = error.message;
                    // ...
                });

        });

so, I get the token, sign in the new user, send the email verification link, and then, sign out the new user.
But my admin user who is doing all of this gets signed out as well.
what am I missing here?

Body:
Here's bojeil's steps in code, which work in a NodeJS Firebase Cloud Function. Assuming that 'admin' is your Firebase Admin SDK instance, and 'firebase' is your Firebase Client SDK instance.

var userId = "YOURUSERIDHERE";
admin.auth()
        .createCustomToken(userId)
        .then((customToken) => {
            return firebase.auth().signInWithCustomToken(customToken)
        })
        .then((data) => {
            return data.user.sendEmailVerification({url: "http://YOURREDIRECTURL"});
        }).then((result) => {
            console.log("success");
        }).catch((error) => {
            console.log("faillure");
        });

Make sure that you've setup the Admin SDK properly, by creating a service account and initialising it in the Admin SDK configuration snippet.


问:
fatal error: google fonts in flutter throws error
i'm getting this error in flutter

```<code>../../../snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/google_fonts-2.3.0/lib/google_fonts.dart:142265:7: Error: No named parameter with the name 'displayLarge'.
      displayLarge:
      ^^^^^^^^^^^^
../../../snap/flutter/common/flutter/packages/flutter/lib/src/material/text_theme.dart:81:9: Context: Found this candidate, but the arguments don't match.
  const TextTheme({
        ^^^^^^^^^

</code>```

while running mobile application

some code snippets...

pubspec.yaml

```<code>dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.4
  cupertino_icons: ^1.0.2
  google_fonts:
  get:
</code>```

code

```<code>     Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Details',
                style: GoogleFonts.pacifico(),
              ),
            )
</code>```

thank you in advance

答:
You should try setting a specific version as it seems to be caused by a requirement by the recent google_fonts update.

Using google_fonts:2.1.1 worked for me.

Also check https://github.com/material-foundation/google-fonts-flutter/issues/219 .

Body:
i'm getting this error in flutter

../../../snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/google_fonts-2.3.0/lib/google_fonts.dart:142265:7: Error: No named parameter with the name 'displayLarge'.
      displayLarge:
      ^^^^^^^^^^^^
../../../snap/flutter/common/flutter/packages/flutter/lib/src/material/text_theme.dart:81:9: Context: Found this candidate, but the arguments don't match.
  const TextTheme({
        ^^^^^^^^^

while running mobile application

some code snippets...

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.4
  cupertino_icons: ^1.0.2
  google_fonts:
  get:

code

     Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Details',
                style: GoogleFonts.pacifico(),
              ),
            )

thank you in advance


问:
Change y-axis range in Pandas.boxplot()
I use the following boxplot function from Pandas,

```<code>df.boxplot(column=['D1', 'D2'])
</code>```

and I would like to change the y-axis range. However, I didn't see such an option in the document. Any idea for that?

答:
You can do so editing the axis-object - you can either do

```<code>ax = df.boxplot(column=['D1', 'D2'])
ax.set_ylim(0, 10)
</code>```

or

```<code>import matplotlib.pyplot as plt
fix, ax = plt.subplots(1, 1)
df.boxplot(column=['D1', 'D2'], ax=ax)
ax.set_ylim(0, 10)
</code>```

figure is the whole graphic, ax is the diagram. plt.subplots(1, 1) is the number of diagrams(rows, columns), in this case 1 - so ax is just one diagram. Otherwise ax would be a list of axis objects.

Title: Change y-axis range in Pandas.boxplot()

Body:
I use the following boxplot function from Pandas,

df.boxplot(column=['D1', 'D2'])

and I would like to change the y-axis range. However, I didn't see such an option in the document. Any idea for that?

Body:
You can do so editing the axis-object - you can either do

ax = df.boxplot(column=['D1', 'D2'])
ax.set_ylim(0, 10)

or

import matplotlib.pyplot as plt
fix, ax = plt.subplots(1, 1)
df.boxplot(column=['D1', 'D2'], ax=ax)
ax.set_ylim(0, 10)

figure is the whole graphic, ax is the diagram. plt.subplots(1, 1) is the number of diagrams(rows, columns), in this case 1 - so ax is just one diagram. Otherwise ax would be a list of axis objects.


问:
Concatenate the count number with a duplicate text pattern using python ReGex
I have very large text file. It contains duplicate text patterns. In the code below, we can see the pattern "Path": "/home/downloads/file" exists 3 times. I want to add/concat the count number at the end of each Path pattern according to its position. E.g. when the code finds first Path pattern, it should concatenate 1 at the end like "Path": "/home/downloads/file/1". For the second Path pattern, it should add 2 at the end e.g.
"Path": "/home/downloads/file/2" and so on. My current code counts the patterns but doesn't concatenate it properly at the end of the Path pattern. Below is my code, its current output and the desired output. I've also added a small chunk from the text.

```<code>from io import StringIO
import re

file = StringIO("""{
    "title": "Pilot",
    "image": [
        {
            "Path": "/home/downloads/file"
            "Path": "/home/downloads/file",
            "Path": "/home/downloads/file"
        }
    ],
    "content": "<p>The wing man ...</p>"
}""")

text = file.read()
patterns = r'"Path": "(.*?)"'

count = 0

for match in re.finditer(patterns, text):
   count += 1
   replace = '"Path": "\\1/' + str(count) + '"'
   text = re.sub(patterns, replace, text)

print(text)

</code>```

Current output of the code is:

```<code>{
    "title": "Pilot",
    "image": [
        {
            "Path": "/home/downloads/file/1/2/3"
            "Path": "/home/downloads/file/1/2/3",
            "Path": "/home/downloads/file/1/2/3"
        }
    ],
    "content": "<p>The wing man ...</p>"
}

</code>```

Desired output is:

```<code>{
    "title": "Pilot",
    "image": [
        {
            "Path": "/home/downloads/file/1"
            "Path": "/home/downloads/file/2",
            "Path": "/home/downloads/file/3"
        }
    ],
    "content": "<p>The wing man ...</p>"
}
</code>```

答:
You have to limit the times that re.sub makes the replacement:

```<code>for cnt,match in enumerate(re.finditer(patterns, text),1):
    text = re.sub(patterns, rf'\1/{cnt}', text, count=1)
</code>```

But as others have said, you should use JSON tools to work with JSON -- not regex.

Here is a simple example:

```<code>import json
data=json.loads(file.read())
k,v=data["image"][0].popitem()
data["image"]=[]
for i in range(1,4):
    data["image"].append(f"{v}/{i}")

>>> print(json.dumps(data,sort_keys=True, indent=4))
{
    "content": "<p>The wing man ...</p>",
    "image": [
        "/home/downloads/file/1",
        "/home/downloads/file/2",
        "/home/downloads/file/3"
    ],
    "title": "Pilot"
}
</code>```

Body:
I have very large text file. It contains duplicate text patterns. In the code below, we can see the pattern "Path": "/home/downloads/file" exists 3 times. I want to add/concat the count number at the end of each Path pattern according to its position. E.g. when the code finds first Path pattern, it should concatenate 1 at the end like "Path": "/home/downloads/file/1". For the second Path pattern, it should add 2 at the end e.g.
"Path": "/home/downloads/file/2" and so on. My current code counts the patterns but doesn't concatenate it properly at the end of the Path pattern. Below is my code, its current output and the desired output. I've also added a small chunk from the text.

from io import StringIO
import re

file = StringIO("""{
    "title": "Pilot",
    "image": [
        {
            "Path": "/home/downloads/file"
            "Path": "/home/downloads/file",
            "Path": "/home/downloads/file"
        }
    ],
    "content": "
The wing man ...
"
}""")

text = file.read()
patterns = r'"Path": "(.*?)"'

count = 0

for match in re.finditer(patterns, text):
   count += 1
   replace = '"Path": "\\1/' + str(count) + '"'
   text = re.sub(patterns, replace, text)

print(text)

Current output of the code is:

{
    "title": "Pilot",
    "image": [
        {
            "Path": "/home/downloads/file/1/2/3"
            "Path": "/home/downloads/file/1/2/3",
            "Path": "/home/downloads/file/1/2/3"
        }
    ],
    "content": "
The wing man ...
"
}

Desired output is:

{
    "title": "Pilot",
    "image": [
        {
            "Path": "/home/downloads/file/1"
            "Path": "/home/downloads/file/2",
            "Path": "/home/downloads/file/3"
        }
    ],
    "content": "
The wing man ...
"
}

Body:
You have to limit the times that re.sub makes the replacement:

for cnt,match in enumerate(re.finditer(patterns, text),1):
    text = re.sub(patterns, rf'\1/{cnt}', text, count=1)

But as others have said, you should use JSON tools to work with JSON -- not regex.

Here is a simple example:

import json
data=json.loads(file.read())
k,v=data["image"][0].popitem()
data["image"]=[]
for i in range(1,4):
    data["image"].append(f"{v}/{i}")

>>> print(json.dumps(data,sort_keys=True, indent=4))
{
    "content": "<p>The wing man ...</p>",
    "image": [
        "/home/downloads/file/1",
        "/home/downloads/file/2",
        "/home/downloads/file/3"
    ],
    "title": "Pilot"
}


答:
You can use re.sub with a function to replace non-overlapping occurences as follows.

Code

```<code>text = file.read()
patterns = r'"Path": "(.*?)"'

def repl(m):
    global count
    count += 1                                         # update count with each
                                                       # detection of pattern
    return m.group(0).replace('file', f'file/{count}') # Desired substitution

count = 0
text = re.sub(patterns, repl, text)  # applies function repl to each detection of pattern

print(text)
</code>```

Output

```<code>{
    "title": "Pilot",
    "image": [
        {
            "Path": "/home/downloads/file/1"
            "Path": "/home/downloads/file/2",
            "Path": "/home/downloads/file/3"
        }
    ],
    "content": "<p>The wing man ...</p>"
}
</code>```

Title: Concatenate the count number with a duplicate text pattern using python ReGex

Body:
You can use re.sub with a function to replace non-overlapping occurences as follows.

Code

text = file.read()
patterns = r'"Path": "(.*?)"'

def repl(m):
    global count
    count += 1                                         # update count with each
                                                       # detection of pattern
    return m.group(0).replace('file', f'file/{count}') # Desired substitution

count = 0
text = re.sub(patterns, repl, text)  # applies function repl to each detection of pattern

print(text)

Output

{
    "title": "Pilot",
    "image": [
        {
            "Path": "/home/downloads/file/1"
            "Path": "/home/downloads/file/2",
            "Path": "/home/downloads/file/3"
        }
    ],
    "content": "<p>The wing man ...</p>"
}


问:
Parsing specific column's using inputs
I've been trying to wrap my head around a method of parsing a text file and specifying the specific columns you want. So for example I ask them to input what columns they want to parse out of the text file.

```<code>Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17
</code>```

So the person will input the txt file and then inputs that they want Column 0 and 2 it will give them a result of

```<code>Joe,19
Jake,19
Bob,19
</code>```

I know I can do the .split()[0] but I dont want to hard code it I want it to work off the input. Im pretty sure its easy but for some reason I just cant get my head around the way to do it.

To make it a bit more in depth I want to make a program that you input a txt file and it asks you for what sections you would like then it prints out the seconds you wanted.

InputFileName = input("Please enter the name of file you would like to parse: ")
ParseSelection = input("Please enter the section's you want to parse: ")
```
<p>and then from that it will open the txt file see that the user asked for Section 0 and 2 and just print them out as "Section 0 | Section 2"</p>
```Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17
```
<p>open Names.txt it see that the person asked for Section 0 and 2 So it prints out</p>
```Joe | 19
Jake | 19
Bob | 19
```

答:
Your question is a bit vague, but i'll attempt to help you here.
You're on the right lines, however for comma separated text it would be best to do this:

```<code>input().split(',')[0:4:2]
</code>```

You can always use modules like this also (much easier):-
https://docs.python.org/3/library/csv.html

Title: Parsing specific column's using inputs

Body:
I've been trying to wrap my head around a method of parsing a text file and specifying the specific columns you want. So for example I ask them to input what columns they want to parse out of the text file.

Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17

So the person will input the txt file and then inputs that they want Column 0 and 2 it will give them a result of

Joe,19
Jake,19
Bob,19

I know I can do the .split()[0] but I dont want to hard code it I want it to work off the input. Im pretty sure its easy but for some reason I just cant get my head around the way to do it.

To make it a bit more in depth I want to make a program that you input a txt file and it asks you for what sections you would like then it prints out the seconds you wanted.

InputFileName = input("Please enter the name of file you would like to parse: ")
ParseSelection = input("Please enter the section's you want to parse: ")

and then from that it will open the txt file see that the user asked for Section 0 and 2 and just print them out as "Section 0 | Section 2"

Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17

open Names.txt it see that the person asked for Section 0 and 2 So it prints out

Joe | 19
Jake | 19
Bob | 19

Body:
Your question is a bit vague, but i'll attempt to help you here.
You're on the right lines, however for comma separated text it would be best to do this:

input().split(',')[0:4:2]

You can always use modules like this also (much easier):-
https://docs.python.org/3/library/csv.html


问:
Converting Protobuf3 with enum to JSON in Go
How can I convert grpc/protobuf3 message to JSON where the enum is represented as string?

For example, the protobuf message:

```<code>enum Level {
    WARNING = 0;
    FATAL = 1;
    SEVERE = 2;
    ...
}

message Http {
    string message = 1;
    Level level = 2;
}
</code>```

Is converted by:

```<code>j, _ := json.MarshalIndent(protoMessage, "", "\t")
</code>```

To:

```<code>{
    "message": "Hello world!",
    "level": 2,
}
</code>```

I wish to get:

```<code>{
    "message": "Hello world!",
    "level": "SEVERE",
}
</code>```

Thanks

答:
For my use case, I wanted to write it to a file. Using the most recent packages as of this date, this was as close to a regular encoding/json marshal as I could get.

I used the google.golang.org/protobuf/encoding/protojson package and the .ProtoReflect().Interface() methods of my protocol buffer data structure.

package main

import (
    "io/ioutil"
    "log"

    "google.golang.org/protobuf/encoding/protojson"

    "myproject/proto"
)

func main() {
    myProtoStruct := proto.MyType{}

    data, err := protojson.Marshal(myProtoStruct.ProtoReflect().Interface())
    if err != nil {
        log.Fatalf("Failed to JSON marhsal protobuf.\nError: %s", err.Error())
    }

    err = ioutil.WriteFile("my.proto.dat", data, 0600)
    if err != nil {
        log.Fatalf("Failed to write protobuf data to file.\nError: %s", err.Error())
    }

    log.Println("Written to file.")
}
```

Body:
How can I convert grpc/protobuf3 message to JSON where the enum is represented as string?

For example, the protobuf message:

enum Level {
    WARNING = 0;
    FATAL = 1;
    SEVERE = 2;
    ...
}

message Http {
    string message = 1;
    Level level = 2;
}

Is converted by:

j, _ := json.MarshalIndent(protoMessage, "", "\t")

To:

{
    "message": "Hello world!",
    "level": 2,
}

I wish to get:

{
    "message": "Hello world!",
    "level": "SEVERE",
}

Thanks