问:
How to code for optional command line parameters in C
My program has to accept optional command line parameters where there will be either 1 or 3 parameters (executable, number of rows, number of columns). If argc is anything other than 3, we have to create a board that is 10x10 (I've already made a function to create the board).

I'm not sure how to account for this. One restriction on main.c is that we're only allowed to declare/assign variables and call functions, so I'm stuck on how I'm supposed to make this work. My initial idea was to write a function correctNumOfArgs to check if argc is 3, and then return true or false. I would then use that result in a different function to determine how to create the board, but that would still require me to pass argv[1] and argv[2] as parameters in the function and they might not even exist. How do I get around this? Note: I looked at other questions regarding optional command line parameters and they suggested solutions more advanced than what we have learned. Is there a more basic solution to this?

答:
You can do it quite easily with variable assignment using a ternary operator to check if argc > 2 and if it is, convert the supplied arguments to rows and cols, otherwise, use the default 10 for each, e.g.

```<code>errno = 0;

int rows = argc > 2 ? (int)strtol (argv[1], NULL, 10) : 10,
    cols = argc > 2 ? (int)strtol (argv[2], NULL, 10) : 10;

if (errno) { /* handle error in strtol conversion    */
             /* (you should also check for overflow) */ }
</code>```

(note: always check for error in the conversion before continuing -- you can move this to a function and fully validate the strtol conversion by checking nptr against endptr to insure characters were converted, and then saving the value to a temporary long value, you can insure the values are between INT_MIN and INT_MAX (and reasonable) before assigning to rows, cols)

If you must use a function, just pass a pointer to rows and cols as parameters and then set the values stored at each respective address within the function. That way you have a simple function call that can return 0/1 for success/failure and update the values for rows, cols through the pointers passed as parameters.

Body:
You can do it quite easily with variable assignment using a ternary operator to check if argc > 2 and if it is, convert the supplied arguments to rows and cols, otherwise, use the default 10 for each, e.g.

errno = 0;

int rows = argc > 2 ? (int)strtol (argv[1], NULL, 10) : 10,
    cols = argc > 2 ? (int)strtol (argv[2], NULL, 10) : 10;

if (errno) { /* handle error in strtol conversion    */
             /* (you should also check for overflow) */ }

(note: always check for error in the conversion before continuing -- you can move this to a function and fully validate the strtol conversion by checking nptr against endptr to insure characters were converted, and then saving the value to a temporary long value, you can insure the values are between INT_MIN and INT_MAX (and reasonable) before assigning to rows, cols)

If you must use a function, just pass a pointer to rows and cols as parameters and then set the values stored at each respective address within the function. That way you have a simple function call that can return 0/1 for success/failure and update the values for rows, cols through the pointers passed as parameters.


来源: stackexchange

问:
How to compile C++ files organized in a directory structure?
I've written a bunch of code now, and sorted it in a fashion similar to this outline:

```<code>project/
+ include/
| + bar/
| |   bar.hpp
|   foo.hpp
+ src/
| + bar/
| |   bar.cpp
|   foo.cpp
|   main.cpp
</code>```

My question is, how do I call g++ now, so that it links everything together nicely?

I've already figured out that I need to call it with the -I option pointing to the include/ directory. I'm guessing it would make most sense calling g++ from the project/ folder. Also, I'm considering writing a Makefile to automate this process, but I have to admit I haven't done very much research on that yet.

答:
I would recommend using some kind of build tool like CMake or Autotools. Creating your own Makefiles can be kind of a PITA to get right.

If you have a small directory structure with some C++ files which you want to quickly compile, you can do something like this:

```<code>find src/ -name "*.cpp" | xargs g++ -I include/
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've written a bunch of code now, and sorted it in a fashion similar to this outline:

project/
+ include/
| + bar/
| |   bar.hpp
|   foo.hpp
+ src/
| + bar/
| |   bar.cpp
|   foo.cpp
|   main.cpp

My question is, how do I call g++ now, so that it links everything together nicely?

I've already figured out that I need to call it with the -I option pointing to the include/ directory. I'm guessing it would make most sense calling g++ from the project/ folder. Also, I'm considering writing a Makefile to automate this process, but I have to admit I haven't done very much research on that yet.

Body:
I would recommend using some kind of build tool like CMake or Autotools. Creating your own Makefiles can be kind of a PITA to get right.

If you have a small directory structure with some C++ files which you want to quickly compile, you can do something like this:

find src/ -name "*.cpp" | xargs g++ -I include/


问:
How to delete all items from an FormApp object?
I recently asked a question about how to add items to a Google Form from a Google Spreadsheet. And it works great. Instead of using FormApp.create(), though, I'll have to use .openByUrl() because the ID has to stay the same. The problem is that if I run my script again, it'll open the existing form (great) and then append more items to the existing form.

This behaviour makes perfect sense but is not quite what I want. So I thought I'd just remove all existing items before I add new ones from my spreadsheet. I consulted the Google dev site for Form Services and feel like I should have all the pieces. I can't quite put them together, though.

I am now doing this following:

```<code>var form = FormApp.openByUrl('https://docs.google.com/forms/d/.../edit');
var items = form.getItems();
for (var i in items) {
    form.deleteItem(i);
}
</code>```

However, that'll give me an out of range error. Can someone point me in the right direction?

答:
Start by deleting the last item and repeat it until all items are deleted. This could be done by a reverse for loop:

```<code>function deleteAllItems(){
  var form = FormApp.openById(/*put here your form id*/);
  var items = form.getItems();
  var end = items.length - 1;
  for(var i = end ; i >= 0; i--){
    form.deleteItem(i);
  }
}
</code>```

Another alternative is avoid of a variable index by using 0, so the first item will be deleted, no matter if a regular or a reverse loop is used. Note: This was already mentioned in a comment to another answer.

ContentLicense: CC BY-SA 3.0

Body:
I recently asked a question about how to add items to a Google Form from a Google Spreadsheet. And it works great. Instead of using FormApp.create(), though, I'll have to use .openByUrl() because the ID has to stay the same. The problem is that if I run my script again, it'll open the existing form (great) and then append more items to the existing form.

This behaviour makes perfect sense but is not quite what I want. So I thought I'd just remove all existing items before I add new ones from my spreadsheet. I consulted the Google dev site for Form Services and feel like I should have all the pieces. I can't quite put them together, though.

I am now doing this following:

var form = FormApp.openByUrl('https://docs.google.com/forms/d/.../edit');
var items = form.getItems();
for (var i in items) {
    form.deleteItem(i);
}

However, that'll give me an out of range error. Can someone point me in the right direction?

Body:
Start by deleting the last item and repeat it until all items are deleted. This could be done by a reverse for loop:

function deleteAllItems(){
  var form = FormApp.openById(/*put here your form id*/);
  var items = form.getItems();
  var end = items.length - 1;
  for(var i = end ; i >= 0; i--){
    form.deleteItem(i);
  }
}

Another alternative is avoid of a variable index by using 0, so the first item will be deleted, no matter if a regular or a reverse loop is used. Note: This was already mentioned in a comment to another answer.


问:
How center the text between the limits of the picture
I'm doing a tool to help in a game. The original game looks like this:

I was able to do the elixir number on the purple drop on the top-left. The transparent label to show the Level. (still need to work with the right colors based in card rarity).

But cant make the label center on the bottom and if possible looks like inside the border instead of above the whole picture.

I was trying following this question CSS center text (horizontally and vertically) inside a div block but haven't be able to make it work.

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header-content {
  position: absolute;
  bottom: 0;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div></code>```

答:
First you need to make the image max-width:100% to avoid overflow, then simply adjust left/right/bottom values since your element is absolute position and add text-align:center :

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header img {
  max-width:100%;
}
#header-content {
  position: absolute;
  bottom: 5px;
  left:5px;
  right:5px;
  text-align:center;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div></code>```

Body:
I'm doing a tool to help in a game. The original game looks like this:

I was able to do the elixir number on the purple drop on the top-left. The transparent label to show the Level. (still need to work with the right colors based in card rarity).

But cant make the label center on the bottom and if possible looks like inside the border instead of above the whole picture.

I was trying following this question CSS center text (horizontally and vertically) inside a div block but haven't be able to make it work.

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header-content {
  position: absolute;
  bottom: 0;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
}

   4
   Level 2

Body:
First you need to make the image max-width:100% to avoid overflow, then simply adjust left/right/bottom values since your element is absolute position and add text-align:center :

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}

#header img {
  max-width:100%;
}
#header-content {
  position: absolute;
  bottom: 5px;
  left:5px;
  right:5px;
  text-align:center;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
}

<div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div>


问:
Rails - Where condition in models
I am using nested includes on Active Record. I want to add conditions on associated models in nested Includes.
In the following code, I have to add where condition on submissions and user_tutorials associations.

How to conditionally include associated models when using .to_json on a model?

```<code>@courses = Course.where("course_id=?",15).includes(:course_series,{courses_languages:[{courses_tutorials:[{tutorials:[{submissions:[:users]},:user_tutorials]}]}]})

@courses.to_json(:include =>
            [:course_series,
            {:courses_languages =>
                {:include =>
                  {:courses_tutorials =>
                    {:include =>
                      {:tutorials =>
                        {:include =>
                          {:submissions =>
                            {:include =>
                              {users: {only: [:user_id]}}
                          },
                          :user_tutorials => {}
                        }
                      }
                    }
                  }
                }
              }
            }
          ])
</code>```

答:
try this: </p>

```<code>    @course=Course.where(course_id: 15).includes(:course_series).(:course_languages).user_tutorials.where(/* condition for user_tutorials */).submissions.where(/* condition for submissions */)
</code>```

Title: Rails - Where condition in models

Body:
I am using nested includes on Active Record. I want to add conditions on associated models in nested Includes.
In the following code, I have to add where condition on submissions and user_tutorials associations.

How to conditionally include associated models when using .to_json on a model?

@courses = Course.where("course_id=?",15).includes(:course_series,{courses_languages:[{courses_tutorials:[{tutorials:[{submissions:[:users]},:user_tutorials]}]}]})

@courses.to_json(:include =>
            [:course_series,
            {:courses_languages =>
                {:include =>
                  {:courses_tutorials =>
                    {:include =>
                      {:tutorials =>
                        {:include =>
                          {:submissions =>
                            {:include =>
                              {users: {only: [:user_id]}}
                          },
                          :user_tutorials => {}
                        }
                      }
                    }
                  }
                }
              }
            }
          ])

Body:
try this:

    @course=Course.where(course_id: 15).includes(:course_series).(:course_languages).user_tutorials.where(/* condition for user_tutorials */).submissions.where(/* condition for submissions */)


问:
Bouncy Castle PGP sign and encrypt in one pass?
I'm looking for an implementation of Bouncy Castle PGP 'sign and encrypt'. Ideally in one operation, if that makes any difference.

I've taken the encrypt example and the signing example and tried to turn it into a 'one pass' encrypt and sign operation.

I see this relatively dated implementation Boncode. It seems to show that the two operations are just linked together.

I'm not getting the consumer to decrypt the code. The signature seems to be able to be verified. This is true whether I use the merged operations or separate encrypt then sign.

Is there a better Bouncy Castle PGP implementation?

答:
Here is my current implementation of a one pass, Bouncy Castle PGP encrypt+sign. The signature seems to verify, but the payload is not decrypted.</p>

```<code>public class SinglePassSignedEncryptedFileProcessor {
private static final Logger logger = LoggerFactory.getLogger(SinglePassSignedEncryptedFileProcessor.class);

/*
 * This is the primary function that will create encrypt a file and sign it
 * with a one pass signature. This leans on an C# example by John Opincar
 * @author Bilal Soylu
 * @param targetFileName
 *            -- file name on drive systems that will contain encrypted content
 * @param embeddedFileName
 *            -- the original file name before encryption
 * @param secretKeyRingInputStream
 *            -- Private Key Ring File
 * @param targetFileStream
 *            -- The stream for the encrypted target file
 * @param secretKeyPassphrase
 *            -- The private key password for the key retrieved from
 *            collection used for signing
 * @param signPublicKeyInputStream
 *            -- the public key of the target recipient to be used to
 *            encrypt the file
 * @throws Exception
 */
public void encryptOnePassSign(
        String fileName,
        InputStream keyIn,
        OutputStream out,
        char[] pass,
        PGPPublicKey encryptionKey,
        boolean armor,
        boolean withIntegrityCheck,
        String providerName)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, PGPException, SignatureException {
    if (armor) {
        out = new ArmoredOutputStream(out);
    }

    // Compress
    byte[] bytes = PGPEncryptUtil.compressFile(fileName, CompressionAlgorithmTags.ZIP);

    // Encryption process.
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC"));

    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encryptionKey).setProvider("BC"));

    ByteArrayOutputStream encryptedOutputStream = new ByteArrayOutputStream();
    OutputStream encryptedOut = encGen.open(encryptedOutputStream, bytes);
    encryptedOut.write(bytes);
    encryptedOut.close();
    byte[] bytesEncrypted = encryptedOutputStream.toByteArray();
    encryptedOutputStream.close();

    // Signing process.
    PGPSecretKey pgpSec = PGPEncryptUtil.readSecretKey(keyIn);
    PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));

    PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), PGPUtil.SHA1).setProvider("BC"));

    sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

    Iterator it = pgpSec.getPublicKey().getUserIDs();
    if (it.hasNext()) {
        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

        spGen.setSignerUserID(false, (String) it.next());
        sGen.setHashedSubpackets(spGen.generate());
    }

    PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(
            PGPCompressedData.UNCOMPRESSED);

    // Write to the output stream.
    BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out));
    sGen.generateOnePassVersion(false).encode(bOut);

    File file = new File(fileName);
    PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
    // file is encoding name.
    Date lastModified = new Date(file.lastModified());
    OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, fileName, lastModified, bytesEncrypted);

    //FileInputStream fIn = new FileInputStream(file);
    //int ch;

    //while ((ch = fIn.read()) >= 0) {
        lOut.write(bytesEncrypted);
        sGen.update(bytesEncrypted);
   // }

    // ?
    lGen.close();

    sGen.generate().encode(bOut);
    cGen.close();

    if (armor) {
        out.close();
    }
    // close everything down we are done
    /*
    literalOut.close();
    literalDataGenerator.close();
    signatureGenerator.generate().encode(compressedOut);
    compressedOut.close();
    compressedDataGenerator.close();
    encryptedOut.close();
    encryptedDataGenerator.close();
     */

    // if (armor) targetFileStream.close();

}
}
</code>```

Body:
Here is my current implementation of a one pass, Bouncy Castle PGP encrypt+sign. The signature seems to verify, but the payload is not decrypted.

public class SinglePassSignedEncryptedFileProcessor {
private static final Logger logger = LoggerFactory.getLogger(SinglePassSignedEncryptedFileProcessor.class);

/*
 * This is the primary function that will create encrypt a file and sign it
 * with a one pass signature. This leans on an C# example by John Opincar
 * @author Bilal Soylu
 * @param targetFileName
 *            -- file name on drive systems that will contain encrypted content
 * @param embeddedFileName
 *            -- the original file name before encryption
 * @param secretKeyRingInputStream
 *            -- Private Key Ring File
 * @param targetFileStream
 *            -- The stream for the encrypted target file
 * @param secretKeyPassphrase
 *            -- The private key password for the key retrieved from
 *            collection used for signing
 * @param signPublicKeyInputStream
 *            -- the public key of the target recipient to be used to
 *            encrypt the file
 * @throws Exception
 */
public void encryptOnePassSign(
        String fileName,
        InputStream keyIn,
        OutputStream out,
        char[] pass,
        PGPPublicKey encryptionKey,
        boolean armor,
        boolean withIntegrityCheck,
        String providerName)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, PGPException, SignatureException {
    if (armor) {
        out = new ArmoredOutputStream(out);
    }

    // Compress
    byte[] bytes = PGPEncryptUtil.compressFile(fileName, CompressionAlgorithmTags.ZIP);

    // Encryption process.
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC"));

    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encryptionKey).setProvider("BC"));

    ByteArrayOutputStream encryptedOutputStream = new ByteArrayOutputStream();
    OutputStream encryptedOut = encGen.open(encryptedOutputStream, bytes);
    encryptedOut.write(bytes);
    encryptedOut.close();
    byte[] bytesEncrypted = encryptedOutputStream.toByteArray();
    encryptedOutputStream.close();

    // Signing process.
    PGPSecretKey pgpSec = PGPEncryptUtil.readSecretKey(keyIn);
    PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));

    PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), PGPUtil.SHA1).setProvider("BC"));

    sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

    Iterator it = pgpSec.getPublicKey().getUserIDs();
    if (it.hasNext()) {
        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

        spGen.setSignerUserID(false, (String) it.next());
        sGen.setHashedSubpackets(spGen.generate());
    }

    PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(
            PGPCompressedData.UNCOMPRESSED);

    // Write to the output stream.
    BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out));
    sGen.generateOnePassVersion(false).encode(bOut);

    File file = new File(fileName);
    PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
    // file is encoding name.
    Date lastModified = new Date(file.lastModified());
    OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, fileName, lastModified, bytesEncrypted);

    //FileInputStream fIn = new FileInputStream(file);
    //int ch;

    //while ((ch = fIn.read()) >= 0) {
        lOut.write(bytesEncrypted);
        sGen.update(bytesEncrypted);
   // }

    // ?
    lGen.close();

    sGen.generate().encode(bOut);
    cGen.close();

    if (armor) {
        out.close();
    }
    // close everything down we are done
    /*
    literalOut.close();
    literalDataGenerator.close();
    signatureGenerator.generate().encode(compressedOut);
    compressedOut.close();
    compressedDataGenerator.close();
    encryptedOut.close();
    encryptedDataGenerator.close();
     */

    // if (armor) targetFileStream.close();

}
}


答:
By using left:0; right:0; and appropirate margin value, you should be able to center it. You could also set the width of the #header-content and set margin:0 auto;, it would achieve the same effect.
I also fit the image inside parent and added a curve to the label, you can see everything commented in css.

Working snippet:

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}
#header img {width:100%; /* sets image to fit parent */}

#header-content {
  position: absolute;
  bottom: 0;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
  right:0; left:0; /*center*/
  margin:0 18px 24px 18px; /* set margin to appropriate values top right bottom left*/
  border-bottom-left-radius:13px; border-bottom-right-radius:13px; /* curved edges */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div></code>```

