问:
RSA Encryption and Decryption successed in JS, but Decryption fails in C#
For security, I encrypted some data, such as username, passwords, and emails in the browser by jsencrypt which is a A Javascript library to perform OpenSSL RSA Encryption, Decryption. And then I decrypt the cipher data using RSACryptoServiceProvider by C#. The public key, and private key are generated by c#：

```<code><RSAKeyValue><Modulus>wDIL9/5eXYZB1J6yOQSJTvczV6dv7/mF3X9p+86kWCArYQmNih/Y+ktOboAjo2UyC8np5Y81yF8G/qAdSrreIwdTtZyAFlgpij2Oovmqpg4/mzL7VS6Sj/4y34+GKRczTjDjxuqTmD4F/lLNhqAwPP2RBbDvCCfmNgnNlkVNOLM=</Modulus><Exponent>AQAB</Exponent><P>wzw0EayQYOMdp6x+OQYryHEmHEu5TY+ZUU6ECOc7zL8EITM9Wm8B7nBgnYZuciJ2Wo+/4+s7E42qEJgyGifznw==</P><Q>/AOmiZxyWeexlilyxxfBjKgr+4wPLSHzbG4vUeY2wngWLTvT/CydZ9vFSXW6jMRVO3Zx8pjyI1bd4uVxZNTCbQ==</Q><DP>IuJY82eADK/IFrOtggbmP9Rn2Np267Li1DJRST3342emF0COj+AR2kbeHIduqJobx6azxMe9MIs5femT2jSVRQ==</DP><DQ>88n8Qsbq//nYmzDBbcOXYqAU3CRjUf+z4cK9V/biJkHRAjUMHrhyFNRPB38x1Zbf9MPh+xLlujYAM8xNY4NGCQ==</DQ><InverseQ>SCvWAH0faRW6h8+ZAJ25kUXsgM0JYY3SoGr7RPkoqpfHyl/41wPth4vvJqLZLnOvX/ip8SEaAE3X9W2z52rIkA==</InverseQ><D>JNJx0JV/ZtOuERpGcv4XgHWD9KszmvpnV0Rt/bxdaDThmrnF0EzBuVJsOGd8bHWa3P9WPJDvcPAj2uy6L/MVU7MHetIEx1FDMPiFXjO9bjaqyx7T9MURuxnCij2flfj/rMEaMx+iRqG+zWP6vMGF3KBFzMjv5/p8o+nKb2znR+E=</D></RSAKeyValue>
</code>```

In most cases, this process successed. But about one in 100, the RSACryptoServiceProvider will raise an Exception:

```<code>System.Security.Cryptography.CryptographicException: Bad Data。
</code>```

The error seems to appear randomly.

The following is some examples that jsencrypt can encrypt and decrypt, but c# failed to decrypt. The first two element of each array are the source and decrypted data by jsencrypt. The Last element of each array are the encrypted data which c# failed to decrypt.

```<code>[
  [
    "75190ba768c49c96adc7e6b048f1e856db8cf6444ce54249d3b2d24a0f480122",
    "75190ba768c49c96adc7e6b048f1e856db8cf6444ce54249d3b2d24a0f480122",
    "gOEY8LP5bYd5UTs+b5xl0MvCijsHJ+jD3hX2ewAibyhYzguB9RAn+pNHpyj0VbC2G9D62oeq2Hdu7YUlSEkEiskeqq9xBKc/xWo+21uc+ArRDdfMSDvHy6iT/KaIQY5LDAZBhv+EHGywkLOhoNSfGrHgyCMKodrIcjJKtv1TDw=="
  ],
  [
    "11b6a03043123d54b6da3f75b9e502ee5db177fbabfe168b19c46f3bebfbfd5c",
    "11b6a03043123d54b6da3f75b9e502ee5db177fbabfe168b19c46f3bebfbfd5c",
    "yX9VGY+4d4TCgE7T8hzyVZcddJPHZzsFsqEM4De1ghlC2wGIK/cKNucVzLgBeJ/VUkR0mhQbqVoWD8eLKfyXM2A1JONN5BgFFQsyOc2oCtZLzbDFk99JYM+7duoejRqM+oDFmKt4aujEYYo4Rcwch+0AfMi3gysHHfmuI/Ry4A=="
  ],
  [
    "12b5fe831e1d5718d06331d0eef2c5f3099f35cb6bcc8fdc5f9aa77df37a6419",
    "12b5fe831e1d5718d06331d0eef2c5f3099f35cb6bcc8fdc5f9aa77df37a6419",
    "IL9nOt4yq4vh2HsCACbCAyJwqMff8/t3AMRbGIYGMjP2SOtZFDeQleOsCYiLtk94lrGLpH2/Ic7KlvgkgtK0u+elbTfkiiSU6pBPiIJE424iNW6sYzCYN/i+gPHnKje9NcDt6BVaWrouDCDbDTtKZsh042iDWSsCRRD0qijdsA=="
  ],
  [
    "918aaf6fcc2fe520f26225335bb1212ac8a6ddf03d01d00c92d189ed2e0ad728",
    "918aaf6fcc2fe520f26225335bb1212ac8a6ddf03d01d00c92d189ed2e0ad728",
    "gA2Bwk7oOw8EvPcbPAF96zxbhK7knhFgEQLgbPU/as1CKfIQz4okci4FKzNx3XrkDNJ0zTcV6T8M2VHo6uCVD160y5BLfragMw5+SVMCRN+3A8Zl01TjYglFF5eChdtY9XDQ9VjSgcqKiHQT2q0lzx9M4Z71ZTtAY03MLAmnxA=="
  ],
  [
    "c72c74a99fd1b207e6532cca34a14a647325bfcfbf47a731378928a526072809",
    "c72c74a99fd1b207e6532cca34a14a647325bfcfbf47a731378928a526072809",
    "SfOl2od01PtPhPdB1ZegkG/ALcDSTyGxcgZMChrCc7HOpYN4o7rD8QeiV2kpi1UUU+F7e+p8V4EAxKdnQbiUXtnboeYY7S+up63AXhYWKDOCNIJLiLv55WQOrgj7OddW4eN6XMFe9OoAcjYLFV+ySgnEDinBoRs+FylAKqJdOQ=="
  ],
  [
    "77b8033daa528892c1282acd2492dbdb363365305c2cd428a29427620474f5a0",
    "77b8033daa528892c1282acd2492dbdb363365305c2cd428a29427620474f5a0",
    "sCloK1zYZlY4/cNEUF4kIBWavWarJk4pn3+302+zWXkaaKqVrWCtGvw9XWOSZ//XvkJHMcwuuNROs/6bUKGsgha+gKnzFSIt7yO+OaP5iBAJd7zCtYiRg5PGkzd9K6aC1MvEflIoi8J8qaziklXh2wKYnQBLumbdxe/xww7QMg=="
  ],
  [
    "d8d35d3eebe25de025844d249f2664d4de4df061d09520d3f04cccf556b766ec",
    "d8d35d3eebe25de025844d249f2664d4de4df061d09520d3f04cccf556b766ec",
    "vBHNc+3gazNDkHJfT76A99+kwy2w7/ZKTBzDN6dkYfdzR+IhRPR2IPI8vhOYW4tGlEdF+dGEFG2F6MJcAWNeVGMqWpD9g1aWqYa4cs1h3EExz9MuikpBkTJ3negm8UArJ4Dhrsa4V0m2cuvmFnBZ29w1Dfe3B9yyIJkxlIIqZQ=="
  ]
]
</code>```

The following is the c# code sample to decrypt data:

```<code>public byte[] Decrypt(byte[] bytes)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(PrivateParameters);
                return rsa.Decrypt(bytes, RSAEncryptionPadding.Pkcs1);
            }
        }
</code>```

The following is the js code sample to encrypt data:

```<code><input id="pubkey" type="hidden" value="@Model.pubkey" />
<input id="prikey" type="hidden" value="@Model.prikey" />
<script type="text/javascript" src="/scripts/crypto/crypto-js.min.js"></script>
<script type="text/javascript" src="/scripts/crypto/jsencrypt.min.js"></script>
<div id="vue-app">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12" v-for="c in cipher">
                {{ c }}
            </div>
        </div>
    </div>
</div>
<script>
    $(function(){
        var pubkey = $("#pubkey").val();
        var prikey = $("#prikey").val();
        window.encryptor = new JSEncrypt();
        encryptor.setPublicKey(pubkey);
        window.decryptor = new JSEncrypt();
        decryptor.setPrivateKey(prikey);
        function task(){
            var src = CryptoJS.SHA256(Math.uuid()).toString();
            var cipher = encryptor.encrypt(src);
            var plain = decryptor.decrypt(cipher)
            var args = { src: src, cipher: cipher, plain: plain  }
            $.post("/api/test/view/rsa", args, function(msg){
                if(msg.error){
                    app.cipher.push([args.cipher==msg.message,args]);
                }
                else{
                    console.log(args)
                }
            });
            setTimeout(task, 1);
        }
        task();
    });
</script>
</code>```

答:
Your javascript encryption is producing results that do not conform to the RSAES-PKCS1-V1_5-ENCRYPT specification.

Your modulus is a 1024-bit number (128 bytes).  Therefore the output of all encrypted messages will be 128 bytes.

https://www.rfc-editor.org/rfc/rfc3447#section-7.2.1:

c. Convert the ciphertext representative c to a ciphertext C of
length k octets (see Section 4.1):

```<code>C = I2OSP (c, k).
</code>```

("of length k", not "of length up to k").

The third values that you've presented all end with ==, which means that the number of bytes mod 3 is 1.  But 128 mod 3 is 2.  Therefore the output here is not a legal output of I2OSP(c, 128).

The javascript library you are using is leaving off the leading zeros.  So to fix this in .NET you would do

```<code>public byte[] Decrypt(byte[] bytes)
{
    using (var rsa = new RSACryptoServiceProvider())
    {
        rsa.ImportParameters(PrivateParameters);

        // Correct the error in the JS encryptor.
        if (bytes.Length < rsa.KeySize / 8)
        {
            byte[] tmp = new byte[rsa.KeySize / 8];
            Buffer.BlockCopy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);
            bytes = tmp;
        }

        return rsa.Decrypt(bytes, RSAEncryptionPadding.Pkcs1);
    }
}
</code>```

Note that I didn't say + 1, because given the observed behavior of the javascript library, if the encryption produced a value which should have started with 00 00 it will leave off both of them.

And filing a bug with the library owner seems good :).

Body:
For security, I encrypted some data, such as username, passwords, and emails in the browser by jsencrypt which is a A Javascript library to perform OpenSSL RSA Encryption, Decryption. And then I decrypt the cipher data using RSACryptoServiceProvider by C#. The public key, and private key are generated by c#：

<RSAKeyValue><Modulus>wDIL9/5eXYZB1J6yOQSJTvczV6dv7/mF3X9p+86kWCArYQmNih/Y+ktOboAjo2UyC8np5Y81yF8G/qAdSrreIwdTtZyAFlgpij2Oovmqpg4/mzL7VS6Sj/4y34+GKRczTjDjxuqTmD4F/lLNhqAwPP2RBbDvCCfmNgnNlkVNOLM=</Modulus><Exponent>AQAB</Exponent>
wzw0EayQYOMdp6x+OQYryHEmHEu5TY+ZUU6ECOc7zL8EITM9Wm8B7nBgnYZuciJ2Wo+/4+s7E42qEJgyGifznw==
<Q>/AOmiZxyWeexlilyxxfBjKgr+4wPLSHzbG4vUeY2wngWLTvT/CydZ9vFSXW6jMRVO3Zx8pjyI1bd4uVxZNTCbQ==</Q><DP>IuJY82eADK/IFrOtggbmP9Rn2Np267Li1DJRST3342emF0COj+AR2kbeHIduqJobx6azxMe9MIs5femT2jSVRQ==</DP><DQ>88n8Qsbq//nYmzDBbcOXYqAU3CRjUf+z4cK9V/biJkHRAjUMHrhyFNRPB38x1Zbf9MPh+xLlujYAM8xNY4NGCQ==</DQ><InverseQ>SCvWAH0faRW6h8+ZAJ25kUXsgM0JYY3SoGr7RPkoqpfHyl/41wPth4vvJqLZLnOvX/ip8SEaAE3X9W2z52rIkA==</InverseQ><D>JNJx0JV/ZtOuERpGcv4XgHWD9KszmvpnV0Rt/bxdaDThmrnF0EzBuVJsOGd8bHWa3P9WPJDvcPAj2uy6L/MVU7MHetIEx1FDMPiFXjO9bjaqyx7T9MURuxnCij2flfj/rMEaMx+iRqG+zWP6vMGF3KBFzMjv5/p8o+nKb2znR+E=</D></RSAKeyValue>

In most cases, this process successed. But about one in 100, the RSACryptoServiceProvider will raise an Exception:

System.Security.Cryptography.CryptographicException: Bad Data。

The error seems to appear randomly.

The following is some examples that jsencrypt can encrypt and decrypt, but c# failed to decrypt. The first two element of each array are the source and decrypted data by jsencrypt. The Last element of each array are the encrypted data which c# failed to decrypt.

[
  [
    "75190ba768c49c96adc7e6b048f1e856db8cf6444ce54249d3b2d24a0f480122",
    "75190ba768c49c96adc7e6b048f1e856db8cf6444ce54249d3b2d24a0f480122",
    "gOEY8LP5bYd5UTs+b5xl0MvCijsHJ+jD3hX2ewAibyhYzguB9RAn+pNHpyj0VbC2G9D62oeq2Hdu7YUlSEkEiskeqq9xBKc/xWo+21uc+ArRDdfMSDvHy6iT/KaIQY5LDAZBhv+EHGywkLOhoNSfGrHgyCMKodrIcjJKtv1TDw=="
  ],
  [
    "11b6a03043123d54b6da3f75b9e502ee5db177fbabfe168b19c46f3bebfbfd5c",
    "11b6a03043123d54b6da3f75b9e502ee5db177fbabfe168b19c46f3bebfbfd5c",
    "yX9VGY+4d4TCgE7T8hzyVZcddJPHZzsFsqEM4De1ghlC2wGIK/cKNucVzLgBeJ/VUkR0mhQbqVoWD8eLKfyXM2A1JONN5BgFFQsyOc2oCtZLzbDFk99JYM+7duoejRqM+oDFmKt4aujEYYo4Rcwch+0AfMi3gysHHfmuI/Ry4A=="
  ],
  [
    "12b5fe831e1d5718d06331d0eef2c5f3099f35cb6bcc8fdc5f9aa77df37a6419",
    "12b5fe831e1d5718d06331d0eef2c5f3099f35cb6bcc8fdc5f9aa77df37a6419",
    "IL9nOt4yq4vh2HsCACbCAyJwqMff8/t3AMRbGIYGMjP2SOtZFDeQleOsCYiLtk94lrGLpH2/Ic7KlvgkgtK0u+elbTfkiiSU6pBPiIJE424iNW6sYzCYN/i+gPHnKje9NcDt6BVaWrouDCDbDTtKZsh042iDWSsCRRD0qijdsA=="
  ],
  [
    "918aaf6fcc2fe520f26225335bb1212ac8a6ddf03d01d00c92d189ed2e0ad728",
    "918aaf6fcc2fe520f26225335bb1212ac8a6ddf03d01d00c92d189ed2e0ad728",
    "gA2Bwk7oOw8EvPcbPAF96zxbhK7knhFgEQLgbPU/as1CKfIQz4okci4FKzNx3XrkDNJ0zTcV6T8M2VHo6uCVD160y5BLfragMw5+SVMCRN+3A8Zl01TjYglFF5eChdtY9XDQ9VjSgcqKiHQT2q0lzx9M4Z71ZTtAY03MLAmnxA=="
  ],
  [
    "c72c74a99fd1b207e6532cca34a14a647325bfcfbf47a731378928a526072809",
    "c72c74a99fd1b207e6532cca34a14a647325bfcfbf47a731378928a526072809",
    "SfOl2od01PtPhPdB1ZegkG/ALcDSTyGxcgZMChrCc7HOpYN4o7rD8QeiV2kpi1UUU+F7e+p8V4EAxKdnQbiUXtnboeYY7S+up63AXhYWKDOCNIJLiLv55WQOrgj7OddW4eN6XMFe9OoAcjYLFV+ySgnEDinBoRs+FylAKqJdOQ=="
  ],
  [
    "77b8033daa528892c1282acd2492dbdb363365305c2cd428a29427620474f5a0",
    "77b8033daa528892c1282acd2492dbdb363365305c2cd428a29427620474f5a0",
    "sCloK1zYZlY4/cNEUF4kIBWavWarJk4pn3+302+zWXkaaKqVrWCtGvw9XWOSZ//XvkJHMcwuuNROs/6bUKGsgha+gKnzFSIt7yO+OaP5iBAJd7zCtYiRg5PGkzd9K6aC1MvEflIoi8J8qaziklXh2wKYnQBLumbdxe/xww7QMg=="
  ],
  [
    "d8d35d3eebe25de025844d249f2664d4de4df061d09520d3f04cccf556b766ec",
    "d8d35d3eebe25de025844d249f2664d4de4df061d09520d3f04cccf556b766ec",
    "vBHNc+3gazNDkHJfT76A99+kwy2w7/ZKTBzDN6dkYfdzR+IhRPR2IPI8vhOYW4tGlEdF+dGEFG2F6MJcAWNeVGMqWpD9g1aWqYa4cs1h3EExz9MuikpBkTJ3negm8UArJ4Dhrsa4V0m2cuvmFnBZ29w1Dfe3B9yyIJkxlIIqZQ=="
  ]
]

The following is the c# code sample to decrypt data:

public byte[] Decrypt(byte[] bytes)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(PrivateParameters);
                return rsa.Decrypt(bytes, RSAEncryptionPadding.Pkcs1);
            }
        }

The following is the js code sample to encrypt data:

<input id="pubkey" type="hidden" value="@Model.pubkey" />
<input id="prikey" type="hidden" value="@Model.prikey" />

                {{ c }}

Body:
Your javascript encryption is producing results that do not conform to the RSAES-PKCS1-V1_5-ENCRYPT specification.

Your modulus is a 1024-bit number (128 bytes).  Therefore the output of all encrypted messages will be 128 bytes.

https://www.rfc-editor.org/rfc/rfc3447#section-7.2.1:

c. Convert the ciphertext representative c to a ciphertext C of
length k octets (see Section 4.1):

C = I2OSP (c, k).

("of length k", not "of length up to k").

The third values that you've presented all end with ==, which means that the number of bytes mod 3 is 1.  But 128 mod 3 is 2.  Therefore the output here is not a legal output of I2OSP(c, 128).

The javascript library you are using is leaving off the leading zeros.  So to fix this in .NET you would do

public byte[] Decrypt(byte[] bytes)
{
    using (var rsa = new RSACryptoServiceProvider())
    {
        rsa.ImportParameters(PrivateParameters);

        // Correct the error in the JS encryptor.
        if (bytes.Length < rsa.KeySize / 8)
        {
            byte[] tmp = new byte[rsa.KeySize / 8];
            Buffer.BlockCopy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);
            bytes = tmp;
        }

        return rsa.Decrypt(bytes, RSAEncryptionPadding.Pkcs1);
    }
}

Note that I didn't say + 1, because given the observed behavior of the javascript library, if the encryption produced a value which should have started with 00 00 it will leave off both of them.

And filing a bug with the library owner seems good :).


来源: stackexchange

问:
Flink DataSet api with Hbase table input format - read rows multiple times
I am using Flink 1.3.2 with the hbase TableInputFormat from flink-connectors (flink-hbase_2.11), using the DataSet API.

I have an HBase table where the rowkeys are stuctured as follows:

```<code>| RowKey       | data |
| 0-someuniqid | data |
| 0-someuniqid | data |
| 2-someuniqid | data |
| 2-someuniqid | data |
| 4-someuniqid | data |
| 5-someuniqid | data |
| 5-someuniqid | data |
| 7-someuniqid | data |
| 8-someuniqid | data |
</code>```

The prefix of the table can be 0 to 9 (this is to prevent hot spotting in the hbase nodes). In my test table no one writes to this table.

I have got a job of the form:

```<code>tableInputFormat0 = new TableInputFormat("table", 0);
tableInputFormat1 = new TableInputFormat("table", 1);
...
tableInputFormat9 = new TableInputFormat("table", 9);

tableInputFormat0.union(tableInputFormat1).(...).union(tableInputFormat9)
                 .map(mapFunction())
                 .rebalance()
                 .filter(someFilter())
                 .groupBy(someField())
                 .reduce(someSumFunction())
                 .output(new HbaseOutputFormat());
</code>```

The problem is when a a lot of records are read (around the 20 million records), the job does not always read the same amount of records.

Most of the time it (correctly) reads: 20,277,161 rows. But sometimes it reads: 20,277,221 or 20,277,171 always more never less. (I get this number via the flink web dashboard, but the effects I can see in what gets written ie too much data is aggregated by the reduce)

I cannot make the problem smaller by using a smaller dataset because the problem does not happen when running the job against a a table of say 5million records. It is hard to identify what records are read multiple times because of the volume.

How can I debug (and solve) this problem?

答:
TableInputFormat is an abstract class and you have to implement a subclass.

I would do two things:

check that each input split is processed just once (this info is written to the JobManager log file)

adapt your input format to count the number of emitted records for each input split. The record count and split id should be written to the (TaskManager) log.