Title: How center the text between the limits of the picture

Body:
By using left:0; right:0; and appropirate margin value, you should be able to center it. You could also set the width of the #header-content and set margin:0 auto;, it would achieve the same effect.
I also fit the image inside parent and added a curve to the label, you can see everything commented in css.

Working snippet:

.elixir {
  position: absolute;
  top: 5px;
  left: 15px;
  color: white;
  font-weight: bold;
  font-size: 50px;
}

.level {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  text-align: center;
}

#header {
  position: relative;
  background: yellow;
  width: 200px;
}
#header img {width:100%; /* sets image to fit parent */}

#header-content {
  position: absolute;
  bottom: 0;
  color: Violet  ;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  /* fallback color */
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  /* width: 100%; */
  line-height: 40px;
  right:0; left:0; /*center*/
  margin:0 18px 24px 18px; /* set margin to appropriate values top right bottom left*/
  border-bottom-left-radius:13px; border-bottom-right-radius:13px; /* curved edges */
}

<div id="header">
  <img src="https://vignette.wikia.nocookie.net/clashroyale/images/4/46/DarkPrinceCard.png/revision/latest?cb=20160702201038" />
  <span class="elixir"> 4 </span>
  <span id="header-content"> Level 2 </span>
</div>


问:
Steps to construct WPF Ribbon based applications
Where can I find tutorials or steps to develop WPF Ribbon based applications? The Microsoft page, Microsoft Ribbon for WPF October 2010 doesn't provide any documents for the code samples. For example it has one code sample called RibbonWindowWord.xaml :