This should help to identify, whether the problem is

due one (or more) splits being assigned more than once or

due to a bug in the code that processes a split.

ContentLicense: CC BY-SA 3.0

Body:
I am using Flink 1.3.2 with the hbase TableInputFormat from flink-connectors (flink-hbase_2.11), using the DataSet API.

I have an HBase table where the rowkeys are stuctured as follows:

| RowKey       | data |
| 0-someuniqid | data |
| 0-someuniqid | data |
| 2-someuniqid | data |
| 2-someuniqid | data |
| 4-someuniqid | data |
| 5-someuniqid | data |
| 5-someuniqid | data |
| 7-someuniqid | data |
| 8-someuniqid | data |

The prefix of the table can be 0 to 9 (this is to prevent hot spotting in the hbase nodes). In my test table no one writes to this table.

I have got a job of the form:

tableInputFormat0 = new TableInputFormat("table", 0);
tableInputFormat1 = new TableInputFormat("table", 1);
...
tableInputFormat9 = new TableInputFormat("table", 9);

tableInputFormat0.union(tableInputFormat1).(...).union(tableInputFormat9)
                 .map(mapFunction())
                 .rebalance()
                 .filter(someFilter())
                 .groupBy(someField())
                 .reduce(someSumFunction())
                 .output(new HbaseOutputFormat());

The problem is when a a lot of records are read (around the 20 million records), the job does not always read the same amount of records.

Most of the time it (correctly) reads: 20,277,161 rows. But sometimes it reads: 20,277,221 or 20,277,171 always more never less. (I get this number via the flink web dashboard, but the effects I can see in what gets written ie too much data is aggregated by the reduce)

I cannot make the problem smaller by using a smaller dataset because the problem does not happen when running the job against a a table of say 5million records. It is hard to identify what records are read multiple times because of the volume.

How can I debug (and solve) this problem?


问:
Python inserting spaces in string
Alright, I'm working on a little project for school, a 6-frame translator. I won't go into too much detail, I'll just describe what I wanted to add.
The normal output would be something like:

```<code>TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSD
</code>```

The important part of this string are the M and the _ (the start and stop codons, biology stuff). What I wanted to do was highlight these like so:

```<code>TTCPTISPALGLAWS_DLGTLGF 'MSYSANTASGETLVSLYQLGLFEM_' VVSYGRTKYYLICP_LFHLSVGFVPSD
</code>```

Now here is where (for me) it gets tricky, I got my output to look like this (adding a space and a ' to highlight the start and stop). But it only does this once, for the first start and stop it finds. If there are any other M....._ combinations it won't highlight them.

Here is my current code, attempting to make it highlight more than once:

```<code>def start_stop(translation):
index_2 = 0
while True:
    if 'M' in translation[index_2::1]:
        index_1 = translation[index_2::1].find('M')
        index_2 = translation[index_1::1].find('_') + index_1
        new_translation = translation[:index_1] + " '" + \
                          translation[index_1:index_2 + 1] + "' " +\
                          translation[index_2 + 1:]
    else:
        break
    return new_translation
</code>```

I really thought this would do it, guess not. So now I find myself being stuck.
If any of you are willing to try and help, here is a randomly generated string with more than one M....._ set:

```<code>'TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSDGRRLTLYMPPARRLATKSRFLTPVISSG_DKPRHNPVARSQFLNPLVRPNYSISASKSGLRLVLSYTRLSLGINSLPIERLQYSVPAPAQITP_IPEHGNARNFLPEWPRLLISEPAPSVNVPCSVFVVDPEHPKAHSKPDGIANRLTFRWRLIG_VFFHNAL_VITHGYSRVDILLPVSRALHVHLSKSLLLRSAWFTLRNTRVTGKPQTSKT_FDPKATRVHAIDACAE_QQH_PDSGLRFPAPGSCSEAIRQLMI'
</code>```

Thank you to anyone willing to help :)

答:
You just require little slice of 'slice' module , you don't need any external module :

Python string have a method called 'index' just use it.

```<code>string_1='TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSD'

before=string_1.index('M')
after=string_1[before:].index('_')
print('{}  {} {}'.format(string_1[:before],string_1[before:before+after+1],string_1[before+after+1:]))
</code>```

output:

```<code>TTCPTISPALGLAWS_DLGTLGF  MSYSANTASGETLVSLYQLGLFEM_ VVSYGRTKYYLICP_LFHLSVGFVPSD
</code>```

Title: Python inserting spaces in string

Body:
Alright, I'm working on a little project for school, a 6-frame translator. I won't go into too much detail, I'll just describe what I wanted to add.
The normal output would be something like:

TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSD

The important part of this string are the M and the _ (the start and stop codons, biology stuff). What I wanted to do was highlight these like so:

TTCPTISPALGLAWS_DLGTLGF 'MSYSANTASGETLVSLYQLGLFEM_' VVSYGRTKYYLICP_LFHLSVGFVPSD

Now here is where (for me) it gets tricky, I got my output to look like this (adding a space and a ' to highlight the start and stop). But it only does this once, for the first start and stop it finds. If there are any other M....._ combinations it won't highlight them.

Here is my current code, attempting to make it highlight more than once:

def start_stop(translation):
index_2 = 0
while True:
    if 'M' in translation[index_2::1]:
        index_1 = translation[index_2::1].find('M')
        index_2 = translation[index_1::1].find('_') + index_1
        new_translation = translation[:index_1] + " '" + \
                          translation[index_1:index_2 + 1] + "' " +\
                          translation[index_2 + 1:]
    else:
        break
    return new_translation

I really thought this would do it, guess not. So now I find myself being stuck.
If any of you are willing to try and help, here is a randomly generated string with more than one M....._ set:

'TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSDGRRLTLYMPPARRLATKSRFLTPVISSG_DKPRHNPVARSQFLNPLVRPNYSISASKSGLRLVLSYTRLSLGINSLPIERLQYSVPAPAQITP_IPEHGNARNFLPEWPRLLISEPAPSVNVPCSVFVVDPEHPKAHSKPDGIANRLTFRWRLIG_VFFHNAL_VITHGYSRVDILLPVSRALHVHLSKSLLLRSAWFTLRNTRVTGKPQTSKT_FDPKATRVHAIDACAE_QQH_PDSGLRFPAPGSCSEAIRQLMI'

Thank you to anyone willing to help :)

Body:
You just require little slice of 'slice' module , you don't need any external module :

Python string have a method called 'index' just use it.

string_1='TTCPTISPALGLAWS_DLGTLGFMSYSANTASGETLVSLYQLGLFEM_VVSYGRTKYYLICP_LFHLSVGFVPSD'

before=string_1.index('M')
after=string_1[before:].index('_')
print('{}  {} {}'.format(string_1[:before],string_1[before:before+after+1],string_1[before+after+1:]))

output:

TTCPTISPALGLAWS_DLGTLGF  MSYSANTASGETLVSLYQLGLFEM_ VVSYGRTKYYLICP_LFHLSVGFVPSD


问:
Java read Properties file that is in same package as the class
I'm stuck in this for almost an hour so please help me.

I'm using netbeans and under my Sources Packages I have a package called com.cmsv1.properties. Inside this package I have 1 java class and .properties file. Called config.java and config.properties.

I've tried so many solutions I got from the internet but nothing works. I always get nullPointerException.

The following are the solutions i've tried:

```<code>try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }
</code>```

another is:

```<code>try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }
</code>```

And a couple more solutions. Please tell me how can I do this. Remember both of my java class and .properties file are in the same package. Thanks in advance.

答:
Your first try was almost exactly right:

```<code>try
{
    Properties prop = new Properties();
    InputStream is = config.class.getResourceAsStream("config.properties");
}
catch (Exception e)
{
    System.out.println("got error");
}
</code>```

Except that you need to load and close the InputStream:

```<code>Properties prop = new Properties();
try (InputStream is = config.class.getResourceAsStream("config.properties")) {
    prop.load(is);
}
</code>```

Also, you need to catch only the exception you need to catch:

```<code>catch (IOException e)
</code>```

This is because other exceptions, especially unchecked exceptions (like NullPointerException), indicate programmer errors.  You don’t catch those, you let them make your program fail, so you can discover and fix them.  Hiding them does not make your program work properly!

ALWAYS show the stack trace of a caught exception, either with a logging statement, exception chaining, or printStackTrace().  If something goes wrong, you want to know why it happened and where it happened:

```<code>catch (IOException e)
{
    e.printStackTrace();
}
</code>```

Regarding the use of Class.getResource versus ClassLoader.getResource, you should always use Class.getResource (or Class.getResourceAsStream).  Among the reasons for this is that it will work in Java 9 modular applications.

If getResourceAsStream returns null, it’s because your properties file is not in the same location as your compiled .class file.

Body:
I'm stuck in this for almost an hour so please help me.

I'm using netbeans and under my Sources Packages I have a package called com.cmsv1.properties. Inside this package I have 1 java class and .properties file. Called config.java and config.properties.

I've tried so many solutions I got from the internet but nothing works. I always get nullPointerException.

The following are the solutions i've tried:

try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

another is:

try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

And a couple more solutions. Please tell me how can I do this. Remember both of my java class and .properties file are in the same package. Thanks in advance.

Body:
Your first try was almost exactly right:

try
{
    Properties prop = new Properties();
    InputStream is = config.class.getResourceAsStream("config.properties");
}
catch (Exception e)
{
    System.out.println("got error");
}

Except that you need to load and close the InputStream:

Properties prop = new Properties();
try (InputStream is = config.class.getResourceAsStream("config.properties")) {
    prop.load(is);
}

Also, you need to catch only the exception you need to catch:

catch (IOException e)

This is because other exceptions, especially unchecked exceptions (like NullPointerException), indicate programmer errors.  You don’t catch those, you let them make your program fail, so you can discover and fix them.  Hiding them does not make your program work properly!

ALWAYS show the stack trace of a caught exception, either with a logging statement, exception chaining, or printStackTrace().  If something goes wrong, you want to know why it happened and where it happened:

catch (IOException e)
{
    e.printStackTrace();
}

Regarding the use of Class.getResource versus ClassLoader.getResource, you should always use Class.getResource (or Class.getResourceAsStream).  Among the reasons for this is that it will work in Java 9 modular applications.

If getResourceAsStream returns null, it’s because your properties file is not in the same location as your compiled .class file.


问:
Usage of [mat-dialog-close]
I am a bit confused about the usage of [mat-dialog-close].

So, I have a dialog with a form. If the user clicks the submit button, the form is validated. If the input is valid, the dialog is closed and the form is submitted. However, if the input is invalid, the dialog remains opened and an error message is shown. For that I want to use [mat-dialog-close] as it is described in the official documentation where it is used as follows:

```<code><button mat-button [mat-dialog-close]="true">Yes</button>
</code>```