```<code><ribbon:RibbonWindow x:Class="RibbonWindowSample.RibbonWindowWord"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ribbon="http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon"
    xmlns:local="clr-namespace:RibbonWindowSample"
    Title="RibbonWindowWord" Height="600" Width="1000"
    Closing="RibbonWindow_Closing">
    <local:UserControlWord x:Name="WordControl" />
</ribbon:RibbonWindow>
</code>```

what is the programming methodology here?
The channel9 pages which shows tutorials on  Ribbon based interfaces are all for c++ programmers. I'm looking code for C# programmers. Can someone specify resources and tell the differences between the previous WPF codeplex release : http://wpf.codeplex.com/wikipage?title=Southridge%20Lab

channel9 pages
http://channel9.msdn.com/blogs/yochay/a-lap-around-windows-7-new-scenic-ribbon
http://channel9.msdn.com/Blogs/yochay/Windows-7-Ribbon-Markup-Overview

答:
The source code and 2 examples are on  this page just download and install 'Microsoft Ribbon for WPF Source and Samples.msi'. Example just looks like one project but actually contains 2 of them to choose which one you want to run go to App.xaml and uncomment line

```<code><Application x:Class="RibbonWindowSample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="RibbonWindowWord.xaml">
<!--StartupUri="RibbonWindowMvvm.xaml">-->
    <Application.Resources>

     </Application.Resources>
</Application>
</code>```

First example is showing how to create all controls in xaml and they are located in RibbonWindowWord.xaml second one is showing mvvm for ribbon RibbonWindowMvvm.xaml.

There are few differences between codeplex version and preview the most important for me is that they switch style to 2010 version and it requires some time to change all the colors.

I found only one Ribbon Feature Walkthrough this is for codeplex version but they are very similar and only Themes & Skins section is not adequate. If you need any other specific help just let me know (I've created different color Theme for ribbon in my project and I've used all the features e.g. contextual tabs). I've noticed this new version is not integrating with chrome library for WPF on Xp.

Body:
Where can I find tutorials or steps to develop WPF Ribbon based applications? The Microsoft page, Microsoft Ribbon for WPF October 2010 doesn't provide any documents for the code samples. For example it has one code sample called RibbonWindowWord.xaml :

<ribbon:RibbonWindow x:Class="RibbonWindowSample.RibbonWindowWord"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ribbon="http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon"
    xmlns:local="clr-namespace:RibbonWindowSample"
    Title="RibbonWindowWord" Height="600" Width="1000"
    Closing="RibbonWindow_Closing">
    <local:UserControlWord x:Name="WordControl" />
</ribbon:RibbonWindow>

what is the programming methodology here?
The channel9 pages which shows tutorials on  Ribbon based interfaces are all for c++ programmers. I'm looking code for C# programmers. Can someone specify resources and tell the differences between the previous WPF codeplex release : http://wpf.codeplex.com/wikipage?title=Southridge%20Lab

channel9 pages
http://channel9.msdn.com/blogs/yochay/a-lap-around-windows-7-new-scenic-ribbon
http://channel9.msdn.com/Blogs/yochay/Windows-7-Ribbon-Markup-Overview

Body:
The source code and 2 examples are on  this page just download and install 'Microsoft Ribbon for WPF Source and Samples.msi'. Example just looks like one project but actually contains 2 of them to choose which one you want to run go to App.xaml and uncomment line

<Application x:Class="RibbonWindowSample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="RibbonWindowWord.xaml">
<!--StartupUri="RibbonWindowMvvm.xaml">-->
    <Application.Resources>

     </Application.Resources>
</Application>

First example is showing how to create all controls in xaml and they are located in RibbonWindowWord.xaml second one is showing mvvm for ribbon RibbonWindowMvvm.xaml.

There are few differences between codeplex version and preview the most important for me is that they switch style to 2010 version and it requires some time to change all the colors.

I found only one Ribbon Feature Walkthrough this is for codeplex version but they are very similar and only Themes & Skins section is not adequate. If you need any other specific help just let me know (I've created different color Theme for ribbon in my project and I've used all the features e.g. contextual tabs). I've noticed this new version is not integrating with chrome library for WPF on Xp.


问:
Angular 5 (mousenter) not working
i updated my full project to angular 5, two weeks ago and i've notice the event (mouseenter) (mouseleave) are not working anymore on a component of mine.
This was perfectly working before.
Is this deprecated or something or do i miss an import ??

(click) works... the html template of the comp

```<code><i *ngFor="let step of steps"
    #ratingPicker
    [ngClass]="{
        'fa-star': !step.half && step.selected,
        'fa-star-o': !step.half && !step.selected,
        'fa-star-half-o': step.half,
        'pre-selected': step.pre_selected,
        'selected': step.selected,
        'fa-lg': (size == 1),
        'fa-2x': (size == 2),
        'fa-3x': (size == 3)
        }"
    (mouseenter)="onMouseEnter(step, $event)"
    (mouseleave)="onMouseLeave(step, $event)"
    (mousemove)="onMouseMove(step, $event, ratingPicker.getBoundingClientRect().width)"
    (click)="setRating(step.index)"
    class="feedbacks-element fa" aria-hidden="true">
</code>```

the component

```<code>import {Component, OnInit, Input, Output, EventEmitter, AfterViewInit} from '@angular/core';

@Component({
  selector: 'rating-picker',
  templateUrl: './rating-picker.html',
  styleUrls: ['./rating-picker.css']
})
export class RatingPickerComponent implements OnInit, AfterViewInit {
</code>```

答:
Your issue may be rooted in a compatibility problem with Safari. Solution comes from this answer: Default Angular-CLI Project Fails in Safari - culprit strict mode?</p>

```<code>npm install webpack-dev-server@2.7.1 --dev
cp -R ./node_modules/webpack-dev-server ./node_modules/@angular/cli/node_modules/
ng serve
</code>```

Title: Angular 5 (mousenter) not working

Body:
i updated my full project to angular 5, two weeks ago and i've notice the event (mouseenter) (mouseleave) are not working anymore on a component of mine.
This was perfectly working before.
Is this deprecated or something or do i miss an import ??

(click) works... the html template of the comp

<i *ngFor="let step of steps"
    #ratingPicker
    [ngClass]="{
        'fa-star': !step.half && step.selected,
        'fa-star-o': !step.half && !step.selected,
        'fa-star-half-o': step.half,
        'pre-selected': step.pre_selected,
        'selected': step.selected,
        'fa-lg': (size == 1),
        'fa-2x': (size == 2),
        'fa-3x': (size == 3)
        }"
    (mouseenter)="onMouseEnter(step, $event)"
    (mouseleave)="onMouseLeave(step, $event)"
    (mousemove)="onMouseMove(step, $event, ratingPicker.getBoundingClientRect().width)"
    (click)="setRating(step.index)"
    class="feedbacks-element fa" aria-hidden="true">

the component

import {Component, OnInit, Input, Output, EventEmitter, AfterViewInit} from '@angular/core';

@Component({
  selector: 'rating-picker',
  templateUrl: './rating-picker.html',
  styleUrls: ['./rating-picker.css']
})
export class RatingPickerComponent implements OnInit, AfterViewInit {

Body:
Your issue may be rooted in a compatibility problem with Safari. Solution comes from this answer: Default Angular-CLI Project Fails in Safari - culprit strict mode?

npm install webpack-dev-server@2.7.1 --dev
cp -R ./node_modules/webpack-dev-server ./node_modules/@angular/cli/node_modules/
ng serve


问:
angularjs ui-select basic validation
I have a basic ui-select drop down with predefined items. I am also able to enter in text and add it to the list. What i need to be able to do is two things.

Allowed characters - a-z, A-Z

Maximum characters allowed is 50

I would like to restrict them as they are typing. So, if there trying to search using a number it just doesnt work or past 50 characters it stops typing.

I found this example, How to set a max length for the search input in (AngularJS) ui-select component? but it doesnt work for me. I set it to 5 length to test.
Im also, unsure how to restrict to only a-z characters.

Here is my HTML - this little bit is in a html table using ng-repeat

```<code><div class="row">
     <div class="form-group">
      <div style="width:300px; margin-left:4px;" class="col-sm-6">
       <ui-select maxlen="5" ng-model="vehicle.linkNote" id="note-{{$index}}" on-select="selectNote(vehicle, $select.selected)">
        <ui-select-match  class="select" placeholder="Select or search a note in the list...">{{$select.selected }}</ui-select-match>
         <ui-select-choices  class="select" id="note-{{$index}}" repeat="note in getNotes($select.search) | filter: $select.search | orderBy:$select.search">
         <div class="select" for="note-{{$index}}" ng-bind="note"></div>
           </ui-select-choices>
             </ui-select>
            </div>
           </div>
          </div>
</code>```

Here is part of my controller

```<code>    $scope.selectNote = function(vehicle, selectedNote) {
    vehicle.linkNote = selectedNote;
    $scope.linkNotes.unshift(selectedNote);
    $scope.submitMapping(vehicle);
};

$scope.options = function (vehicle, optionAdjustment) {
        vehicle.optionAdjustment = optionAdjustment;
        $scope.submitMapping(vehicle);
};

app.directive('maxlen', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            var $uiSelect = angular.element(element[0].querySelector('.ui-select-search'));
            $uiSelect.attr("maxlength", attr.maxlen);
        }
    }
});

$scope.$watch('note.selected', function(newVal, oldVal) {
    if (newVal !== oldVal) {
        if ($scope.linkNotes.indexOf(newVal) === -1) {
            $scope.linkNotes.unshift(newVal);
        }
    }
});

$scope.getNotes = function(search) {
    var newNotes = $scope.linkNotes.slice();

    if (search && newNotes.indexOf(search) === -1) {
        newNotes.unshift(search);

    }
    return newNotes;
};

$scope.linkNotes = [
    'Cannot link half years',
    'Conflicting data provided by vendor',
    'Duplicate',
    'Incomplete data provided by vendor',
    'No ASC Code',
    'No data provided by vendor'
].sort();
</code>```

答:
Probably not what you're looking for but all the functionality you describe above exists natively in HTML5.

pattern="[a-zA-Z]+" will allow one or more characters: a-z, A-Z

maxlength="50" will limit maximum characters to 50

Working Example:

<input list="fruit" maxlength="50" pattern="[A-Za-z]+" placeholder="What fruit?" />

<datalist id="fruit">
<option value="Apple">
<option value="Apricot">
<option value="Avocado">
<option value="Banana">
<option value="Cherry">
<option value="Pear">
<option value="Peach">
<option value="Pineapple">
</datalist>```

Title: angularjs ui-select basic validation

Body:
I have a basic ui-select drop down with predefined items. I am also able to enter in text and add it to the list. What i need to be able to do is two things.

Allowed characters - a-z, A-Z

Maximum characters allowed is 50

I would like to restrict them as they are typing. So, if there trying to search using a number it just doesnt work or past 50 characters it stops typing.

I found this example, How to set a max length for the search input in (AngularJS) ui-select component? but it doesnt work for me. I set it to 5 length to test.
Im also, unsure how to restrict to only a-z characters.

Here is my HTML - this little bit is in a html table using ng-repeat

       <ui-select maxlen="5" ng-model="vehicle.linkNote" id="note-{{$index}}" on-select="selectNote(vehicle, $select.selected)">
        <ui-select-match  class="select" placeholder="Select or search a note in the list...">{{$select.selected }}</ui-select-match>
         <ui-select-choices  class="select" id="note-{{$index}}" repeat="note in getNotes($select.search) | filter: $select.search | orderBy:$select.search">

           </ui-select-choices>
             </ui-select>

Here is part of my controller

    $scope.selectNote = function(vehicle, selectedNote) {
    vehicle.linkNote = selectedNote;
    $scope.linkNotes.unshift(selectedNote);
    $scope.submitMapping(vehicle);
};

$scope.options = function (vehicle, optionAdjustment) {
        vehicle.optionAdjustment = optionAdjustment;
        $scope.submitMapping(vehicle);
};

app.directive('maxlen', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            var $uiSelect = angular.element(element[0].querySelector('.ui-select-search'));
            $uiSelect.attr("maxlength", attr.maxlen);
        }
    }
});

$scope.$watch('note.selected', function(newVal, oldVal) {
    if (newVal !== oldVal) {
        if ($scope.linkNotes.indexOf(newVal) === -1) {
            $scope.linkNotes.unshift(newVal);
        }
    }
});

$scope.getNotes = function(search) {
    var newNotes = $scope.linkNotes.slice();

    if (search && newNotes.indexOf(search) === -1) {
        newNotes.unshift(search);

    }
    return newNotes;
};

$scope.linkNotes = [
    'Cannot link half years',
    'Conflicting data provided by vendor',
    'Duplicate',
    'Incomplete data provided by vendor',
    'No ASC Code',
    'No data provided by vendor'
].sort();


问:
How to restrict certain users from editing all attributes of an object using PUT with Spring Data Rest?
When using Spring Data Rest is there a way to let certain users only edit part of an entity using a PUT request?

Taking this item as an example:

```<code>{
    "name": "Item1",
    "description": "Description",
    "creator": "User1"
}
</code>```

What's the best way to let the creator of the item edit the whole item using a PUT request while restricting other users to only edit the "description" field?

I have tried using a custom validator and an event handler without any luck.

答:
I think that custom Validator is right choice in your case.

First - update your entity to make it save its previous state (thanks to @AlanHay):

```<code>@Entity
class ItemEntity {

    @Transient
    private ItemEntity previousState;

    @PostLoad
    private void setPreviousState(){
        previousState = new ItemEntity();
        //copy the fields
    }

    public ItemEntity getPreviousState(){
        return previousState;
    }
}
</code>```

Then implement validator in which you check if the current user with some 'authority' has changed the fields:

```<code>public class ItemValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        //...
    }

    @Override
    public void validate(Object target, Errors errors) {

        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        SimpleGrantedAuthority userRole = new SimpleGrantedAuthority("ROLE_USER");

        if (authorities.contains(userRole)) {

            ItemEntity item = (ItemEntity) target;
            prevItem = item.getPreviousState();

            String prevName = prevItem.getName();
            String prevCreator = prevItem.getCreator();
            String newName = item.getName();
            String newCreator = item.getCreator();

            if (!prevName.equals(newName)) {
                errors.rejectValue("name", "You cannot change Name field!");
            }

            if (!prevCreator.equals(newCreator)) {
                errors.rejectValue("creator", "You cannot change Creator field!");
            }
        }
        // Other checks...
    }
}
</code>```

Then in RepositoryRestConfigurerAdapter plug this Validator:

```<code>@Configuration
public class RepoRestConfig extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
        v.addValidator("beforeCreate", itemValidator()); // POST (if needed)
        v.addValidator("beforeSave", itemValidator());   // PUT/PATCH
        super.configureValidatingRepositoryEventListener(v);
    }

    @Bean
    ListingValidator itemValidator() {
        return new ItemValidator();
    }
}
</code>```

I think this should work ...

Body:
When using Spring Data Rest is there a way to let certain users only edit part of an entity using a PUT request?

Taking this item as an example:

{
    "name": "Item1",
    "description": "Description",
    "creator": "User1"
}

What's the best way to let the creator of the item edit the whole item using a PUT request while restricting other users to only edit the "description" field?

I have tried using a custom validator and an event handler without any luck.

Body:
I think that custom Validator is right choice in your case.

First - update your entity to make it save its previous state (thanks to @AlanHay):

@Entity
class ItemEntity {

    @Transient
    private ItemEntity previousState;

    @PostLoad
    private void setPreviousState(){
        previousState = new ItemEntity();
        //copy the fields
    }

    public ItemEntity getPreviousState(){
        return previousState;
    }
}

Then implement validator in which you check if the current user with some 'authority' has changed the fields:

public class ItemValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        //...
    }

    @Override
    public void validate(Object target, Errors errors) {

        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        SimpleGrantedAuthority userRole = new SimpleGrantedAuthority("ROLE_USER");

        if (authorities.contains(userRole)) {

            ItemEntity item = (ItemEntity) target;
            prevItem = item.getPreviousState();

            String prevName = prevItem.getName();
            String prevCreator = prevItem.getCreator();
            String newName = item.getName();
            String newCreator = item.getCreator();

            if (!prevName.equals(newName)) {
                errors.rejectValue("name", "You cannot change Name field!");
            }

            if (!prevCreator.equals(newCreator)) {
                errors.rejectValue("creator", "You cannot change Creator field!");
            }
        }
        // Other checks...
    }
}

Then in RepositoryRestConfigurerAdapter plug this Validator:

@Configuration
public class RepoRestConfig extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
        v.addValidator("beforeCreate", itemValidator()); // POST (if needed)
        v.addValidator("beforeSave", itemValidator());   // PUT/PATCH
        super.configureValidatingRepositoryEventListener(v);
    }

    @Bean
    ListingValidator itemValidator() {
        return new ItemValidator();
    }
}

I think this should work ...


问:
Null propagation operator, out parameters and false compiler errors?
Let's assume I have a class that has a property of type Dictionary<string,string>, that may be null.

This compiles but the call to TryGetValue() could throw at a NullRef exception at runtime:

```<code>MyClass c = ...;
string val;
if(c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val);
}
</code>```

So I'm adding a null-propagating operator to guard against nulls, but this doesn't compile:

```<code>MyClass c = ...;
string val;
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // use of unassigned local variable

}
</code>```

Is there an actual use case where val will be uninitialized inside the if block, or can the compiler simply not infer this (and why) ?

Update: The cleanest (?) way to workaround^H^H^H^H^H fix this is:

```<code>MyClass c = ...;
string val = null; //POW! initialized.
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // no more compiler error

}
</code>```

答:
That's because if c.PossiblyNullDictionary is null, TryGetValue won't be executed and that expression won't return true or false.

c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) returns Nullable, you can replace your code with something like this and will compile:

```<code>        string val;
        var result = c.PossiblyNullDictionary?.TryGetValue("key", out val);
        if (result.HasValue && result.Value)
        {

        }