I thought that I can just pass it a boolean and whether the tag is active depends on the boolean value of the variable. However, this does not work. I tried it like this:

```<code><button type="submit" (click)="addUser()" [mat-dialog-close]="formisvalid" mat-button>Submit</button>
</code>```

I passed it the variable formisvalid. It's value is true unless the input is invalid. But now the dialog closes always, regardless of the value of formisvalid.
I also tried replacing it with false. I thought the dialog would remain opened no matter what happens, but it would also always close.

So, my question is: am I mistaken about the use of [mat-dialog-close] or am I just doing something wrong? If this is not achievable with the [mat-dialog-close] directive, what would be another way to achieve what I'm trying to do?

答:
Set your button to have disabled on it if the form is not valid.  This way the button cannot be clicked unless the form is valid, meaning it won't close unless the form is valid</p>

```<code><button type="submit" (click)="addUser()" mat-dialog-close [disabled]="formisvalid" mat-button>Submit</button>
</code>```

Title: Usage of [mat-dialog-close]

Body:
I am a bit confused about the usage of [mat-dialog-close].

So, I have a dialog with a form. If the user clicks the submit button, the form is validated. If the input is valid, the dialog is closed and the form is submitted. However, if the input is invalid, the dialog remains opened and an error message is shown. For that I want to use [mat-dialog-close] as it is described in the official documentation where it is used as follows:

<button mat-button [mat-dialog-close]="true">Yes</button>

I thought that I can just pass it a boolean and whether the tag is active depends on the boolean value of the variable. However, this does not work. I tried it like this:

<button type="submit" (click)="addUser()" [mat-dialog-close]="formisvalid" mat-button>Submit</button>

I passed it the variable formisvalid. It's value is true unless the input is invalid. But now the dialog closes always, regardless of the value of formisvalid.
I also tried replacing it with false. I thought the dialog would remain opened no matter what happens, but it would also always close.

So, my question is: am I mistaken about the use of [mat-dialog-close] or am I just doing something wrong? If this is not achievable with the [mat-dialog-close] directive, what would be another way to achieve what I'm trying to do?

Body:
Set your button to have disabled on it if the form is not valid.  This way the button cannot be clicked unless the form is valid, meaning it won't close unless the form is valid

<button type="submit" (click)="addUser()" mat-dialog-close [disabled]="formisvalid" mat-button>Submit</button>


问:
Using docker pull & run to build dockerfile
I'm learning how to use docker.

I want to deploy a microservice for swagger. I can do

```<code>docker pull schickling/swagger-ui
docker run -p 80:8080 -e API_URL=http://myapiurl/api.json swaggerapi/swagger-ui
</code>```

To deploy it, I need a dockerfile i can run.
How do i generate the dockerfile in a way I can run it with docker build ?

答:
Usually the docker pull pulls the Dockerfile. The Dockerfile for swagger is on the docker repo for it if you wanted to edit it or customize it.
 (https://hub.docker.com/r/schickling/swagger-ui/~/dockerfile/)

That one should work with the build command. The build command builds the image, the run command turns the image into a container. The docker pull command should pull the image in. You don't need to run docker build for it as you should already have the image from the pull. You only need to do docker run.

Body:
I'm learning how to use docker.

I want to deploy a microservice for swagger. I can do

docker pull schickling/swagger-ui
docker run -p 80:8080 -e API_URL=http://myapiurl/api.json swaggerapi/swagger-ui

To deploy it, I need a dockerfile i can run.
How do i generate the dockerfile in a way I can run it with docker build ?


问:
JQueryUI modal - focus on close button - How to remove focus on close button

When using the JQueryUI modal dialog, the close button is automatically focused leading the title exposed through the jquery tooltip. I want nothing in the modal to be focused. I have tried to add a click trigger on the title of the modal window, but it seems that it had no effect.

Please help me.

答:
Neither of these solutions worked for me. I found this jsfiddle in the wild that fixed it.

```<code>$( "#dialog-modal" ).dialog({
    height: 140,
    modal: true,

    // When the dialog is opened, move the focus off the button. This
    // causes the close button to trigger a click event when the space
    // key is pressed.
    open: function( e, ui ) {
        $( this ).siblings( ".ui-dialog-titlebar" )
                 .find( "button" ).blur();
    }
});
</code>```

https://jsfiddle.net/adamboduch/ekaW6/

Body:
Neither of these solutions worked for me. I found this jsfiddle in the wild that fixed it.

$( "#dialog-modal" ).dialog({
    height: 140,
    modal: true,

    // When the dialog is opened, move the focus off the button. This
    // causes the close button to trigger a click event when the space
    // key is pressed.
    open: function( e, ui ) {
        $( this ).siblings( ".ui-dialog-titlebar" )
                 .find( "button" ).blur();
    }
});

https://jsfiddle.net/adamboduch/ekaW6/


问:
How do I retrieve the groovy pipeline script used by one jenkins build?
I am looking for an API call that would allow me to retrieve the pipeline script that was use by a specific Jenkins build.

Please note that this may be different than the pipeline script defined in the job definition, as this could have being changed between builds.

This script is stored by Jenkins because /replay plugin allows you to replay a pipeline (the original version used by a specific build).

答:
My current workaround for this was to parse the HTML of that page with something like:

```<code>curl -n --silent $JOB/replay/ | \
    xmllint --nowarning --html --xpath "//textarea/text()" > Jenkinsfile
</code>```

Yes, us ugly, but it did work. I would be more than happy to see that someone comes with a proper REST API call solution.

Body:
My current workaround for this was to parse the HTML of that page with something like:

curl -n --silent $JOB/replay/ | \
    xmllint --nowarning --html --xpath "//textarea/text()" > Jenkinsfile

Yes, us ugly, but it did work. I would be more than happy to see that someone comes with a proper REST API call solution.


答:
The original question asks for a Dockerfile, perhaps for some CI/CD workflow, so this answer addresses that requirement:

Create a very simple Dockerfile beginning with

```<code>FROM schickling/swagger-ui
</code>```

Then from that directory run

```<code>$ docker build -t mycontainername .
</code>```

Which can then be run:

```<code>$ docker run -p 80:8080 -e API_URL=http://myapiurl/api.json mycontainername
</code>```

Title: Using docker pull & run to build dockerfile

Body:
The original question asks for a Dockerfile, perhaps for some CI/CD workflow, so this answer addresses that requirement:

Create a very simple Dockerfile beginning with

FROM schickling/swagger-ui

Then from that directory run

$ docker build -t mycontainername .

Which can then be run:

$ docker run -p 80:8080 -e API_URL=http://myapiurl/api.json mycontainername


问:
SIGBUS when trying to increment a std::map iterator
I am debugging a big C++98 application and I am obtaining a SIBGUS error when a method tries to increment a std::map::iterator.

By putiing traces, I have discovered that the method in question removes elements from the mentioned map (indireclty, by calling other methods that call other methods and so on...), so I suspect that the problem is to been iterating over the map while deleting its elements.

I have been searching the proper way to iterate over a std::map and delete items safelly, and I have found this:

```<code>for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it++);    // or "it = m.erase(it)" since C++11
  }
  else
  {
    ++it;
  }
}
</code>```

Code quoted from How to remove from a map while iterating it?

I have some questions about this:

Is it actually necessary to distinguis between deleting elements or not, taking into account that the iterator is going to be increased in any case?

Is the following code snippet equivalent to the above one, in terms of safety?

```<code>for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it);
  }
  it++;
}
</code>```

The method that is producing the SIGBUS follows the following pattern:

```<code>std::map<..., ...>::iterator it = myMap.begin(); // myMap is an instance attribute and can be accessed by any class method.

while(it != myMap.end() {
  if(somethingHappens())
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete 'myMap' elements.
  it++; // The error occurs here
}
</code>```

Since the deletion is performed by other method/s, I cannot distinguis if an element has been deleted or not (unless I return a boolean value or similar). Is this potentially unsafe?

答:
Since the deletion is performed by other method/s, I cannot distinguish if an element has been deleted or not (unless I return a boolean value or similar).

You certainly can. Keep the size of the map before the call to doSomethingThatMightDeleteMapElements. Get the the size of the map after the call to doSomethingThatMightDeleteMapElements. Then take appropriate action depending on whether they are equal or not.

```<code>while(it != myMap.end() {
  size_t size_before = myMap.size();
  size_t size_after = size_before;
  if(somethingHappens())
  {
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete myMap  elements.
    size_after = myMap.size();
  }

  if ( size_before != size_after )
  {
    // Be safe. Iterate from the start again.
    it = myMap.begin();
  }
  else
  {
    it++; // The error occurs here
  }
}
</code>```

Body:
I am debugging a big C++98 application and I am obtaining a SIBGUS error when a method tries to increment a std::map::iterator.

By putiing traces, I have discovered that the method in question removes elements from the mentioned map (indireclty, by calling other methods that call other methods and so on...), so I suspect that the problem is to been iterating over the map while deleting its elements.

I have been searching the proper way to iterate over a std::map and delete items safelly, and I have found this:

for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it++);    // or "it = m.erase(it)" since C++11
  }
  else
  {
    ++it;
  }
}

Code quoted from How to remove from a map while iterating it?

I have some questions about this:

Is it actually necessary to distinguis between deleting elements or not, taking into account that the iterator is going to be increased in any case?

Is the following code snippet equivalent to the above one, in terms of safety?

for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it);
  }
  it++;
}

The method that is producing the SIGBUS follows the following pattern:

std::map<..., ...>::iterator it = myMap.begin(); // myMap is an instance attribute and can be accessed by any class method.