</code>```

Body:
Let's assume I have a class that has a property of type Dictionary<string,string>, that may be null.

This compiles but the call to TryGetValue() could throw at a NullRef exception at runtime:

MyClass c = ...;
string val;
if(c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val);
}

So I'm adding a null-propagating operator to guard against nulls, but this doesn't compile:

MyClass c = ...;
string val;
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // use of unassigned local variable

}

Is there an actual use case where val will be uninitialized inside the if block, or can the compiler simply not infer this (and why) ?

Update: The cleanest (?) way to workaround^H^H^H^H^H fix this is:

MyClass c = ...;
string val = null; //POW! initialized.
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // no more compiler error

}

Body:
That's because if c.PossiblyNullDictionary is null, TryGetValue won't be executed and that expression won't return true or false.

c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) returns Nullable, you can replace your code with something like this and will compile:

        string val;
        var result = c.PossiblyNullDictionary?.TryGetValue("key", out val);
        if (result.HasValue && result.Value)
        {

        }


问:
What happens when a SQL query runs out of memory?

I want to set up a Postgres server on AWS, the biggest table will be 10GB - do I have to select 10GB of memory for this instance?

What happens when my query result is larger than 10GB?

答:
On the server side, with a simple query like yours it just keeps a "cursor" which points to where it's at, as it's spooling the results to you, and uses very little memory.  Now if there were some "sorts" in there or what not, that didn't have indexes it could use, that might use up lots of memory, not sure there.  On the client side the postgres JDBC client by default loads the "entire results" into memory before passing them back to you (overcomeable by specifying a fetch count).

With more complex queries  (for example give me all 100M rows, but order them by "X" where X is not indexed) I don't know, but probably internally it creates a temp table (so it won't run out of RAM) which, treated as a normal table, uses disk backing.  If there's a matching index then it can just traverse that, using a pointer, still uses little RAM.


问:
Marketo Leads - How to find the updated values of progressionStatus field
I need to get the Marketo Leads who have changes on "progressionStatus" field (inside membership) with the API.
I can get all the leads related to a Program (with Get Leads by ProgramID API) without issues, but my need is to get those Leads with changes on "progressionStatus" column.
I was thinking to use the CreatedAt / UpdatedAt fields of the Program, so then, get all the leads related to those programs. But I didn't get the accurate results that I want.
Also, I tried to use the GET Lead changes API and use "fields" parameter to "progressionstatus" but that field don't exist.

It is possible to resolve this?
Thanks in advance.

答:
You can get the list of Leads with progression status change by querying against the Get Lead Activities endpoint.

The Get Lead Changes endpoint could sound as a good candidate, but that endpoint only returns changes on the lead fields. Progression status change is not stored on the lead directly, so at the end that won't work. On the other hand the Get Leads by ProgramId endpoint returns –amongst others– the actual value of progressionStatus (program status of the lead in the parent program) but not the “change” itself, so you cannot process the resultset based on that.

The good news is that the progression status change is an activity type and luckily we have the above mentioned Get Lead Activities endpoint (which is also mentioned as the Query in the API docs) available to query just that. This endpoint also allows for filtering by activityTypeIds to narrow down the resultset to a single activity type.

Basically you have to call the GET /rest/v1/activities.json enpoint and pass the values of activityTypeIds and nextPageToken as query parameters (next to the access token obviously). So, first you need to get the internal Id of the activity type called “Change Status in Progression”. You can do that by querying the GET /rest/v1/activities/types.json endpoint and look for a record with that name. (I don't know if this Id changes from instance to instance, but in ours it is the #104). Also, to obtain a nextPageToken you have to make a call to GET /rest/v1/activities/pagingtoken.json as well, where you have to specify the earliest datetime to retrieve activities from. See more about Paging Tokens.

Once you have all of these bits at hand, you can make your request like that:

```<code>GET https://<INSTANCE_ID>.mktorest.com/rest/v1/activities.json?activityTypeIds=<TYPE_ID>&nextPageToken=<NEXTPAGE_TOKEN>&access_token=<ACCESS_TOKEN>
</code>```

The result it gives is an array with items like below, which is easy to process further.

```<code>{
    "id":712630,
    "marketoGUID":"712630",
    "leadId":824864,
    "activityDate":"2017-12-01T08:51:13Z",
    "activityTypeId":104,
    "primaryAttributeValueId":1104,
    "primaryAttributeValue":"PROGRAM_NAME",
    "attributes":[
        {"name":"Acquired By","value":true},
        {"name":"New Status ID","value":33},
        {"name":"Old Status ID","value":32},
        {"name":"Reason","value":"Filled out form"},
        {"name":"Success","value":false},
        {"name":"New Status","value":"Filled-out Form"},
        {"name":"Old Status","value":"Not in Program"}
    ]
}
</code>```

Knowing the leadIds in question, you can make yet another request to fetch the actual lead records.

Body:
You can get the list of Leads with progression status change by querying against the Get Lead Activities endpoint.

The Get Lead Changes endpoint could sound as a good candidate, but that endpoint only returns changes on the lead fields. Progression status change is not stored on the lead directly, so at the end that won't work. On the other hand the Get Leads by ProgramId endpoint returns –amongst others– the actual value of progressionStatus (program status of the lead in the parent program) but not the “change” itself, so you cannot process the resultset based on that.

The good news is that the progression status change is an activity type and luckily we have the above mentioned Get Lead Activities endpoint (which is also mentioned as the Query in the API docs) available to query just that. This endpoint also allows for filtering by activityTypeIds to narrow down the resultset to a single activity type.

Basically you have to call the GET /rest/v1/activities.json enpoint and pass the values of activityTypeIds and nextPageToken as query parameters (next to the access token obviously). So, first you need to get the internal Id of the activity type called “Change Status in Progression”. You can do that by querying the GET /rest/v1/activities/types.json endpoint and look for a record with that name. (I don't know if this Id changes from instance to instance, but in ours it is the #104). Also, to obtain a nextPageToken you have to make a call to GET /rest/v1/activities/pagingtoken.json as well, where you have to specify the earliest datetime to retrieve activities from. See more about Paging Tokens.

Once you have all of these bits at hand, you can make your request like that:

GET https://<INSTANCE_ID>.mktorest.com/rest/v1/activities.json?activityTypeIds=<TYPE_ID>&nextPageToken=<NEXTPAGE_TOKEN>&access_token=<ACCESS_TOKEN>

The result it gives is an array with items like below, which is easy to process further.

{
    "id":712630,
    "marketoGUID":"712630",
    "leadId":824864,
    "activityDate":"2017-12-01T08:51:13Z",
    "activityTypeId":104,
    "primaryAttributeValueId":1104,
    "primaryAttributeValue":"PROGRAM_NAME",
    "attributes":[
        {"name":"Acquired By","value":true},
        {"name":"New Status ID","value":33},
        {"name":"Old Status ID","value":32},
        {"name":"Reason","value":"Filled out form"},
        {"name":"Success","value":false},
        {"name":"New Status","value":"Filled-out Form"},
        {"name":"Old Status","value":"Not in Program"}
    ]
}

Knowing the leadIds in question, you can make yet another request to fetch the actual lead records.


问:
Gitlab CI - how to build a local maven dependency before the current build?
I have the following setup:

Java Library 1

Java Library 2

Java application

The "Java application" depends on "Java Library 1" and "Java Library 2" and they are both internal.

"Java Library 1" and "Java Library 2" need to be installed on the local maven repository before "Java application" can be successfully compiled and packaged.

"Java Library 1", "Java Library 2" and "Java application" are separate projects on GitLab.

Each project has a .gitlab-ci.yml.

Each "Java Library" would have something like this:

```<code>build:
    script:
        - mvn clean install
    stage: build
    only:
        - master
    tags:
        - java
</code>```

I want to tell the .gitlab-ci.yml from the "Java application" to first build "Java Library 1" and "Java Library 2".

Is it possible?

答:
If you use Gitlab Enterprise Edition, I suggest the solution of dbrekelmans.

That said, another possibility is to setup an artifact service such as Artifactory and let maven use the repos of the service.

Use case:

Develope Libary

Push code to Gitlab

CI builds and deploy libary

Use libary with maven at the workstations and CI servers

A tutorial how this can be achieved, can be found here:
https://docs.gitlab.com/ee/articles/artifactory_and_gitlab/

Body:
I have the following setup:

Java Library 1

Java Library 2

Java application

The "Java application" depends on "Java Library 1" and "Java Library 2" and they are both internal.

"Java Library 1" and "Java Library 2" need to be installed on the local maven repository before "Java application" can be successfully compiled and packaged.

"Java Library 1", "Java Library 2" and "Java application" are separate projects on GitLab.

Each project has a .gitlab-ci.yml.

Each "Java Library" would have something like this:

build:
    script:
        - mvn clean install
    stage: build
    only:
        - master
    tags:
        - java

I want to tell the .gitlab-ci.yml from the "Java application" to first build "Java Library 1" and "Java Library 2".

Is it possible?


问:
Xamarin forms relative layout constraints top and bottom
I am new to Xamarin.Forms (Swift is my strong point). To make my App work across all screen sizes, I am using RelativeLayout. The only problem is, I can only find out how to set the width and height.

What I want to do is set the top and bottom constraints.

This is what I can do in Swift:

let redBox = UIView()
redBox.translatesAutoresizingMaskIntoConstraints = false
redBox.backgroundColor = .red

let blueBox = UIView()
blueBox.translatesAutoresizingMaskIntoConstraints = false
blueBox.backgroundColor = .blue

view.addSubview(redBox)
view.addSubview(blueBox)

redBox.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
redBox.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
redBox.heightAnchor.constraint(equalToConstant: 150).isActive = true

blueBox.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
blueBox.topAnchor.constraint(equalTo: redBox.bottomAnchor).isActive = true
blueBox.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
```

<p>This results in the following screen:</p>

<p><img src="https://i.stack.imgur.com/Rzgap.png" alt="enter image description here"></p>

<p>How would I achieve this in <code>Xamarin.Forms</code>?
I can only find out how to do width and height constraints. I also want to do it programatically instead of <code>XAML</code> or drag and drop.</p>

<p>Here is the <code>C#</code> <code>Xamarin.Forms</code> code that I have found out:</p>

<pre class="lang-cs prettyprint-override"><code>var layout = new RelativeLayout();
Content = layout;

var aquaBox = new BoxView()
{
    Color = Color.Aqua
};

var silverBox = new BoxView
{
    Color = Color.Silver
};

aquaBox.HeightRequest = 150;
layout.Children.Add(aquaBox,
    widthConstraint: Constraint.RelativeToParent(parent => parent.Width)
);

layout.Children.Add(silverBox,
    yConstraint: Constraint.RelativeToView(aquaBox, (RelativeLayout, element) => element.Height)
);
</code>```

XAML:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Test"
             x:Class="Test.TestPage">

</ContentPage>
```

The result of this code is:

What C# Xamarin.Forms code is needed to get the same view as I have with Swift?

Note: I would like Xamarin.Forms code and not separate code for Android, Windows and iOS.

答:
I'm not sure how to implement that with a RelativeLayout but it is easy with a Grid.

```<code>var aquaBox = new BoxView
{
    Color = Color.Aqua,
    HeightRequest = 150
};

var silverBox = new BoxView
{
    Color = Color.Silver
};

var grid = new Grid { RowSpacing = 0 };
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto});
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Star });

grid.Children.Add(aquaBox, 0, 0);
grid.Children.Add(silverBox, 0, 1);

Content = grid;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to Xamarin.Forms (Swift is my strong point). To make my App work across all screen sizes, I am using RelativeLayout. The only problem is, I can only find out how to set the width and height.

What I want to do is set the top and bottom constraints.

This is what I can do in Swift:

let redBox = UIView()
redBox.translatesAutoresizingMaskIntoConstraints = false
redBox.backgroundColor = .red

let blueBox = UIView()
blueBox.translatesAutoresizingMaskIntoConstraints = false
blueBox.backgroundColor = .blue

view.addSubview(redBox)
view.addSubview(blueBox)

redBox.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
redBox.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
redBox.heightAnchor.constraint(equalToConstant: 150).isActive = true

blueBox.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
blueBox.topAnchor.constraint(equalTo: redBox.bottomAnchor).isActive = true
blueBox.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

This results in the following screen:

How would I achieve this in Xamarin.Forms?
I can only find out how to do width and height constraints. I also want to do it programatically instead of XAML or drag and drop.

Here is the C# Xamarin.Forms code that I have found out:

var layout = new RelativeLayout();
Content = layout;

var aquaBox = new BoxView()
{
    Color = Color.Aqua
};

var silverBox = new BoxView
{
    Color = Color.Silver
};

aquaBox.HeightRequest = 150;
layout.Children.Add(aquaBox,
    widthConstraint: Constraint.RelativeToParent(parent => parent.Width)
);

layout.Children.Add(silverBox,
    yConstraint: Constraint.RelativeToView(aquaBox, (RelativeLayout, element) => element.Height)
);

XAML:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Test"
             x:Class="Test.TestPage">

</ContentPage>

The result of this code is:

What C# Xamarin.Forms code is needed to get the same view as I have with Swift?

Note: I would like Xamarin.Forms code and not separate code for Android, Windows and iOS.

Body:
I'm not sure how to implement that with a RelativeLayout but it is easy with a Grid.

var aquaBox = new BoxView
{
    Color = Color.Aqua,
    HeightRequest = 150
};

var silverBox = new BoxView
{
    Color = Color.Silver
};

var grid = new Grid { RowSpacing = 0 };
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto});
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Star });

grid.Children.Add(aquaBox, 0, 0);
grid.Children.Add(silverBox, 0, 1);

Content = grid;


问:
Is there anything different between R.merge vs composing with rest operator?
Is there any advantage of use R.merge over composing with the rest operator?

```<code>const a = {name: 'john', job: 'developer'};
const b = {name: 'peter', commute: 'bike', address: {city: 'San Francisco'}};
const c = {...a, ...b};
console.log('rest', c);
const d = R.merge(a, b);
console.log('R.merge', d);
</code>```

c and d appear to be the same.

Are there any cases where the rest operator won't work while R.merge will?

答:
As well as the (absolutely correct and relevant) answer from Scott Christopher, there is also another way in which the two differ.  merge is a function.  {...a, ...b} is an expression.

One of the important features of Javascript is that functions are first class citizens: you can pass them to and return them from functions.  They can be the values of variables, or properties of objects.  The same is not true of expressions.  So to have a true equivalence, it would be one between

```<code>merge
</code>```

and

```<code>(a, b) => ({...a, ...b})
</code>```

And even that does not capture the curried nature of R.merge that Scott discusses.

Of course this makes no difference for a one-off expression, but when you're passing the function around, merge might be clearer to read.

Body:
Is there any advantage of use R.merge over composing with the rest operator?

const a = {name: 'john', job: 'developer'};
const b = {name: 'peter', commute: 'bike', address: {city: 'San Francisco'}};
const c = {...a, ...b};
console.log('rest', c);
const d = R.merge(a, b);
console.log('R.merge', d);

c and d appear to be the same.

Are there any cases where the rest operator won't work while R.merge will?

Body:
As well as the (absolutely correct and relevant) answer from Scott Christopher, there is also another way in which the two differ.  merge is a function.  {...a, ...b} is an expression.

One of the important features of Javascript is that functions are first class citizens: you can pass them to and return them from functions.  They can be the values of variables, or properties of objects.  The same is not true of expressions.  So to have a true equivalence, it would be one between

merge

and

(a, b) => ({...a, ...b})

And even that does not capture the curried nature of R.merge that Scott discusses.

Of course this makes no difference for a one-off expression, but when you're passing the function around, merge might be clearer to read.


问:
Multiple Rows with Null Values Returned from CASE WHEN - Single Row?
I'm using a CASE WHEN statement to return different products' names and prices during certain periods from my dataset, but it is returning numerous rows per unique product. Is this an incorrect use of CASE WHEN, and if so, how would I fix this?

```<code>SELECT product_name,
    CASE WHEN period_fiscal_year=1 THEN product_price ELSE 0 END as Period_1,
    CASE WHEN period_fiscal_year=2 THEN product_price ELSE 0 END as Period_2,
    CASE WHEN period_fiscal_year=3 THEN product_price ELSE 0 END as Period_3