while(it != myMap.end() {
  if(somethingHappens())
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete 'myMap' elements.
  it++; // The error occurs here
}

Since the deletion is performed by other method/s, I cannot distinguis if an element has been deleted or not (unless I return a boolean value or similar). Is this potentially unsafe?

Body:
Since the deletion is performed by other method/s, I cannot distinguish if an element has been deleted or not (unless I return a boolean value or similar).

You certainly can. Keep the size of the map before the call to doSomethingThatMightDeleteMapElements. Get the the size of the map after the call to doSomethingThatMightDeleteMapElements. Then take appropriate action depending on whether they are equal or not.

while(it != myMap.end() {
  size_t size_before = myMap.size();
  size_t size_after = size_before;
  if(somethingHappens())
  {
    doSomethingThatMightDeleteMapElements(); // this can (or not) delete myMap  elements.
    size_after = myMap.size();
  }

  if ( size_before != size_after )
  {
    // Be safe. Iterate from the start again.
    it = myMap.begin();
  }
  else
  {
    it++; // The error occurs here
  }
}


问:
Symfony 4 - Manually Form
I'm creating my first project in Symfony framework.
I chose 4.0 version. I have a question about creating forms.

config/routes.yaml

```<code>home:
    path: /
    controller: App\Controller\HomeController::index
    methods: [GET]

login:
    path: /login
    controller: App\Controller\HomeController::login
    methods: [POST]

register:
    path: /register
    controller: App\Controller\HomeController::register
    methods: [POST]

timeline:
    path: /timeline
    controller: App\Controller\TimelineController::index
    methods: [GET]
</code>```

src/Entity/User.php

```<code>//

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $lastName;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    public function getId()
    {
        return $this->id;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getFirstName()
    {
        return $this->firstName;
    }

    public function getLastName()
    {
        return $this->lastName;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }

    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;
    }

    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
    }

    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }
}
</code>```

src/Controller/HomeController.php

```<code><?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\User;

class HomeController extends Controller
{
    public function index() {
        return $this->render('home/index.html.twig');
    }

    public function login(Request $request) {
        // ?????
    }

    public function register(Request $request) {
        $user = new User();
        // ?????
    }
}
</code>```

templates/home/index.html.twig

```<code>...

<form action="{{ path('login') }}" id="signInForm" role="form"
      method="POST" class="visible">
                        <h2>Sign In</h2>
                        <hr class="colorgraph">
                        <div class="form-group">
                            <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address">
                        </div>
                        <div class="form-group">
                            <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password">
                        </div>
                        <span class="button-checkbox">
                            <button type="button" class="btn btn-info active" data-color="info">
                                <i class="state-icon glyphicon glyphicon-check"></i> Remember Me</button>
                           <input type="checkbox" name="remember_me" id="remember_me" class="hidden">
                            <a href="" class="btn btn-link pull-right">Forgot Password?</a>
                        </span>
                        <hr class="colorgraph">
                        <div class="row">
                            <div class="col-xs-6 col-sm-6 col-md-6">
                                  <input type="submit" class="btn btn-lg btn-success btn-block" value="Sign In">
                            </div>
                            <div class="col-xs-6 col-sm-6 col-md-6">
                                <a id="registerBtn" href="#" class="btn btn-lg btn-block btn-toggle">To Register</a>
                            </div>
                        </div>
                    </form>
                    <form action="{{ path('register') }}" id="registerForm" role="form" method="POST">
                        <h2>
                            Please Sign Up
                            <small>It's free and always will be.</small>
                        </h2>
                        <hr class="colorgraph">
                        <div class="row">
                            <div class="col-xs-12 col-sm-6 col-md-6">
                                <div class="form-group">
                                    <input type="text" name="first_name" id="first_name" class="form-control input-lg" placeholder="First Name" tabindex="1">
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-6 col-md-6">
                                <div class="form-group">
                                    <input type="text" name="last_name" id="last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="text" name="display_name" id="display_name" class="form-control input-lg" placeholder="Display Name" tabindex="3">
                        </div>
                        <div class="form-group">
                            <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4">
                        </div>
                        <div class="row">
                            <div class="col-xs-12 col-sm-6 col-md-6">
                                <div class="form-group">
                                    <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-6 col-md-6">
                                <div class="form-group">
                                    <input type="password" name="password_confirmation" id="password_confirmation" class="form-control input-lg" placeholder="Confirm Password"
                                        tabindex="6">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-4 col-sm-3 col-md-3">
                                <span class="button-checkbox">
                                    <button type="button" class="btn" data-color="info" tabindex="7">I Agree</button>
                                    <input type="checkbox" name="t_and_c" id="t_and_c" class="hidden" value="1">
                                </span>
                            </div>
                            <div class="col-xs-8 col-sm-9 col-md-9">
                                By clicking
                                <strong class="label label-primary">Register</strong>, you agree to the
                                <a href="#" data-toggle="modal" data-target="#t_and_c_m">Terms and Conditions</a> set out by this site, including our Cookie Use.
                            </div>
                        </div>

                        <hr class="colorgraph">
                        <div class="row">
                            <div class="col-xs-6 col-sm-6 col-md-6">
                                <input type="submit" value="Register" class="btn btn-primary btn-block btn-lg" tabindex="7">
                            </div>
                            <div class="col-xs-6 col-sm-6 col-md-6">
                                <a id="signInBtn" href="#" class="btn btn-block btn-lg btn-toggle">To Sign In</a>
                            </div>
                        </div>
                    </form>
...
</code>```

What should be in the controller in the login() and register() methods?
I've read about creating forms in Symfony, but I want to use the form from a view done manually.

Should it look like this?

```<code>public function login(Request $request) {
        $email = $request->get('email');
        $password = $request->get('password');

        $repository = $this->getDoctrine()->getRepository(User::class);
        $user = $repository->findOneBy([
            'email' => $email,
            'password' => $password
        ]);

        if($user) {
            // TODO: Set session
            return $this->redirectToRoute('timeline');
        }

        return $this->redirectToRoute('home');
    }

    public function register(Request $request) {
        $user = new User();

        $firstName = $request->get('first_name');
        $lastName = $request->get('last_name');
        $nickname = $request->get('display_name');
        $email = $request->get('email');
        $password = $request->get('password');
        $password2 = $request->get('password_confirmation');

        // VALIDATION

        return $this->render('message.html.twig', [
            'header' => 'Congratulations',
            'title' => 'Welcome <b>'. ucfirst($firstName) .' '. ucfirst($lastName) .'</b>!',
            'message' => 'The registration process completed correctly!
            An activation link has been sent to your e-mail address.',
            'button' => [
                'href' => $this->generateUrl('home'),
                'text' => 'To Sign In'
            ]
        ]);
    }
</code>```

答:
the login controller must to be something like this:

```<code> /**
     * @Route("/login", name="login_route")
     */
    public function loginAction()
    {

        $autenticacion = $this->get('security.authentication_utils');

        // if there is any error, here you get it
        $error = $autenticacion->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $autenticacion->getLastUsername();

        return $this->render(
            'login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $lastUsername,
                'error' => $error,
            )
        );
    }
</code>```

And the register do it saving the input in the view, you can use Type, becase the form needs hidden inputs for security.

Title: Symfony 4 - Manually Form

Body:
I'm creating my first project in Symfony framework.
I chose 4.0 version. I have a question about creating forms.

config/routes.yaml

home:
    path: /
    controller: App\Controller\HomeController::index
    methods: [GET]

login:
    path: /login
    controller: App\Controller\HomeController::login
    methods: [POST]

register:
    path: /register
    controller: App\Controller\HomeController::register
    methods: [POST]

timeline:
    path: /timeline
    controller: App\Controller\TimelineController::index
    methods: [GET]

src/Entity/User.php

//

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $lastName;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    public function getId()
    {
        return $this->id;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getFirstName()
    {
        return $this->firstName;
    }

    public function getLastName()
    {
        return $this->lastName;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }

    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;
    }

    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
    }

    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }
}

src/Controller/HomeController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\User;

class HomeController extends Controller
{
    public function index() {
        return $this->render('home/index.html.twig');
    }

    public function login(Request $request) {
        // ?????
    }

    public function register(Request $request) {
        $user = new User();
        // ?????
    }
}

templates/home/index.html.twig

...

<form action="{{ path('login') }}" id="signInForm" role="form"
      method="POST" class="visible">

Sign In

                            <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address">

                            <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password">

                            <button type="button" class="btn btn-info active" data-color="info">
                                 Remember Me</button>
                           <input type="checkbox" name="remember_me" id="remember_me" class="hidden">
                            Forgot Password?

                                  <input type="submit" class="btn btn-lg btn-success btn-block" value="Sign In">

                                To Register

                    </form>
                    <form action="{{ path('register') }}" id="registerForm" role="form" method="POST">

                            Please Sign Up
                            It's free and always will be.

                                    <input type="text" name="first_name" id="first_name" class="form-control input-lg" placeholder="First Name" tabindex="1">

                                    <input type="text" name="last_name" id="last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2">

                            <input type="text" name="display_name" id="display_name" class="form-control input-lg" placeholder="Display Name" tabindex="3">

                            <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4">

                                    <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">

                                    <input type="password" name="password_confirmation" id="password_confirmation" class="form-control input-lg" placeholder="Confirm Password"
                                        tabindex="6">

                                    <button type="button" class="btn" data-color="info" tabindex="7">I Agree</button>
                                    <input type="checkbox" name="t_and_c" id="t_and_c" class="hidden" value="1">

                                By clicking
                                Register, you agree to the
                                Terms and Conditions set out by this site, including our Cookie Use.

                                <input type="submit" value="Register" class="btn btn-primary btn-block btn-lg" tabindex="7">

                                To Sign In

                    </form>
...

What should be in the controller in the login() and register() methods?
I've read about creating forms in Symfony, but I want to use the form from a view done manually.

Should it look like this?

public function login(Request $request) {
        $email = $request->get('email');
        $password = $request->get('password');

        $repository = $this->getDoctrine()->getRepository(User::class);
        $user = $repository->findOneBy([
            'email' => $email,
            'password' => $password
        ]);

        if($user) {
            // TODO: Set session
            return $this->redirectToRoute('timeline');
        }

        return $this->redirectToRoute('home');
    }

    public function register(Request $request) {
        $user = new User();

        $firstName = $request->get('first_name');
        $lastName = $request->get('last_name');
        $nickname = $request->get('display_name');
        $email = $request->get('email');
        $password = $request->get('password');
        $password2 = $request->get('password_confirmation');

        // VALIDATION

        return $this->render('message.html.twig', [
            'header' => 'Congratulations',
            'title' => 'Welcome '. ucfirst($firstName) .' '. ucfirst($lastName) .'!',
            'message' => 'The registration process completed correctly!
            An activation link has been sent to your e-mail address.',
            'button' => [
                'href' => $this->generateUrl('home'),
                'text' => 'To Sign In'
            ]
        ]);
    }

Body:
the login controller must to be something like this:

 /**
     * @Route("/login", name="login_route")
     */
    public function loginAction()
    {

        $autenticacion = $this->get('security.authentication_utils');

        // if there is any error, here you get it
        $error = $autenticacion->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $autenticacion->getLastUsername();

        return $this->render(
            'login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $lastUsername,
                'error' => $error,
            )
        );
    }

And the register do it saving the input in the view, you can use Type, becase the form needs hidden inputs for security.


问:
Translating cURL request to python
I have to make a cURL request that sends information to the server, the working example request looks like:

```<code>curl "https://api.XX.com" -u ":test_KayuXJKEdc" -d "name=Sam" -d "address=123 Mockingbird" -d "city=Somewhere"
</code>```

I've tried pycurl, httplib2, and requests, I can't figure out how to properly format this. A non-working pycurl example from one of many attempts:

```<code>import pycurl

user = ':test_KayuXJKEdc'
name = 'name=Sam'
address = 'address=123 Mockingbird'
city = 'city=Somewhere'

c = pycurl.Curl()
data = BytesIO()
c.setopt(c.URL, 'https://api.XX.com')
c.setopt(pycurl.USERNAME, user)
c.setopt(pycurl.POSTFIELDS, name)
c.setopt(pycurl.POSTFIELDS, address)
c.setopt(pycurl.POSTFIELDS, city)
c.setopt(c.WRITEFUNCTION, data.write)
c.perform()
c.close()

result = json.loads(data.getvalue().decode('latin-1'))
print(result)
</code>```

I've done a lot of searching and experimenting for a couple days now. Any help is greatly appreciated. Thank you

答:
Thanks to Galen's comment and a fresh start, here is how I ended up formatting and getting it to work:

Instead of c.USERNAME I had to use c.USERPWD. This was an API key
and not a user name.

Reformatted the different data values to look like: {'name':
'Sam', 'city': 'Somewhere', etc...}

Used urlencode as per documentation before passing to c.POSTFIELDS

Title: Translating cURL request to python

Body:
I have to make a cURL request that sends information to the server, the working example request looks like:

curl "https://api.XX.com" -u ":test_KayuXJKEdc" -d "name=Sam" -d "address=123 Mockingbird" -d "city=Somewhere"

I've tried pycurl, httplib2, and requests, I can't figure out how to properly format this. A non-working pycurl example from one of many attempts:

import pycurl

user = ':test_KayuXJKEdc'
name = 'name=Sam'
address = 'address=123 Mockingbird'
city = 'city=Somewhere'

c = pycurl.Curl()
data = BytesIO()
c.setopt(c.URL, 'https://api.XX.com')
c.setopt(pycurl.USERNAME, user)
c.setopt(pycurl.POSTFIELDS, name)
c.setopt(pycurl.POSTFIELDS, address)
c.setopt(pycurl.POSTFIELDS, city)
c.setopt(c.WRITEFUNCTION, data.write)
c.perform()
c.close()

result = json.loads(data.getvalue().decode('latin-1'))
print(result)

I've done a lot of searching and experimenting for a couple days now. Any help is greatly appreciated. Thank you


问:
Swift: Local Notifications not popping up, although request / scheduled seems to works - no errors
I am trying to learn how to use local notifications and currently I am just trying to let a notification pop up when a certain time has passed (for the sake of learning just 5 seconds).

I register the notification in this function, which is used at the end of an onBoarding screen:

```<code>func registerNotification() {

    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Granted.")
        } else {
            print("Not granted.")
       }
    }
}
</code>```

Now to test the notification I just add the function set() to a button:

```<code>set() {

    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Test Notification"
    content.body = "It works!"
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}
</code>```

But when the button is pressed and 5 seconds passed, no notification is shown, but also no error in Xcode, so I suppose this should all work?

What am I missing here? As far as I understand from various sources on the net this is the easiest way to display a local notification?

答:
So to register a UserNotification and call the function at an appropriate
 place:

```<code>func registerNotification() {

    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Granted.")
        } else {
            print("Not granted.")
        }
    }
}
</code>```

This functions sets a notification with a time interval of 5 seconds. When the app is closed the notification will be displayed:

```<code>set() {

    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Test Notification"
    content.body = "It works!"
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}
</code>```

Body:
I am trying to learn how to use local notifications and currently I am just trying to let a notification pop up when a certain time has passed (for the sake of learning just 5 seconds).

I register the notification in this function, which is used at the end of an onBoarding screen:

func registerNotification() {

    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Granted.")
        } else {
            print("Not granted.")
       }
    }
}

Now to test the notification I just add the function set() to a button:

set() {

    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Test Notification"
    content.body = "It works!"
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}

But when the button is pressed and 5 seconds passed, no notification is shown, but also no error in Xcode, so I suppose this should all work?

What am I missing here? As far as I understand from various sources on the net this is the easiest way to display a local notification?

Body:
So to register a UserNotification and call the function at an appropriate
 place:

func registerNotification() {

    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Granted.")
        } else {
            print("Not granted.")
        }
    }
}

This functions sets a notification with a time interval of 5 seconds. When the app is closed the notification will be displayed:

set() {

    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Test Notification"
    content.body = "It works!"
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}


问:
Rails 3, update linked model in controller on record creation
In my rails app I have the Posts Model, which has_many Comments.

Everytime a new comment is posted, I'd like the updated_at column in the Posts model to be updated.

I assume I need to do this in the create method of the Comments controller.

Does anyone have some idea of the specific way to do this?

```<code>   @post = Post.find_by_id(@comment.post_id)
   @post.save!
</code>```

Did not work.

Thanks!

-Elliot

答:
I'd implement it in your commment model</p>

```<code>class Comment < ActiveRecord::Base
  belongs_to :post

  def after_create
    post.update_attribute(:updated_at, Time.now)
  end
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In my rails app I have the Posts Model, which has_many Comments.

Everytime a new comment is posted, I'd like the updated_at column in the Posts model to be updated.

I assume I need to do this in the create method of the Comments controller.

Does anyone have some idea of the specific way to do this?

   @post = Post.find_by_id(@comment.post_id)
   @post.save!

Did not work.

Thanks!

-Elliot

Body:
I'd implement it in your commment model

class Comment < ActiveRecord::Base
  belongs_to :post

  def after_create
    post.update_attribute(:updated_at, Time.now)
  end
end


问:
ASP.Net WebApi do not return form data via Content
I don't know if it's a bug but i'm unable to get raw request on server side.

Consider following controller method:

```<code>[AllowAnonymous]
[Route("api/sayHello")]
[HttpPost]
public string SayHello([FromBody] string userName)
{
    return $"Hello, {userName}.";
}
</code>```

I call it via cUrl:

```<code>curl -X POST 'https://localhost:809/api/sayHello' --insecure -d "=userName"
</code>```

It works fine.

Now I'm trying to add some logging. I add a global filter which is doing following:

```<code>public async Task LogFilterAction(HttpActionContext context)
{
    if (context == null)
        throw new ArgumentNullException(nameof(context));
    LogFilterAction(context.ActionDescriptor?.ControllerDescriptor?.ControllerType,
        context.ActionDescriptor?.ActionName,
        context.Request?.RequestUri,
        await GetDataAsString(context.Request?.Content),
        context.Response?.StatusCode
    );
}

private static async Task<string> GetDataAsString(HttpContent content)
{
    if (content == null)
        return null;
    var contentBytes = await content.ReadAsByteArrayAsync();
    return Encoding.UTF8.GetString(contentBytes);
}
</code>```

But here is the problem: for unknown reason reason contentBytes are always an empty array. I see that it's actual length is 9 (it's length of =userName string)

Or Even

As you can see, ASP.Net has successfully request arguments, however, it doesn't return it's in raw manner. Stream has position=0, contentConsumed=false, and everything else is just fine. But i can't read data passed to the controller.

What's wrong here?

答:
ASP.NET Web API reads the content only once, so at the time that you access the content stream, it has already been read and the stream is positioned at its end. Another attempt to read the content will return nothing.

However, in a small sample I was able to reset the stream and read it again:

```<code>private async Task<string> GetDataAsString(HttpContent content)
{
    if (content == null)
        return null;
    using (var str = await content.ReadAsStreamAsync())
    {
        if (str.CanSeek)
            str.Seek(0, System.IO.SeekOrigin.Begin);
        using (var rdr = new StreamReader(str))
        {
            return rdr.ReadToEnd();
        }
    }
}
</code>```

However, in order to avoid side effects, you might want to consider to use the ActionArguments property of the ActionContext. You can use this property to retrieve the values that are handed to the action for logging. This does not interfere with the internal plumbing of ASP.NET Web API.

Body:
I don't know if it's a bug but i'm unable to get raw request on server side.

Consider following controller method:

[AllowAnonymous]
[Route("api/sayHello")]
[HttpPost]
public string SayHello([FromBody] string userName)
{
    return $"Hello, {userName}.";
}

I call it via cUrl:

curl -X POST 'https://localhost:809/api/sayHello' --insecure -d "=userName"

It works fine.

Now I'm trying to add some logging. I add a global filter which is doing following:

public async Task LogFilterAction(HttpActionContext context)
{
    if (context == null)
        throw new ArgumentNullException(nameof(context));
    LogFilterAction(context.ActionDescriptor?.ControllerDescriptor?.ControllerType,
        context.ActionDescriptor?.ActionName,
        context.Request?.RequestUri,
        await GetDataAsString(context.Request?.Content),
        context.Response?.StatusCode
    );
}

private static async Task<string> GetDataAsString(HttpContent content)
{
    if (content == null)
        return null;
    var contentBytes = await content.ReadAsByteArrayAsync();
    return Encoding.UTF8.GetString(contentBytes);
}

But here is the problem: for unknown reason reason contentBytes are always an empty array. I see that it's actual length is 9 (it's length of =userName string)

Or Even

As you can see, ASP.Net has successfully request arguments, however, it doesn't return it's in raw manner. Stream has position=0, contentConsumed=false, and everything else is just fine. But i can't read data passed to the controller.

What's wrong here?

Body:
ASP.NET Web API reads the content only once, so at the time that you access the content stream, it has already been read and the stream is positioned at its end. Another attempt to read the content will return nothing.

However, in a small sample I was able to reset the stream and read it again:

private async Task<string> GetDataAsString(HttpContent content)
{
    if (content == null)
        return null;
    using (var str = await content.ReadAsStreamAsync())
    {
        if (str.CanSeek)
            str.Seek(0, System.IO.SeekOrigin.Begin);
        using (var rdr = new StreamReader(str))
        {
            return rdr.ReadToEnd();
        }
    }
}

However, in order to avoid side effects, you might want to consider to use the ActionArguments property of the ActionContext. You can use this property to retrieve the values that are handed to the action for logging. This does not interfere with the internal plumbing of ASP.NET Web API.


问:
Spring Data Neo4j @Index annotation on collection property
will the SDN <code>@Index</code> work properly on the collection properties, something like this: </p>

```<code>@Index(unique = false)
private Set<Long> optionIds;
</code>```

答:
This is possible and should work, an index should be created on property optionIds for given label.

But most likely this will not work as you expect. The problem comes from how Neo4j indexes arrays (and the fact it can't index sets - only lists and it can't index individual elements from arrays).

Whole arrays will be indexed and then can be looked up by whole arrays again. If you want to do index lookups by whole sets use sorted sets so the ids are always in the same order in the stored array (Set is stored as array by OGM).

You can't do index lookups by individual elements from the indexed array.

Body:
will the SDN @Index work properly on the collection properties, something like this:

@Index(unique = false)
private Set<Long> optionIds;


问:
Why is this std::vector being cleared when program enters main function?
The problem I'm having is that I am pushing an element into a vector at initialisation when all the static variables are initialised, and then when it enters the main function the vector resets to 0, as if it has cleared. In my case the vector was in a different CPP, but this also shows the problem:

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

struct List
{
    static std::vector<int> listVector;
};

struct Foo
{
    Foo()
    {
        std::cout << List::listVector.size() << '\n';   // Prints 0
        List::listVector.push_back(1);
        std::cout << List::listVector.size() << '\n';   // Prints 1
    }
};
Foo fooObj;

std::vector<int> List::listVector;

int main()
{
    std::cout << List::listVector.size() << '\n';   // Prints 0
    List::listVector.push_back(2);
    std::cout << List::listVector.size() << '\n';   // Prints 1
}
</code>```