FROM product_table
</code>```

The result should ideally look like this (one example):

```<code>|product_name|Period_1|Period_2|Period_3|
|1st Product |   $25  |   $35  |   $20  |
</code>```

Currently, it looks like:

```<code>|product_name|Period_1|Period_2|Period_3|
|1st Product |   $25  |    0   |    0   |
|1st Product |    0   |   $35  |    0   |
|1st Product |    0   |    0   |   $20  |
|1st Product |    0   |    0   |    0   |
</code>```

How would I go about consolidating these rows and thus removing the 0 values? Thank you!

答:
It seems that you have more than one entry for 1st Product in the table which is why you would need to aggregate the prices for different periods at the product_name level.

```<code>SELECT product_name,
SUM(CASE WHEN period_fiscal_year=1 THEN product_price ELSE 0 END) as Period_1,
SUM(CASE WHEN period_fiscal_year=2 THEN product_price ELSE 0 END) as Period_2,
SUM(CASE WHEN period_fiscal_year=3 THEN product_price ELSE 0 END) as Period_3
FROM product_table
GROUP BY product_name;
</code>```

Body:
I'm using a CASE WHEN statement to return different products' names and prices during certain periods from my dataset, but it is returning numerous rows per unique product. Is this an incorrect use of CASE WHEN, and if so, how would I fix this?

SELECT product_name,
    CASE WHEN period_fiscal_year=1 THEN product_price ELSE 0 END as Period_1,
    CASE WHEN period_fiscal_year=2 THEN product_price ELSE 0 END as Period_2,
    CASE WHEN period_fiscal_year=3 THEN product_price ELSE 0 END as Period_3
FROM product_table

The result should ideally look like this (one example):

|product_name|Period_1|Period_2|Period_3|
|1st Product |   $25  |   $35  |   $20  |

Currently, it looks like:

|product_name|Period_1|Period_2|Period_3|
|1st Product |   $25  |    0   |    0   |
|1st Product |    0   |   $35  |    0   |
|1st Product |    0   |    0   |   $20  |
|1st Product |    0   |    0   |    0   |

How would I go about consolidating these rows and thus removing the 0 values? Thank you!

Body:
It seems that you have more than one entry for 1st Product in the table which is why you would need to aggregate the prices for different periods at the product_name level.

SELECT product_name,
SUM(CASE WHEN period_fiscal_year=1 THEN product_price ELSE 0 END) as Period_1,
SUM(CASE WHEN period_fiscal_year=2 THEN product_price ELSE 0 END) as Period_2,
SUM(CASE WHEN period_fiscal_year=3 THEN product_price ELSE 0 END) as Period_3
FROM product_table
GROUP BY product_name;


问:
Pass Rails model params to javascript onchange call?
Say I have the following rails code in a view:

```<code>    <%= form.select(:language_id,
        options_from_collection_for_select(Language.all, :id, :name),
        {},
        { :onchange => "setThemeAndMode('theme', 'mode')", class: "form-control" })
    %>
</code>```

Is it possible to send, say language.theme and language.mode to the setThemeAndMode call in the onchange event? Or even the specific language model element as some flat json?

答:
As you can see in the Rails's document, you can pass the block to select for customizing how the options tags will be rendered.

```<code>form.select :language_id do
  Language.all.each do |lang|
    content_tag(:option, c.name, value: c.id,
      onchange: "setThemeAndMode('#{get_theme_logic}', '#{get_mode_logic}')")
  end
end
</code>```

You also can define a helper for rendering the content_tag to make your code cleaner

Body:
Say I have the following rails code in a view:

    <%= form.select(:language_id,
        options_from_collection_for_select(Language.all, :id, :name),
        {},
        { :onchange => "setThemeAndMode('theme', 'mode')", class: "form-control" })
    %>

Is it possible to send, say language.theme and language.mode to the setThemeAndMode call in the onchange event? Or even the specific language model element as some flat json?

Body:
As you can see in the Rails's document, you can pass the block to select for customizing how the options tags will be rendered.

form.select :language_id do
  Language.all.each do |lang|
    content_tag(:option, c.name, value: c.id,
      onchange: "setThemeAndMode('#{get_theme_logic}', '#{get_mode_logic}')")
  end
end

You also can define a helper for rendering the content_tag to make your code cleaner


问:
How to stream Twitter API in spark Scala
How to read Twitter tweets using scala using spark streaming.
I am not able to find any spark connectors for Twitter.</p>

答:
I used spark-streaming-twitter twitter connector to read the tweets.
To install this on DSX, I used pixiedust.

spark-streaming-twitter

```<code>import pixiedust

pixiedust.installPackage("org.apache.bahir:spark-streaming-twitter_2.11:2.0.1")

import org.apache.spark.streaming.twitter._

TwitterUtils.createStream(ssc, None)
</code>```

Body:
I used spark-streaming-twitter twitter connector to read the tweets.
To install this on DSX, I used pixiedust.

spark-streaming-twitter

import pixiedust

pixiedust.installPackage("org.apache.bahir:spark-streaming-twitter_2.11:2.0.1")

import org.apache.spark.streaming.twitter._

TwitterUtils.createStream(ssc, None)


问:
Migrating a project in asp.net to drupal
I am tryin to rebuild a website designed in asp.net.But,being an informative site it has a lot of content in it which i dnt want to input to the database manually.

can ne1 help me out with any drupal module to migrate the asp.net data in sql server to mysql db in form of drupal architecture??

say for example a page in asp.net is displaying data from a form.Can i migrate it in form of cck and get the page data as nodes table.

答: This page have a comparison table of the main modules that may help you importing the data into Drupal. But keep in mind that you'll have some work to do before actually importing, since there's no magical way for Drupal to map the columns of your database to the Drupal columns.</p>


问:
Linked Lists Structures
```<code>typedef struct numbers{
int number_inserted;
struct numbers *next;
}NUMBERS;

int main(){
NUMBERS * num=NULL
int i=0;

while(i<5){
   num=add_number(num);
   i++;
}
}

NUMBERS * add_number(NUMBERS *num){

if (num== NULL) {
    num = (NUMBERS *) malloc(sizeof(NUMBERS));
    num->number_inserted=0;
    num->next = NULL;
}

int gets;
printf("Insira o numero");
scanf("%d",&gets);
num->number_inserted=gets;
num->next = ????????

return num;
}
</code>```

<p>How can I link my variable num->next for my structure NUMBERS so when it is called again I dont lose the numbers I have inserted previously. </p>

答:
For starters according to the C Standard the function main without parameters shall be declared like

```<code>int main( void )
</code>```

Also it seems you defined the function add_number inside the main (if you did not omit the closing brace for main). The C Standard does not allow to declare a function inside another function.

Usually if a singly-linked one-sided list is declared then nodes to the list are added to its beginning.

Here is a demonstrative program that shows how new nodes can be added to the beginning and the end of a singly linked list.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct numbers
{
    int number_inserted;
    struct numbers *next;
} NUMBERS;

int add_number_front( NUMBERS **numbers, int x  )
{
    NUMBERS *tmp = malloc( sizeof( NUMBERS ) );
    int success = tmp != NULL;

    if ( success )
    {
        tmp->number_inserted = x;
        tmp->next = *numbers;

        *numbers = tmp;
    }

    return success;
}

int add_number_back( NUMBERS **numbers, int x  )
{
    NUMBERS *tmp = malloc( sizeof( NUMBERS ) );
    int success = tmp != NULL;

    if ( success )
    {
        tmp->number_inserted = x;
        tmp->next = NULL;

        while ( *numbers != NULL ) numbers = &( *numbers )->next;

        *numbers = tmp;
    }

    return success;
}

void display_numbers( NUMBERS **numbers )
{
    for ( NUMBERS *current = *numbers; current != NULL; current = current->next )
    {
        printf( "%d ", current->number_inserted );
    }
}

int main(void)
{
    NUMBERS *numbers = NULL;

    for ( int i = 0; i < 5; i++ ) add_number_back( &numbers, i );

    display_numbers( &numbers );
    putchar( '\n' );

    for ( int i = 0; i < 5; i++ ) add_number_front( &numbers, i );

    display_numbers( &numbers );
    putchar( '\n' );

    return 0;
}
</code>```

Its output is

```<code>0 1 2 3 4
4 3 2 1 0 0 1 2 3 4
</code>```

Title: Linked Lists Structures

Body:
typedef struct numbers{
int number_inserted;
struct numbers *next;
}NUMBERS;

int main(){
NUMBERS * num=NULL
int i=0;

while(i<5){
   num=add_number(num);
   i++;
}
}

NUMBERS * add_number(NUMBERS *num){

if (num== NULL) {
    num = (NUMBERS *) malloc(sizeof(NUMBERS));
    num->number_inserted=0;
    num->next = NULL;
}

int gets;
printf("Insira o numero");
scanf("%d",&gets);
num->number_inserted=gets;
num->next = ????????

return num;
}

How can I link my variable num->next for my structure NUMBERS so when it is called again I dont lose the numbers I have inserted previously.

Body:
For starters according to the C Standard the function main without parameters shall be declared like

int main( void )

Also it seems you defined the function add_number inside the main (if you did not omit the closing brace for main). The C Standard does not allow to declare a function inside another function.

Usually if a singly-linked one-sided list is declared then nodes to the list are added to its beginning.

Here is a demonstrative program that shows how new nodes can be added to the beginning and the end of a singly linked list.

#include <stdio.h>
#include <stdlib.h>

typedef struct numbers
{
    int number_inserted;
    struct numbers *next;
} NUMBERS;

int add_number_front( NUMBERS **numbers, int x  )
{
    NUMBERS *tmp = malloc( sizeof( NUMBERS ) );
    int success = tmp != NULL;

    if ( success )
    {
        tmp->number_inserted = x;
        tmp->next = *numbers;

        *numbers = tmp;
    }

    return success;
}

int add_number_back( NUMBERS **numbers, int x  )
{
    NUMBERS *tmp = malloc( sizeof( NUMBERS ) );
    int success = tmp != NULL;

    if ( success )
    {
        tmp->number_inserted = x;
        tmp->next = NULL;

        while ( *numbers != NULL ) numbers = &( *numbers )->next;

        *numbers = tmp;
    }

    return success;
}

void display_numbers( NUMBERS **numbers )
{
    for ( NUMBERS *current = *numbers; current != NULL; current = current->next )
    {
        printf( "%d ", current->number_inserted );
    }
}

int main(void)
{
    NUMBERS *numbers = NULL;

    for ( int i = 0; i < 5; i++ ) add_number_back( &numbers, i );

    display_numbers( &numbers );
    putchar( '\n' );

    for ( int i = 0; i < 5; i++ ) add_number_front( &numbers, i );

    display_numbers( &numbers );
    putchar( '\n' );

    return 0;
}

Its output is

0 1 2 3 4
4 3 2 1 0 0 1 2 3 4


问:
Python split string at comma, ignore comma in numbers
If I'm given the string

```<code>"Today, I picked, a total, of, 1,000,000, apples"
</code>```

I want

```<code>[Today, I picked, a total, of, 1,000,000, apples]
</code>```

I tried using string.split(","), but that doesn't account for commas in numbers... Could you help me for this particular case? Thank you

Edit
I previously asked this question for javascript, can anyone provide any insights for python?

答:
You can be more specific by using a regular expression to ignore commas when next to numeric values.

var s = "Today, I picked, a total, of, 1,000,000, apples";

var a = s.split(/(?!\d)\,(?!\d)/);

console.log(a);```

Body:
If I'm given the string

"Today, I picked, a total, of, 1,000,000, apples"

I want

[Today, I picked, a total, of, 1,000,000, apples]

I tried using string.split(","), but that doesn't account for commas in numbers... Could you help me for this particular case? Thank you

Edit
I previously asked this question for javascript, can anyone provide any insights for python?


问:
Android Studio 3.0 - "Failed to transform file 'gson-2.2.4.jar' to match attributes {artifactType=android-classes}"
I'm a newcomer to Android Studio development, and I'm currently following an online tutorial to make a messenger app.

I've followed the steps of this tutorial, and it now needs me to download the Library files for Smack API & GSON, and add the .jar files to the libs folder in my project.

With this done, I right-clicked the files in the directory and clicked Add as library (the tutorial says to do Build Path -> Add to Build Path, but this doesn't seem to be an option in this version of Android Studio).

At this point, the project directory menu sidebar looks like this:

From here, I tried to rebuild the project but was met with the following error:

I've not been able to find a way around this error at all, and don't know enough about Android Studio to know if this is an issue with the IDE or the package itself. I've had a look around S/O but none of the posts seem to describe the same issue, or offer any solutions to similar issues that appear to work for this too.

If anyone has run into this before, or if it is a common Android Studio problem, would you be able to advise me on how to resolve it please? Very frustrating when I just want to get on with learning how to code for Android!

Any help massively appreciated, thanks in advance!

Mark

答:
Since Gson is in maven central, you have to add mavenCentral() in buildscripts phase. you have to add the Gson library in the dependency using project structure, now to update the gradle, for the add the .jar file to your build.gradle file like:

```<code>dependencies {
    compile files('libs/gson-2.2.4.jar')
}
</code>```

or

```<code>dependencies {
    compile 'com.google.code.gson:gson:2.2.+'
}
</code>```

And make sure you are connected to the internet

Body:
Since Gson is in maven central, you have to add mavenCentral() in buildscripts phase. you have to add the Gson library in the dependency using project structure, now to update the gradle, for the add the .jar file to your build.gradle file like:

dependencies {
    compile files('libs/gson-2.2.4.jar')
}

or

dependencies {
    compile 'com.google.code.gson:gson:2.2.+'
}

And make sure you are connected to the internet


问:
What is the easiest way to privately distribute a jar and resolve it's dependencies?
I am an Android developer and my use case is very basic. I have a java library. I want to share the jar with my teammates as a re-usable piece of functionality.

So far I have tried,

Building a .jar from ./gradlew jar by following this guide. But when I include the same jar in Android Studio the jar's dependencies are not resolved.

I can't publish it on bintray or maven central. So I used maven-publish gradle plugin to publishToLocal by following these steps. This didn't help either. In fact, this didn't publish anything at all.

I used gradle shadow jar plugin. It made the jar "fat" i.e. increase the size from 25KB to 3MB.

All I want is to share a jar within my team. And also the transitive dependencies to be resolved.

Can anyone help?

答: You can use Jitpack or create a new module .aar</p>


问:
Running out of sockets when re-using a single HttpClient amongst multiple threads - 1000's of TIMED_WAIT connections remain
Environment: Windows Server 2012 R2 64-bit.
C# .NET Framework version 4.5.1.

I am trying to use this program to download a bunch of files from a SharePoint 2013 site: https://github.com/nddipiazza/Sharepoint-Exporter

In this project there is a [FileDownloader.cs][1] file that pulls requests to download files from a BlockingCollection and downloads them to file.

When I run this I pretty quickly get hit with socket errors:

```<code>System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted 10.5.50.2:443
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at SpPrefetchIndexBuilder.FileDownloader.attemptToDownload(FileToDownload toDownload, Int32 numRetry)
---> (Inner Exception #0) System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted 10.5.50.2:443
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---<---
</code>```

Basically it seems like I am hitting this code too hard:

```<code>public void AttemptToDownload(FileToDownload toDownload, int numRetry)
{
    try
    {
        var responseResult = client.GetAsync(SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl);
        if (responseResult.Result != null && responseResult.Result.StatusCode == System.Net.HttpStatusCode.OK)
        {
            using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().GetAwaiter().GetResult())
            {
                using (var fileStream = File.Create(toDownload.saveToPath))
                {
                    memStream.CopyTo(fileStream);
                }
            }
            Console.WriteLine("Thread {0} - Successfully downloaded {1} to {2}", Thread.CurrentThread.ManagedThreadId, toDownload.serverRelativeUrl, toDownload.saveToPath);
        }
        else
        {
            Console.WriteLine("Got non-OK status {0} when trying to download url {1}", responseResult.Result.StatusCode, SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl);
        }
    }
    catch (Exception e)
    {
        if (numRetry >= NUM_RETRIES)
        {
            Console.WriteLine("Gave up trying to download url {0} to file {1} after {2} retries due to error: {3}", SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl, toDownload.saveToPath, NUM_RETRIES, e);
        }
        else
        {
            AttemptToDownload(toDownload, numRetry + 1);
        }
    }
}
</code>```

Is there something wrong with how I'm using HttpClient? I read all the forums and it says to re-use a static reference, and I am doing that. All of my threads share the same static HttpClient reference.

Here is a netstat -a -o -n from when the downloads have been running for a few minutes. There are a lot of TIMED_WAIT sitting there. https://pastebin.com/GTYmqwue In this test i was using SharePoint on port 80. Why is that?

When I run it again a couple minutes later, the number of TIMED_WAIT have increased hundreds more. There must be a leak of some sort going on?

Why is HttpClient leaving 1000's of TIMED_WAIT connections sitting there? How can I get them to close?

I tried to set ServiePointManager.DefaultConnectionLimit = numThreads but it still grows to 1000's of connections.

答:
I think I figured it out finally

I accidentally had a really aggressive client.Timeout = TimeSpan.FromMinutes(5);

I changed this to client.Timeout = TimeSpan.FromSeconds(15);

Now I think the connections aren't leaking anymore.

Body:
Environment: Windows Server 2012 R2 64-bit.
C# .NET Framework version 4.5.1.

I am trying to use this program to download a bunch of files from a SharePoint 2013 site: https://github.com/nddipiazza/Sharepoint-Exporter

In this project there is a [FileDownloader.cs][1] file that pulls requests to download files from a BlockingCollection and downloads them to file.

When I run this I pretty quickly get hit with socket errors:

System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted 10.5.50.2:443
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at SpPrefetchIndexBuilder.FileDownloader.attemptToDownload(FileToDownload toDownload, Int32 numRetry)
---> (Inner Exception #0) System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted 10.5.50.2:443
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---<---

Basically it seems like I am hitting this code too hard:

public void AttemptToDownload(FileToDownload toDownload, int numRetry)
{
    try
    {
        var responseResult = client.GetAsync(SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl);
        if (responseResult.Result != null && responseResult.Result.StatusCode == System.Net.HttpStatusCode.OK)
        {
            using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().GetAwaiter().GetResult())
            {
                using (var fileStream = File.Create(toDownload.saveToPath))
                {
                    memStream.CopyTo(fileStream);
                }
            }
            Console.WriteLine("Thread {0} - Successfully downloaded {1} to {2}", Thread.CurrentThread.ManagedThreadId, toDownload.serverRelativeUrl, toDownload.saveToPath);
        }
        else
        {
            Console.WriteLine("Got non-OK status {0} when trying to download url {1}", responseResult.Result.StatusCode, SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl);
        }
    }
    catch (Exception e)
    {
        if (numRetry >= NUM_RETRIES)
        {
            Console.WriteLine("Gave up trying to download url {0} to file {1} after {2} retries due to error: {3}", SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl, toDownload.saveToPath, NUM_RETRIES, e);
        }
        else
        {
            AttemptToDownload(toDownload, numRetry + 1);
        }
    }
}

Is there something wrong with how I'm using HttpClient? I read all the forums and it says to re-use a static reference, and I am doing that. All of my threads share the same static HttpClient reference.

Here is a netstat -a -o -n from when the downloads have been running for a few minutes. There are a lot of TIMED_WAIT sitting there. https://pastebin.com/GTYmqwue In this test i was using SharePoint on port 80. Why is that?

When I run it again a couple minutes later, the number of TIMED_WAIT have increased hundreds more. There must be a leak of some sort going on?

Why is HttpClient leaving 1000's of TIMED_WAIT connections sitting there? How can I get them to close?

I tried to set ServiePointManager.DefaultConnectionLimit = numThreads but it still grows to 1000's of connections.