The first element I added to the vector has been lost. I know one has to be careful with initialisation order of static global variables, but I can't understand why the vector is being cleared. I'm tempted to think that when the Foo constructor runs it adds an element to the vector, but the vector hasn't been created yet, because it's written on the line after the Foo object is created. However, if this is the case, just what vector am I adding into when I do so in the constructor and it prints out a size of 1?

I'm kind of confused.

答:
if you change the code to

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

namespace List
{
    static std::vector<int> listVector;
}

struct Foo
{
    Foo()
    {
        std::cout << List::listVector.size() << '\n';   // Prints 0
        List::listVector.push_back(1);
        std::cout << List::listVector.size() << '\n';   // Prints 1
    }
};
Foo fooObj;

//std::vector<int> List::listVector;

int main()
{
    std::cout << List::listVector.size() << '\n';   // Prints 0
    List::listVector.push_back(2);
    std::cout << List::listVector.size() << '\n';   // Prints 1
}
</code>```

it should work. I'm not in global variables (I don't use them) but I think the problem that the struct param don't make it real global. Maybe a other user can explain it ...

Edit: you can also remove the namespace, i make it so you can let the List::

Edit2: if you want to use with struct than it works with

```<code>struct List
{
    std::vector<int> listVector;
};

static List GlobL;
</code>```

And than use GlobL.listVector, than the struct obj ist static and not the parameter of the struct.

Body:
The problem I'm having is that I am pushing an element into a vector at initialisation when all the static variables are initialised, and then when it enters the main function the vector resets to 0, as if it has cleared. In my case the vector was in a different CPP, but this also shows the problem:

#include <iostream>
#include <vector>

struct List
{
    static std::vector<int> listVector;
};

struct Foo
{
    Foo()
    {
        std::cout << List::listVector.size() << '\n';   // Prints 0
        List::listVector.push_back(1);
        std::cout << List::listVector.size() << '\n';   // Prints 1
    }
};
Foo fooObj;

std::vector<int> List::listVector;

int main()
{
    std::cout << List::listVector.size() << '\n';   // Prints 0
    List::listVector.push_back(2);
    std::cout << List::listVector.size() << '\n';   // Prints 1
}

The first element I added to the vector has been lost. I know one has to be careful with initialisation order of static global variables, but I can't understand why the vector is being cleared. I'm tempted to think that when the Foo constructor runs it adds an element to the vector, but the vector hasn't been created yet, because it's written on the line after the Foo object is created. However, if this is the case, just what vector am I adding into when I do so in the constructor and it prints out a size of 1?

I'm kind of confused.

Body:
if you change the code to

#include <iostream>
#include <vector>

namespace List
{
    static std::vector<int> listVector;
}

struct Foo
{
    Foo()
    {
        std::cout << List::listVector.size() << '\n';   // Prints 0
        List::listVector.push_back(1);
        std::cout << List::listVector.size() << '\n';   // Prints 1
    }
};
Foo fooObj;

//std::vector<int> List::listVector;

int main()
{
    std::cout << List::listVector.size() << '\n';   // Prints 0
    List::listVector.push_back(2);
    std::cout << List::listVector.size() << '\n';   // Prints 1
}

it should work. I'm not in global variables (I don't use them) but I think the problem that the struct param don't make it real global. Maybe a other user can explain it ...

Edit: you can also remove the namespace, i make it so you can let the List::

Edit2: if you want to use with struct than it works with

struct List
{
    std::vector<int> listVector;
};

static List GlobL;

And than use GlobL.listVector, than the struct obj ist static and not the parameter of the struct.


问:
Same JMX Mbean class for many application at same server
I have more than 5 spring web application and all of them are utilizing another common library. This common library has its own MBeans. Because of mandatory unique objectName constraint, my applications could not be deployed on same server.

The way I am using MBeans are like this:

```<code>@ManagedResource(objectName = "com.org.city:name=City", description = "City related operations")
</code>```

I would like to use same MBean class with different objectNames for all applications. What is the correct way to utilize it without duplicating my MBeans.

Thanks

答:
These answers helped point me in the right direction, but there were a few pieces missing for an Annotation based setup (I'm not using Spring Boot however)

The Spring Docs on this subject say:

If you prefer using the annotation based approach to define your management interfaces, then a convenience subclass of MBeanExporter is available: AnnotationMBeanExporter. When defining an instance of this subclass, the namingStrategy, assembler, and attributeSource configuration is no longer needed, since it will always use standard Java annotation-based metadata (autodetection is always enabled as well). In fact, rather than defining an MBeanExporter bean, an even simpler syntax is supported by the @EnableMBeanExport @Configuration annotation.

But using @EnableMBeanExport prevents you from having the ability of defining your own NamingStrategy

So Instead of just setup a @Bean method that returns my MBeanExporter with a custom naming strategy that uses the context path.

```<code>@Configuration
public class JmxUtil {

    @Value("#{servletContext.contextPath}")
    private String contextPath;
    private String domain = "foo.bar";

    @Bean
    public MBeanExporter mbeanExporter() {
        AnnotationMBeanExporter exporter = new AnnotationMBeanExporter();
        exporter.setNamingStrategy((managedBean, beanKey) -> {
            return ObjectNameManager.getInstance(domain, new Hashtable<>(ImmutableMap.of(
                "name", beanKey,
                "instance", contextPath
            )));
        });
        exporter.setDefaultDomain(domain);
        return exporter;
    }
}
</code>```

Body:
I have more than 5 spring web application and all of them are utilizing another common library. This common library has its own MBeans. Because of mandatory unique objectName constraint, my applications could not be deployed on same server.

The way I am using MBeans are like this:

@ManagedResource(objectName = "com.org.city:name=City", description = "City related operations")

I would like to use same MBean class with different objectNames for all applications. What is the correct way to utilize it without duplicating my MBeans.

Thanks

Body:
These answers helped point me in the right direction, but there were a few pieces missing for an Annotation based setup (I'm not using Spring Boot however)

The Spring Docs on this subject say:

If you prefer using the annotation based approach to define your management interfaces, then a convenience subclass of MBeanExporter is available: AnnotationMBeanExporter. When defining an instance of this subclass, the namingStrategy, assembler, and attributeSource configuration is no longer needed, since it will always use standard Java annotation-based metadata (autodetection is always enabled as well). In fact, rather than defining an MBeanExporter bean, an even simpler syntax is supported by the @EnableMBeanExport @Configuration annotation.

But using @EnableMBeanExport prevents you from having the ability of defining your own NamingStrategy

So Instead of just setup a @Bean method that returns my MBeanExporter with a custom naming strategy that uses the context path.

@Configuration
public class JmxUtil {

    @Value("#{servletContext.contextPath}")
    private String contextPath;
    private String domain = "foo.bar";

    @Bean
    public MBeanExporter mbeanExporter() {
        AnnotationMBeanExporter exporter = new AnnotationMBeanExporter();
        exporter.setNamingStrategy((managedBean, beanKey) -> {
            return ObjectNameManager.getInstance(domain, new Hashtable<>(ImmutableMap.of(
                "name", beanKey,
                "instance", contextPath
            )));
        });
        exporter.setDefaultDomain(domain);
        return exporter;
    }
}


问:
Cloudformation SimpleAD assign custom Security Group
I am using cloudformation to create a SimpleAD; By default AWS creates a security group which opens a bunch of ports to the internet 0.0.0.0/0
The port opened are the following;
UDP 445, 138, 464, 389, 53, 123, 88
TCP 464, 389, 445, 3268-3269, 1024 - 65535, 88, 135, 636, 53
ICMP ALL

The AWS environment has a WatchDog which sees any outbound security group line going to 0.0.0.0/0 and deletes it

I am now planning to create a custom security group which will open these ports within the VPC CIDR and want to assign this to the SimpleAD

For this we will need to assign the same to the Network Interface.
My Question is how will I find the network interface already existing for this Simple AD and assign this

I am thinking boto3 is the way to go; has anyone done this in cloudformation?

答:
I was not able to assign a security group to the AD via boto; however, I did the following

Found the Security group associated with the AD; edited the security group to be restricted to the VPC

if anyone is interested in the code please ping me and I will send it over


问:
Struggling with while loop with two conditions and a for loop
I'm trying to learn how to use arrays in bash. I'm writing a script that asks the user for three numbers and figures out what the biggest number is. I want the script to force the user to enter only numeric values. Furthermore, I want the three numbers should be different. I'm using an array to store user input. This is what I have so far:

```<code>## declare variables
order=("first" "second" "third")
answers=()
RED='\033[0;31m'
NC='\033[0m' # No Color

numbersonly() {
        if [[ ! $1 =~ ^[0-9]+$ ]]; then
        echo "${RED}$1 is not a valid number.${NC}"
        else
            answers+=("$input")
            break
        fi
}

inarray(){
    for e in ${answers[@]}; do
    if [[ $1 == $e ]]; then
    echo "${RED}Warning.${NC}"
    fi
    done
}

readnumber(){
for i in {1..3}; do
j=$(awk "BEGIN { print $i-1 }")
    while read -p "Enter the ${order[$j]} number: " input ; do
    inarray $input
    numbersonly $input
    done
done
}

displayanswers(){
echo "Your numbers are: ${answers[@]}"
}

biggestnumber(){

if (( ${answers[0]} >= ${answers[1]} )); then
        biggest=${answers[0]}
        else
        biggest=${answers[1]}
        fi
if (( $biggest <= ${answers[2]} )); then
        biggest=${answers[2]}
        fi
echo "The biggest number is: $biggest"
}

main(){
readnumber
displayanswers
biggestnumber
}

main
</code>```

Right now, I can get the script to display a warning when the user enters a number that was previously entered, but I can't seem to find the proper syntax to stay in the while loop if the user input has already been entered. Thoughts?

答:
I found a way around it. My problem was twofold: 1) I didn't realize that if you have a for loop nested in a while loop, you'll need two break statements to exit the while loop; 2) having two functions within the same while loop made it hard to control what was happening. By merging inarray() and numbersonly() into a new function, I solved the double conditional issue. The new function looks like this:</p>

```<code>testing(){
for item in ${answers[*]}
do
    test "$item" == "$1" && { inlist="yes"; break; } || inlist="no"
done

if [[ $inlist == "yes" ]]; then
echo "${RED}$1 is already in list.${NC}"
else
        if [[ ! $1 =~ ^[0-9]+$ ]]; then
        echo "${RED}$1 is not a valid number.${NC}"
        else
            answers+=("$input")
            break
        fi
fi
}
</code>```

Body:
I'm trying to learn how to use arrays in bash. I'm writing a script that asks the user for three numbers and figures out what the biggest number is. I want the script to force the user to enter only numeric values. Furthermore, I want the three numbers should be different. I'm using an array to store user input. This is what I have so far:

## declare variables
order=("first" "second" "third")
answers=()
RED='\033[0;31m'
NC='\033[0m' # No Color

numbersonly() {
        if [[ ! $1 =~ ^[0-9]+$ ]]; then
        echo "${RED}$1 is not a valid number.${NC}"
        else
            answers+=("$input")
            break
        fi
}

inarray(){
    for e in ${answers[@]}; do
    if [[ $1 == $e ]]; then
    echo "${RED}Warning.${NC}"
    fi
    done
}

readnumber(){
for i in {1..3}; do
j=$(awk "BEGIN { print $i-1 }")
    while read -p "Enter the ${order[$j]} number: " input ; do
    inarray $input
    numbersonly $input
    done
done
}

displayanswers(){
echo "Your numbers are: ${answers[@]}"
}

biggestnumber(){

if (( ${answers[0]} >= ${answers[1]} )); then
        biggest=${answers[0]}
        else
        biggest=${answers[1]}
        fi
if (( $biggest <= ${answers[2]} )); then
        biggest=${answers[2]}
        fi
echo "The biggest number is: $biggest"
}

main(){
readnumber
displayanswers
biggestnumber
}

main

Right now, I can get the script to display a warning when the user enters a number that was previously entered, but I can't seem to find the proper syntax to stay in the while loop if the user input has already been entered. Thoughts?

Body:
I found a way around it. My problem was twofold: 1) I didn't realize that if you have a for loop nested in a while loop, you'll need two break statements to exit the while loop; 2) having two functions within the same while loop made it hard to control what was happening. By merging inarray() and numbersonly() into a new function, I solved the double conditional issue. The new function looks like this:

testing(){
for item in ${answers[*]}
do
    test "$item" == "$1" && { inlist="yes"; break; } || inlist="no"
done

if [[ $inlist == "yes" ]]; then
echo "${RED}$1 is already in list.${NC}"
else
        if [[ ! $1 =~ ^[0-9]+$ ]]; then
        echo "${RED}$1 is not a valid number.${NC}"
        else
            answers+=("$input")
            break
        fi
fi
}


问:
Declaring two-dimensional array locally and storing on heap with non-constant size
In C when you declare e.g. int ar[x][y]; it actually is int[x*y], and you calls are compiled in needed manner.

But this array is stored on stack if made inside a function.
I'm looking for a way to have it stored on heap, while having the same functionality. Because when I was looking for a way to do is, the only thing I found was make int** and then each of element (type int*) would be pointer to another array. (Correct me if I'm wrong) It seems legit but the second way doesn't store the values one after another and also uses more memory. For ar[x][y] first method is just x*y*sizeof(int), but for second it's x*y*sizeof(int)+x*sizeof(int*).

Summarizing is having two-dimensional array stored on heap possible, while maintaining functionality of int ar[x][y]?

EDIT: I'm sorry for misleading everyone, but ar[3][4] was just en example, I'm actually looking for a way to do this with non-constant size.

EDIT2: Actually I'm even looking for sth that will also work in raw C.

答:
If at least one of the sizes is known at compile time, you can use standard C++ containers:

```<code> using my2daraytype  = std::array<std::array<int, N>, M>; // both N and M are compile time constants
 // allocate this on the heap normally (e.g. with std::make_unique)
 // example
 auto myarray = std::make_unique<my2daraytype>();
</code>```

Note that myarray above is a (smart) pointer to a 2d array, so you access it as (*myarray)[i][i].

```<code> using my2daraytype = std::vector<std::array<int, N>>; // inner size N is known
 // data already lives on the heap, no need to allocate
 // example
 my2darraytype myarray(M);
</code>```

This one is not a pointer so you use myarray[i][j].

When both sizes are determined at run time, this is not so easy. std::vector<std::vector<int>> memory is organised similarly to int** so it is not suitable. You may want to create your own class that stores std::vector<int> of size M*N internally, and provide a two-argument int& operator()(size_t, size_t) for indexing. The familiar syntax with two levels of square brackets is possible but too complicated and potentially inefficient, so it's rarely worth the trouble. myarray(i,j) works perfectly so just use that.

Here's one possible basic outline of the class (unfinished, unteated) templatized for convenience:

```<code>template <class T>
class my2darray {
    std::vector<T> values;
    size_t m, n;
   public:
     my2darray(size_t m, size_t n) : values(m*n), m(m), n(n) {}
     T& operator()(size_t i, size_t j) {
          return values[i*n+j];
      }
};
</code>```

It needs more code to be fully functional but this is the basis.

Body:
If at least one of the sizes is known at compile time, you can use standard C++ containers:

 using my2daraytype  = std::array<std::array<int, N>, M>; // both N and M are compile time constants
 // allocate this on the heap normally (e.g. with std::make_unique)
 // example
 auto myarray = std::make_unique<my2daraytype>();

Note that myarray above is a (smart) pointer to a 2d array, so you access it as (*myarray)[i][i].

 using my2daraytype = std::vector<std::array<int, N>>; // inner size N is known
 // data already lives on the heap, no need to allocate
 // example
 my2darraytype myarray(M);

This one is not a pointer so you use myarray[i][j].

When both sizes are determined at run time, this is not so easy. std::vector<std::vector<int>> memory is organised similarly to int** so it is not suitable. You may want to create your own class that stores std::vector<int> of size M*N internally, and provide a two-argument int& operator()(size_t, size_t) for indexing. The familiar syntax with two levels of square brackets is possible but too complicated and potentially inefficient, so it's rarely worth the trouble. myarray(i,j) works perfectly so just use that.

Here's one possible basic outline of the class (unfinished, unteated) templatized for convenience:

template <class T>
class my2darray {
    std::vector<T> values;
    size_t m, n;
   public:
     my2darray(size_t m, size_t n) : values(m*n), m(m), n(n) {}
     T& operator()(size_t i, size_t j) {
          return values[i*n+j];
      }
};

It needs more code to be fully functional but this is the basis.


问:
Allow quantity selection even when price is zero
I have this code string that does the following...

Condition: only if product category is 'stone' then

adds "per ft squared" after the price

if the price is left empty, instead of it saying $0 it says "call for price"

Goal: when the product doesnt have a price or is zero, I want the quantity selector to remain visible on the product page.

// Add's feet squared to pricing only if prododuct category is 'stone'

add_filter( 'woocommerce_get_price_html', 'custom_price_message' );

function custom_price_message($price) {

if ( !has_term( 'stone', 'product_cat' ) ) {
   return $price;

} elseif (!empty($price)){
   $vat = ' per ft2';
   return $price . $vat;

 }else{
   return 'Call for Price';
 }```

答:
Found it! This makes no purchasable product purchasable

add_filter( 'woocommerce_is_purchasable', 'wpa_109409_is_purchasable', 10, 2 );

function wpa_109409_is_purchasable( $purchasable, $product ){
    if( $product->get_price() >= 0 )
        $purchasable = true;
    return $purchasable;
}```


问:
Match multiple characters one or more times
Consider the following problem:
We have a string of random chars flowing from /dev/urandom and we want to process it in such way that we will get strings of a constant length which meet certain conditions .
For example if we run the following command 5 times we get :

```<code>cat /dev/urandom |tr -dc A-Z5|head -c${1:-30}
DLZEZDATSTDN55BNVDSNRFSLRKHDGR
AVCRIE5OAFBUWZZYQYQWCTAZSNMQAA
HSTFN5AQNWILXMSZCBIGREPNCFGPDM
AZJNEUQRCDYSKXMQDUHVTOFEOAYPHF
ANFDWHHZHLAGXCPKWLQESSZLEZYNDC
</code>```

Now, these strings meet the conditions I need but only partially.
For ex. I need that the digit 5 to appear at least 2 times but no more than 7 times in a string and any of the letters should not appear more than 10 times.
How should I customize the command above to get this result ?

答:
Bash solution using a function with the filter needed by OP.

Explanation :

filter is the count of character 5 appearances. I get that by removing everything on the string with tr except the character 5 and then counting how many chars are left.

grep -E '(.)(.\1){10}'* is  a standard regular expression to make sure no character is present more than 10 times.

The loop then just gets one random word after the other until all the three conditions are met. It can take a random time of course. :P

```<code>function GETRANDOMWORD {
    local filter=0;
    until [[ $filter -gt 1 && $filter -lt 8 && ! $( echo "$word" | grep -E '(.)(.*\1){10}') ]]
    do
        word="$( cat /dev/urandom |tr -dc A-Z5|head -c${1:-30} )"
        filter=$( echo "$word" | tr -cd '5' | wc -c )
    done
    [[ "$word" ]] && echo "$word"
}
</code>```

Usage :

Body:
Consider the following problem:
We have a string of random chars flowing from /dev/urandom and we want to process it in such way that we will get strings of a constant length which meet certain conditions .
For example if we run the following command 5 times we get :

cat /dev/urandom |tr -dc A-Z5|head -c${1:-30}
DLZEZDATSTDN55BNVDSNRFSLRKHDGR
AVCRIE5OAFBUWZZYQYQWCTAZSNMQAA
HSTFN5AQNWILXMSZCBIGREPNCFGPDM
AZJNEUQRCDYSKXMQDUHVTOFEOAYPHF
ANFDWHHZHLAGXCPKWLQESSZLEZYNDC

Now, these strings meet the conditions I need but only partially.
For ex. I need that the digit 5 to appear at least 2 times but no more than 7 times in a string and any of the letters should not appear more than 10 times.
How should I customize the command above to get this result ?

Body:
Bash solution using a function with the filter needed by OP.

Explanation :

filter is the count of character 5 appearances. I get that by removing everything on the string with tr except the character 5 and then counting how many chars are left.

grep -E '(.)(.\1){10}'* is  a standard regular expression to make sure no character is present more than 10 times.

The loop then just gets one random word after the other until all the three conditions are met. It can take a random time of course. :P

function GETRANDOMWORD {
    local filter=0;
    until [[ $filter -gt 1 && $filter -lt 8 && ! $( echo "$word" | grep -E '(.)(.*\1){10}') ]]
    do
        word="$( cat /dev/urandom |tr -dc A-Z5|head -c${1:-30} )"
        filter=$( echo "$word" | tr -cd '5' | wc -c )
    done
    [[ "$word" ]] && echo "$word"
}

Usage :