问:
How to style a specific word in textarea
I have something like this in my code (I can't put too much code in StackOverFlow):

```<code> <textarea id="text" style="width:500px;height:500px;">
    Have I Cherry
    Have I Banana
    Have I Apple
    Have I Banana
    Have I Strawberry
    </textarea>
</code>```

On my script I fixed the orders already so it turns in to this.

```<code> <textarea id="result" style="width:500px;height:500px;">
I Have Cherry
I Have Banana
I Have Apple
I Have Banana
I Have Strawberry
</textarea>
</code>```

What I want is if the word is Banana, style= yellow, else style = red. This is what I tried

```<code>lines = text.value.split('\n');
result.value = '';
for(var i = 0;i < lines.length;i++){
    var line = lines[i];
    var word = line.split(' ');
     var check = line.match(/Banana/);
     if(check) {
    result.value += word[1] + ' ' + word[0] + ' ' + word[2].style.color = "yellow";
</code>```

Result should be every Banana word is yellow and other is red. Remember not the whole sentence should be yellow, only 'Banana'. Still new to Javascript, can anyone tell me if there's anyway I can do this?

Body:
I have something like this in my code (I can't put too much code in StackOverFlow):

 <textarea id="text" style="width:500px;height:500px;">
    Have I Cherry
    Have I Banana
    Have I Apple
    Have I Banana
    Have I Strawberry
    </textarea>

On my script I fixed the orders already so it turns in to this.

 <textarea id="result" style="width:500px;height:500px;">
I Have Cherry
I Have Banana
I Have Apple
I Have Banana
I Have Strawberry
</textarea>

What I want is if the word is Banana, style= yellow, else style = red. This is what I tried

lines = text.value.split('\n');
result.value = '';
for(var i = 0;i < lines.length;i++){
    var line = lines[i];
    var word = line.split(' ');
     var check = line.match(/Banana/);
     if(check) {
    result.value += word[1] + ' ' + word[0] + ' ' + word[2].style.color = "yellow";

Result should be every Banana word is yellow and other is red. Remember not the whole sentence should be yellow, only 'Banana'. Still new to Javascript, can anyone tell me if there's anyway I can do this?

Body:
Textarea is not the best way to do what you want, try using a div with editable content, you'll have more control over the styling

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content

That way you'll be able yo wrap all bananas in a <span style="color: yellow;"></span>


来源: stackexchange

问:
Why isn't that C++ const templated vector initialised before being used?
Update: the question is why the code below (MWE) works as it is and not as I would expect it to.

For personal convenience, I created the following templated vector const:

```<code>// shorthand for loops, etc.
template <size_t N>
const vector<size_t> range = []() {
    vector<size_t> res(N);
    for (size_t i = 0; i < N; i++) res[i] = i;
    cout << "Created range<" << N << ">: [";
    for (auto x: res) cout << x << ' ';
    cout << ']' << endl;
    return res;
}();
</code>```

So that further, I can write more laconic loops like the following:

```<code>for (auto i : range<42>) do_something(i);
</code>```

However, I realised (after some debugging) that it seems to be not guaranteed that all required instantiations of range<N> are initialised before usage! This is rather counter-intuitive so I think if I am doing something wrong.

More precisely, I have the following MWE:

```<code>#include <bits/stdc++.h>
using namespace std;

template <size_t N>
const vector<size_t> range = []() {
    cout << "Initialising range<" << N << ">" << endl;
    vector<size_t> result(N);
    for (size_t i = 0; i < N; i++) result[i] = i;
    return result;
}();

template <size_t K>
class Data {
   private:
    size_t m_code;

   public:
    size_t get_code() const { return m_code; }

    constexpr static size_t cardinality = K + 1;

    explicit Data(size_t code);

    const static vector<Data> elems;
};

template <size_t K>
const vector<Data<K>> Data<K>::elems = []() {
    cout << "Creating Data elements for K=" << K << endl;
    vector<Data<K>> xs;
    for (size_t i : range<Data<K>::cardinality>) xs.push_back(Data<K>(i));
    return xs;
}();

template <size_t K>
Data<K>::Data(size_t code) {
    m_code = code;

    cout << "At the moment, range<" << K << "> is [";
    for (auto k : range<K>)
        cout << k << ' ';  // <<< Shouldn't range<K> be already initialised here?..
    cout << "] (len=" << range<K>.size() << ")" << endl;
}

int main() {
    cout << ">>> Inside main()" << endl;
    constexpr size_t K = 2;

    cout << "Data elements:" << endl;
    for (const auto &X : Data<K>::elems) {
        cout << "Element Data(" << X.get_code() << ")" << endl;
    }

    cout << "Now, range<" << K << "> is [";
    for (auto k : range<K>) cout << k << ' ';
    cout << "] (len=" << range<K>.size() << ")" << endl;
}
</code>```

This produces the following output:

```<code>Initialising range<3>
Creating Data elements for K=2
At the moment, range<2> is [] (len=0)
At the moment, range<2> is [] (len=0)
At the moment, range<2> is [] (len=0)
Initialising range<2>
>>> Inside main()
Data elements:
Element Data(0)
Element Data(1)
Element Data(2)
Now, range<2> is [0 1 ] (len=2)
</code>```

I don't really understand why it is working as it is. I mean, I would expect a const vector (or any vector!) to be initialised before it is used and thus range<2> to be of length two any time I use it in the code.

答:
The dynamic initialization of non-local static storage duration variables resulting from (non-explicit) template specializations is unordered, i.e. sequenced indeterminately, meaning that the order in which the initializations happen is unspecified. It does not take into account either dependencies between the variables, or order of definition, or order of instantiation.

Therefore your program has undefined behavior, since Data<2>::elems, instantiated from the use in main, has unordered dynamic initialization and uses range<2> and range<3>, both of which also have unordered dynamic initialization. Because it is unspecified whether the former or the latter are initialized first, it is possible that you access range<2> or range<3> before their initializations have begun, causing undefined behavior.

This can be resolved by using std::array instead of std::vector for range and in its initializer (and removing the cout statements in the initializer), so that the initializer becomes a constant expression. Then range<K> will not have dynamic initialization, but constant initialization, which is always performed before any dynamic initialization, i.e. before Data<K>::elems will use it.

In addition you should then declare range as constexpr to make sure that the initializer is indeed a constant expression. Otherwise you might still get dynamic initialization and the undefined behavior without warning, for example when you make a change that accidentally causes the initializer not to be a constant expression anymore.

ContentLicense: CC BY-SA 4.0

Body:
Update: the question is why the code below (MWE) works as it is and not as I would expect it to.

For personal convenience, I created the following templated vector const:

// shorthand for loops, etc.
template <size_t N>
const vector<size_t> range = []() {
    vector<size_t> res(N);
    for (size_t i = 0; i < N; i++) res[i] = i;
    cout << "Created range<" << N << ">: [";
    for (auto x: res) cout << x << ' ';
    cout << ']' << endl;
    return res;
}();

So that further, I can write more laconic loops like the following:

for (auto i : range<42>) do_something(i);

However, I realised (after some debugging) that it seems to be not guaranteed that all required instantiations of range<N> are initialised before usage! This is rather counter-intuitive so I think if I am doing something wrong.

More precisely, I have the following MWE:

#include <bits/stdc++.h>
using namespace std;

template <size_t N>
const vector<size_t> range = []() {
    cout << "Initialising range<" << N << ">" << endl;
    vector<size_t> result(N);
    for (size_t i = 0; i < N; i++) result[i] = i;
    return result;
}();

template <size_t K>
class Data {
   private:
    size_t m_code;

   public:
    size_t get_code() const { return m_code; }

    constexpr static size_t cardinality = K + 1;

    explicit Data(size_t code);

    const static vector<Data> elems;
};

template <size_t K>
const vector<Data<K>> Data<K>::elems = []() {
    cout << "Creating Data elements for K=" << K << endl;
    vector<Data<K>> xs;
    for (size_t i : range<Data<K>::cardinality>) xs.push_back(Data<K>(i));
    return xs;
}();

template <size_t K>
Data<K>::Data(size_t code) {
    m_code = code;

    cout << "At the moment, range<" << K << "> is [";
    for (auto k : range<K>)
        cout << k << ' ';  // <<< Shouldn't range<K> be already initialised here?..
    cout << "] (len=" << range<K>.size() << ")" << endl;
}

int main() {
    cout << ">>> Inside main()" << endl;
    constexpr size_t K = 2;

    cout << "Data elements:" << endl;
    for (const auto &X : Data<K>::elems) {
        cout << "Element Data(" << X.get_code() << ")" << endl;
    }

    cout << "Now, range<" << K << "> is [";
    for (auto k : range<K>) cout << k << ' ';
    cout << "] (len=" << range<K>.size() << ")" << endl;
}

This produces the following output:

Initialising range<3>
Creating Data elements for K=2
At the moment, range<2> is [] (len=0)
At the moment, range<2> is [] (len=0)
At the moment, range<2> is [] (len=0)
Initialising range<2>
>>> Inside main()
Data elements:
Element Data(0)
Element Data(1)
Element Data(2)
Now, range<2> is [0 1 ] (len=2)

I don't really understand why it is working as it is. I mean, I would expect a const vector (or any vector!) to be initialised before it is used and thus range<2> to be of length two any time I use it in the code.


问:
Display strokes on an InkCanvas, but do not capture events
I am developing a touch screen application and allow users to add touch-based markup to an overlay over content using an ink canvas. I have reached a point where the view behind the overlay has an element that needs the user should be allowed to interact with, but events are captured by the InkCanvas and not by the underlying control. Is there a way to display strokes, but still allow controls behind the InkCanvas to capture events?</p>

答: You can set InkCanvas.IsHitTestVisible = false and it will still display but you will not be able to interact with it and all events will go to elements lower in the z-order, which sounds like exactly what you want.

ContentLicense: CC BY-SA 3.0


问:
Passing custom List of data using Bundle
I'm developing a simple app, that contains tabview with fragment. I am stuck at the place, where i have to pass data to my newly created fragment on tabselect.

I have a List of  lists of my custom class objects:

```<code>List<List<NewsObjectClass>> myList;
</code>```

Here is where I got stuck:

```<code>public static class PlaceholderFragment extends ListFragment{

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment(){

    }

    public static PlaceholderFragment newInstance(int sectionNumber, List<List<NewsObjectsClass>> data)  {

        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);

        // Here i want to pass my List<List<NewsObjectClass>> to the bundle

        fragment.setArguments(args);
        return fragment;
    }
...
</code>```

So specifically i need a way how to pass my list of lsits of myCustomObjects to the fragment, so there I could use it for lsitview adapter.

Any syggestions on how to pass this type of data would be great.
Thanks.

答:
Or, simplest, make NewObjectClass Serializable and use putSerializable passing ArrayList because ArrayList is Serializable

Unfortunately, this did not work in my case. I ended up converting my array list to string (or JSON string) and send by

```<code>bundle.putString()
</code>```

and then, in fragment, parsed the string back to array list.

Body:
I'm developing a simple app, that contains tabview with fragment. I am stuck at the place, where i have to pass data to my newly created fragment on tabselect.

I have a List of  lists of my custom class objects:

List<List<NewsObjectClass>> myList;

Here is where I got stuck:

public static class PlaceholderFragment extends ListFragment{

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment(){

    }

    public static PlaceholderFragment newInstance(int sectionNumber, List<List<NewsObjectsClass>> data)  {

        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);

        // Here i want to pass my List<List<NewsObjectClass>> to the bundle

        fragment.setArguments(args);
        return fragment;
    }
...

So specifically i need a way how to pass my list of lsits of myCustomObjects to the fragment, so there I could use it for lsitview adapter.

Any syggestions on how to pass this type of data would be great.
Thanks.

Body:
Or, simplest, make NewObjectClass Serializable and use putSerializable passing ArrayList because ArrayList is Serializable

Unfortunately, this did not work in my case. I ended up converting my array list to string (or JSON string) and send by

bundle.putString()

and then, in fragment, parsed the string back to array list.


问:
Pytorch torch.cholesky ignoring exception
For some matrices on my batch I'm having an exception due the matrix being singular.

```<code>L = th.cholesky(Xt.bmm(X))
</code>```

cholesky_cpu: For batch 51100: U(22,22) is zero, singular U

Since they are few for my use case I would like to ignore the exception and further deal with them. I will set the resulting calculation as nan is it possible somehow?

Actually if I catch the exception and use continue still it doesn’t finish the calculation of the rest of the batch.

The same happens in C++ with Pytorch libtorch.

答:
When performing cholesky decomposition PyTorch relies on LAPACK for CPU tensors and MAGMA for CUDA tensors. In the PyTorch code used to call LAPACK the batch is just iterated over, invoking LAPACK's zpotrs_ function on each matrix separately. In the PyTorch code used to call MAGMA the entire batch is processed using MAGMA's magma_dpotrs_batched which is probably faster than iterating over each matrix separately.

AFAIK there's no way to indicate to MAGMA or LAPACK to not raise exceptions (though to be fair, I'm not an expert on these packages). Since MAGMA may be exploiting batches in some way we may not want to just default to an iterative approach, since we are potentially losing performance by not performing the batched cholesky.

One potential solution is to first try and perform batched cholesky decomposition, if it fails then we could perform cholesky decomposition on each element in the batch, setting the entries that fail to NaN.

```<code>def cholesky_no_except(x, upper=False, force_iterative=False):
    success = False
    if not force_iterative:
        try:
            results = torch.cholesky(x, upper=upper)
            success = True
        except RuntimeError:
            pass

    if not success:
        # fall back to operating on each element separately
        results_list = []
        x_batched = x.reshape(-1, x.shape[-2], x.shape[-1])
        for batch_idx in range(x_batched.shape[0]):
            try:
                result = torch.cholesky(x_batched[batch_idx, :, :], upper=upper)
            except RuntimeError:
                # may want to only accept certain RuntimeErrors add a check here if that's the case
                # on failure create a "nan" matrix
                result = float('nan') + torch.empty(x.shape[-2], x.shape[-1], device=x.device, dtype=x.dtype)
            results_list.append(result)
        results = torch.cat(results_list, dim=0).reshape(*x.shape)

    return results
</code>```

If you expect exceptions to be common during cholesky decomposition you may want use force_iterative=True to skip the initial call which tries to use the batched version, since in that case this function would likely just be wasting time with the first attempt.

Body:
For some matrices on my batch I'm having an exception due the matrix being singular.

L = th.cholesky(Xt.bmm(X))

cholesky_cpu: For batch 51100: U(22,22) is zero, singular U

Since they are few for my use case I would like to ignore the exception and further deal with them. I will set the resulting calculation as nan is it possible somehow?

Actually if I catch the exception and use continue still it doesn’t finish the calculation of the rest of the batch.

The same happens in C++ with Pytorch libtorch.

Body:
When performing cholesky decomposition PyTorch relies on LAPACK for CPU tensors and MAGMA for CUDA tensors. In the PyTorch code used to call LAPACK the batch is just iterated over, invoking LAPACK's zpotrs_ function on each matrix separately. In the PyTorch code used to call MAGMA the entire batch is processed using MAGMA's magma_dpotrs_batched which is probably faster than iterating over each matrix separately.

AFAIK there's no way to indicate to MAGMA or LAPACK to not raise exceptions (though to be fair, I'm not an expert on these packages). Since MAGMA may be exploiting batches in some way we may not want to just default to an iterative approach, since we are potentially losing performance by not performing the batched cholesky.

One potential solution is to first try and perform batched cholesky decomposition, if it fails then we could perform cholesky decomposition on each element in the batch, setting the entries that fail to NaN.

def cholesky_no_except(x, upper=False, force_iterative=False):
    success = False
    if not force_iterative:
        try:
            results = torch.cholesky(x, upper=upper)
            success = True
        except RuntimeError:
            pass

    if not success:
        # fall back to operating on each element separately
        results_list = []
        x_batched = x.reshape(-1, x.shape[-2], x.shape[-1])
        for batch_idx in range(x_batched.shape[0]):
            try:
                result = torch.cholesky(x_batched[batch_idx, :, :], upper=upper)
            except RuntimeError:
                # may want to only accept certain RuntimeErrors add a check here if that's the case
                # on failure create a "nan" matrix
                result = float('nan') + torch.empty(x.shape[-2], x.shape[-1], device=x.device, dtype=x.dtype)
            results_list.append(result)
        results = torch.cat(results_list, dim=0).reshape(*x.shape)

    return results

If you expect exceptions to be common during cholesky decomposition you may want use force_iterative=True to skip the initial call which tries to use the batched version, since in that case this function would likely just be wasting time with the first attempt.


问:
Gradle : How to translate some groovy code to kotlin
The groovy code below is working fine in a script build.gradle :

```<code>task sourcesJar(type: Jar, dependsOn: classes) {
    from sourceSets.main.allSource
    classifier = 'sources'
}

artifacts {
    archives sourcesJar
}
</code>```

I can't succeed in translating its syntax to kotlin build.gradle.kts. Could someone give me the correct translation ?

答:
If you are on Gradle 6, then this is trivial with the java plugin:

```<code>plugins {
    java
}

java {
    withSourcesJar()
}
</code>```

If you are on an older version of Gradle or unable to upgrade, then you'll need to define the task as you have above:

```<code>plugins {
    java
}

val sourcesjar by tasks.registering(Jar::class) {
    from(sourceSets[SourceSet.MAIN_SOURCE_SET_NAME].allSource)
    // Use archiveClassifier on Gradle 5.1+ otherwise use classifier
    archiveClassifier.set("sources")
}

artifacts {
    archives(sourcesjar.get())
}
</code>```

Body:
The groovy code below is working fine in a script build.gradle :

task sourcesJar(type: Jar, dependsOn: classes) {
    from sourceSets.main.allSource
    classifier = 'sources'
}

artifacts {
    archives sourcesJar
}

I can't succeed in translating its syntax to kotlin build.gradle.kts. Could someone give me the correct translation ?

Body:
If you are on Gradle 6, then this is trivial with the java plugin:

plugins {
    java
}

java {
    withSourcesJar()
}

If you are on an older version of Gradle or unable to upgrade, then you'll need to define the task as you have above:

plugins {
    java
}

val sourcesjar by tasks.registering(Jar::class) {
    from(sourceSets[SourceSet.MAIN_SOURCE_SET_NAME].allSource)
    // Use archiveClassifier on Gradle 5.1+ otherwise use classifier
    archiveClassifier.set("sources")
}

artifacts {
    archives(sourcesjar.get())
}


问:
Twitter embed - How to override CSS
I'm trying to override an embedded tweet CSS. I first tried using regular CSS but it's not understood by the tweets and doesn't seem to work : https://dev.twitter.com/web/overview/css

I'm now trying a javascript approach, but I can't manage to target the elements inside the tweet. I've been looking for answers but they are all about twitter timelines, not single embedded tweets.

I'm using https://dev.twitter.com/web/javascript/events :

```<code>twttr.ready( function(twttr){

twttr.events.bind('rendered',function (event) {

var tgt = event.target;  // Now inside each tweet
// Code to target the content in order to change its css
});
</code>```

Thank you for your help.

EDIT // Here is the working script :

```<code>twttr.ready( function(twttr){

twttr.events.bind('rendered',function (event) {

    var tgt = event.target;

    $(tgt).contents().find(".EmbeddedTweet").css({
        "border":"2px solid black",
        "border-radius":"7px",
        "max-width":"100%"
    });

  });

});
</code>```

答:
Following codes worked for me - </p>

```<code>twttr.ready(function(twttr) {
  twttr.events.bind("rendered", function(event) {
    var tgt = event.target;
    $(tgt.shadowRoot)
      .find(".EmbeddedTweet")
      .css({
        "max-width": "100%"
      });
  });
});
</code>```

Title: Twitter embed - How to override CSS

Body:
I'm trying to override an embedded tweet CSS. I first tried using regular CSS but it's not understood by the tweets and doesn't seem to work : https://dev.twitter.com/web/overview/css

I'm now trying a javascript approach, but I can't manage to target the elements inside the tweet. I've been looking for answers but they are all about twitter timelines, not single embedded tweets.

I'm using https://dev.twitter.com/web/javascript/events :

twttr.ready( function(twttr){

twttr.events.bind('rendered',function (event) {

var tgt = event.target;  // Now inside each tweet
// Code to target the content in order to change its css
});

Thank you for your help.

EDIT // Here is the working script :

twttr.ready( function(twttr){

twttr.events.bind('rendered',function (event) {

    var tgt = event.target;

    $(tgt).contents().find(".EmbeddedTweet").css({
        "border":"2px solid black",
        "border-radius":"7px",
        "max-width":"100%"
    });

  });

});

Body:
Following codes worked for me -

twttr.ready(function(twttr) {
  twttr.events.bind("rendered", function(event) {
    var tgt = event.target;
    $(tgt.shadowRoot)
      .find(".EmbeddedTweet")
      .css({
        "max-width": "100%"
      });
  });
});


问:
Invalid Resource and malformed policy errors - aws cloudformation YAML
Addig bucketpolicy for a s3 Bucket. But am running into multiple problems defining it in YAML. Here is the sample -

```<code> S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource: !Join [ '', ["arn:aws:s3:::", !Ref S3BucketTest]]
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest
</code>```

S3BucketTest is the resource name of s3 bucket I defined in the same cft

```<code>S3BucketTest:
  Type: AWS::S3::Bucket
</code>```

I was able to create s3 bucket without any issues, but the bucketpolicy giving errors.

For the above yaml, it says that resource name is invalid.

If I have multiple Actions and I mention them in [], it throws invalid Acttions and malformed policy error.

I alo want to mention multiple resources.

I am essentially looking to replicatee this in YAML -

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "stmt_cross_acct_rs_Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": ["arn:aws:iam::12345678:role/role_rs_1", "arn:aws:iam::12345678:root"]
            },
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListBucketMultipartUploads",
                "s3:ListMultipartUploadParts",
                "s3:AbortMultipartUpload",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::<demo-bucket>",
                "arn:aws:s3:::<demo-bucket>/*"
            ]
        }
    ]
}
</code>```

答:
For multiple resources, try this:

Resource:
  - 'arn:aws:s3:::<demo-bucket>'
  - 'arn:aws:s3:::<demo-bucket>'
```

Body:
Addig bucketpolicy for a s3 Bucket. But am running into multiple problems defining it in YAML. Here is the sample -

 S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource: !Join [ '', ["arn:aws:s3:::", !Ref S3BucketTest]]
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest

S3BucketTest is the resource name of s3 bucket I defined in the same cft

S3BucketTest:
  Type: AWS::S3::Bucket

I was able to create s3 bucket without any issues, but the bucketpolicy giving errors.

For the above yaml, it says that resource name is invalid.

If I have multiple Actions and I mention them in [], it throws invalid Acttions and malformed policy error.

I alo want to mention multiple resources.

I am essentially looking to replicatee this in YAML -

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "stmt_cross_acct_rs_Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": ["arn:aws:iam::12345678:role/role_rs_1", "arn:aws:iam::12345678:root"]
            },
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListBucketMultipartUploads",
                "s3:ListMultipartUploadParts",
                "s3:AbortMultipartUpload",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::<demo-bucket>",
                "arn:aws:s3:::<demo-bucket>/*"
            ]
        }
    ]
}


问:
How to check if an element exists in multiple lists in python
```<code>companies = ['apple','google','tesla','facebook','cisco']
list_1 = ['apple','google','tesla','facebook']
list_2 = ['google','tesla','facebook']
list_3 = ['apple','tesla','cisco']
list_4 = ['apple','google','tesla']
list_5 = ['google','tesla','facebook']
</code>```

And I have pandas df as follows -
COMPANY_DF

```<code>+--------+---------------------------------------+---------------+
|column1 |             column2                   |   column3     |
+------------------------------------------------+---------------|
|apple   | [list_2,list_3,list_4]                |               |
|google  | [list_1,list_2,list_3,list_5]         |               |
|tesla   | [list_1,list_2,list_3,list_4,list_5]  |               |
|facebook| [list_1,list_2,list_5]                |               |
|cisco   | [list_3]                              |               |
+------------------------------------------------+---------------+
</code>```

Problem -
For column3 I have to find other elements that exists in the lists from column2
For e.g. - for column1 row 1 apple I have to find with what other companies are there with apple in [list_2,list_3,list_4] (column2 row 1)

My approach -

for i in range(0, len(COMPANY_DF['column2'])):
    column3_list = []
    for company in companies:
        for j in range(0, len(COMPANY_DF['column2'].loc[i])):
            if company in COMPANY_DF['column2'].loc[i][j]:
                company.append(column3_list)
            else:
                print('Not there')
    COMPANY_DF['column3'].loc[i] = column3_list
```

<p>I am having issue with this if statement - </p>

<pre class="lang-rb prettyprint-override"><code>if company in COMPANY_DF['column2'].loc[i][j]:
if company in COMPANY_DF['column2'].loc[i][j] is
giving 'list_2' instead of list_2 I believe that's why it's failing.
</code>```

Any help is appreciated.

答:
This was my method:

companies = ['apple','google','tesla','facebook','cisco']
list_1 = ['apple','google','tesla','facebook']
list_2 = ['google','tesla','facebook']
list_3 = ['apple','tesla','cisco']
list_4 = ['apple','google','tesla']
list_5 = ['google','tesla','facebook']

list_of_lists = [f'list_{i}' for i in range(1, 6)]
# will create a string named the same for each of the lists,
# so it can be added to the list of mentions later, and also evaluated.

company_mentions = []
for company in companies:
    mentions = [mention for mention in list_of_lists if company in eval(mention)]
    # a list of the lists that a particular company has been mentioned in.

    company_mentions.append(mentions)
    # will append a list of the lists that company is mentioned in.
```

Hope this helps.

Edit: you can add an eval around mentions when you append it, if you'd prefer to have the entire list instead. Whatever works best for you.

Body:
companies = ['apple','google','tesla','facebook','cisco']
list_1 = ['apple','google','tesla','facebook']
list_2 = ['google','tesla','facebook']
list_3 = ['apple','tesla','cisco']
list_4 = ['apple','google','tesla']
list_5 = ['google','tesla','facebook']

And I have pandas df as follows -
COMPANY_DF

+--------+---------------------------------------+---------------+
|column1 |             column2                   |   column3     |
+------------------------------------------------+---------------|
|apple   | [list_2,list_3,list_4]                |               |
|google  | [list_1,list_2,list_3,list_5]         |               |
|tesla   | [list_1,list_2,list_3,list_4,list_5]  |               |
|facebook| [list_1,list_2,list_5]                |               |
|cisco   | [list_3]                              |               |
+------------------------------------------------+---------------+

Problem -
For column3 I have to find other elements that exists in the lists from column2
For e.g. - for column1 row 1 apple I have to find with what other companies are there with apple in [list_2,list_3,list_4] (column2 row 1)

My approach -

for i in range(0, len(COMPANY_DF['column2'])):
    column3_list = []
    for company in companies:
        for j in range(0, len(COMPANY_DF['column2'].loc[i])):
            if company in COMPANY_DF['column2'].loc[i][j]:
                company.append(column3_list)
            else:
                print('Not there')
    COMPANY_DF['column3'].loc[i] = column3_list

I am having issue with this if statement -

if company in COMPANY_DF['column2'].loc[i][j]:
if company in COMPANY_DF['column2'].loc[i][j] is
giving 'list_2' instead of list_2 I believe that's why it's failing.

Any help is appreciated.

Body:
This was my method:

companies = ['apple','google','tesla','facebook','cisco']
list_1 = ['apple','google','tesla','facebook']
list_2 = ['google','tesla','facebook']
list_3 = ['apple','tesla','cisco']
list_4 = ['apple','google','tesla']
list_5 = ['google','tesla','facebook']

list_of_lists = [f'list_{i}' for i in range(1, 6)]
# will create a string named the same for each of the lists,
# so it can be added to the list of mentions later, and also evaluated.

company_mentions = []
for company in companies:
    mentions = [mention for mention in list_of_lists if company in eval(mention)]
    # a list of the lists that a particular company has been mentioned in.

    company_mentions.append(mentions)
    # will append a list of the lists that company is mentioned in.

Hope this helps.

Edit: you can add an eval around mentions when you append it, if you'd prefer to have the entire list instead. Whatever works best for you.


问:
Adding category method to NSObject, but getting warnings because it's not in the <NSObject> protocol when I call it
(I found some questions discussing the idea, but I didn't see a solution for my problem.)

I added this convenience method as a category to NSObject. (I've added other methods, so I'm still interested in an answer even if you disagree with this particular convenience method.)

```<code>@implementation NSObject (MyCategory)
- (void)performInvocationOnMainThread:(NSInvocation *)invocation waitUntilDone:(BOOL)waitForMainThread;
@end
</code>```

Then I have a protocol I defined:

```<code>@protocol MyDelegateProtocol <NSObject>
- (void)myDelegateProtocolMethod;
@end
</code>```

Then I declare the delegate as a property of my class that implements said protocol.

```<code>@property (nonatomic, assign) id <MyDelegateProtocol> delegate;
</code>```

But when I try to call the NSObject method I added in my category like so

```<code>NSInvocation *invocation = [self.delegate invocationForSelector:@selector(someSelector:withArg:)];
</code>```

I get this warning

```<code>'-performInvocationOnMainThread:waitUntilDone:' not found in protocol(s)
</code>```

If I cast my delegate as (NSObject *) then I don't get the warning. What am I doing wrong? It didn't seem like I could (or should?) add methods to an existing protocol without creating a "sub protocol" and using it from then on. (Which kind of defeats the point of adding methods to NSObject in mind.)

```<code>NSInvocation *invocation = [(NSObject *)self.delegate invocationForSelector:@selector(someSelector:withArg:)];
</code>```

答:
when pass/expect this type, qualify it like so:</p>

```<code>- (void)race:(NSObject<MyDelegateProtocol>*)arg;
</code>```

Body:
(I found some questions discussing the idea, but I didn't see a solution for my problem.)

I added this convenience method as a category to NSObject. (I've added other methods, so I'm still interested in an answer even if you disagree with this particular convenience method.)

@implementation NSObject (MyCategory)
- (void)performInvocationOnMainThread:(NSInvocation *)invocation waitUntilDone:(BOOL)waitForMainThread;
@end

Then I have a protocol I defined:

@protocol MyDelegateProtocol <NSObject>
- (void)myDelegateProtocolMethod;
@end

Then I declare the delegate as a property of my class that implements said protocol.

@property (nonatomic, assign) id <MyDelegateProtocol> delegate;

But when I try to call the NSObject method I added in my category like so

NSInvocation *invocation = [self.delegate invocationForSelector:@selector(someSelector:withArg:)];

I get this warning

'-performInvocationOnMainThread:waitUntilDone:' not found in protocol(s)

If I cast my delegate as (NSObject *) then I don't get the warning. What am I doing wrong? It didn't seem like I could (or should?) add methods to an existing protocol without creating a "sub protocol" and using it from then on. (Which kind of defeats the point of adding methods to NSObject in mind.)

NSInvocation *invocation = [(NSObject *)self.delegate invocationForSelector:@selector(someSelector:withArg:)];

Body:
when pass/expect this type, qualify it like so:

- (void)race:(NSObject<MyDelegateProtocol>*)arg;


问:
How does the Google Service Client (PHP) method documentation work?
I have consistent difficulty using any client service method that is not explicitly exampled somewhere. Despite following the docs and even reading the sourcecode, The class or method names I come up with following the scheme are never right.

The documentation at Packagist (see 'Making Requests") says the client library classes are autogenerated from the Google endpoints, which agrees with the description in the library's docs on Github that say the pattern for accessing methods should be "$service->resource->method(args)".

So why the following?

```<code>// works:
// I get a countable object of active classrooms owner by the specified id
$response = $this->ClassroomService->courses->listCourses([
            'courseStates' =>   'ACTIVE',
            'teacherId'     => 'me']);

// works:
// I get an instance of the single classroom's object containing lots of meta data
$response = $this->ClassroomService->courses->get( $id );

// does not work:
// 500 error, obj has no such method
$response = $this->ClassroomService->topics->listCoursesTopics( $id  );
</code>```

According to the API Explorer all three should be fine.

What am I missing about using client service objects?

Edit
Ultimately I determined the resource in my example to be 'courses_topics'; the method was correct per the docs. Thanks for the idea @ebram.
The question remains how the methods are named though. courseWork is my next challenge and it does not fit the the naming pattern of topics.

答:
There is no topics member of ClassroomService.

The member is named courses_topics.

This is documented in the "Properties summary" at the bottom of the Classroom documentation.

Your code should look like this:

```<code>$response = $this->ClassroomService->courses_topics->listCoursesTopics( $id  );
</code>```

The documentation for Google_Service_Classroom_CoursesTopics_Resource does incorrectly give sample code where the member is named ->topics.

Given that API documentation is generated from source, but sample code is (generally) written by hand, I'll assume the API documentation is correct and the sample code is incorrect. I'd file a documentation-bug with Google.

Update:

I looked at the PHP source code for Google_Service_Classroom in GitHub and verified that the property is named courses_topics instead of topics, so in conclusion: the sample code is wrong.

What's also interesting is the resource-type in the actual source-code is Google_Service_Classroom_Resource_CoursesTopics but the documentation refers to it as Google_Service_Classroom_CoursesTopics_Resource - so that documentation is definitely wrong.

Body:
I have consistent difficulty using any client service method that is not explicitly exampled somewhere. Despite following the docs and even reading the sourcecode, The class or method names I come up with following the scheme are never right.

The documentation at Packagist (see 'Making Requests") says the client library classes are autogenerated from the Google endpoints, which agrees with the description in the library's docs on Github that say the pattern for accessing methods should be "$service->resource->method(args)".

So why the following?

// works:
// I get a countable object of active classrooms owner by the specified id
$response = $this->ClassroomService->courses->listCourses([
            'courseStates' =>   'ACTIVE',
            'teacherId'     => 'me']);

// works:
// I get an instance of the single classroom's object containing lots of meta data
$response = $this->ClassroomService->courses->get( $id );

// does not work:
// 500 error, obj has no such method
$response = $this->ClassroomService->topics->listCoursesTopics( $id  );

According to the API Explorer all three should be fine.

What am I missing about using client service objects?

Edit
Ultimately I determined the resource in my example to be 'courses_topics'; the method was correct per the docs. Thanks for the idea @ebram.
The question remains how the methods are named though. courseWork is my next challenge and it does not fit the the naming pattern of topics.

Body:
There is no topics member of ClassroomService.

The member is named courses_topics.

This is documented in the "Properties summary" at the bottom of the Classroom documentation.

Your code should look like this:

$response = $this->ClassroomService->courses_topics->listCoursesTopics( $id  );

The documentation for Google_Service_Classroom_CoursesTopics_Resource does incorrectly give sample code where the member is named ->topics.

Given that API documentation is generated from source, but sample code is (generally) written by hand, I'll assume the API documentation is correct and the sample code is incorrect. I'd file a documentation-bug with Google.

Update:

I looked at the PHP source code for Google_Service_Classroom in GitHub and verified that the property is named courses_topics instead of topics, so in conclusion: the sample code is wrong.

What's also interesting is the resource-type in the actual source-code is Google_Service_Classroom_Resource_CoursesTopics but the documentation refers to it as Google_Service_Classroom_CoursesTopics_Resource - so that documentation is definitely wrong.


问:
put awesome font icons in c # code behind
Currently I can measure the impressive font icons on my page with tabs from XAML code as follows:

```<code><ContentPage.IconImageSource>
    <FontImageSource  FontFamily="{StaticResource Solid }" Glyph="" ></FontImageSource>
</ContentPage.IconImageSource>
</code>```

That way I can already put icons in my applications, but I want to do it from the codebehind because that tabbed page will have to be created from certain actions and I did it in the following way:

```<code> contenido.IconImageSource  = new ContentPage().IconImageSource {
    new FontImageSource().FontFamily = "\uf108";
};
</code>```

but in the first "{" I get the error that says "I expected one ; "

Update

code App.xaml

```<code><Application.Resources>
    <ResourceDictionary>
        <!--Global Styles-->
        <Color x:Key="NavigationPrimary">#2196F3</Color>
        <Style TargetType="NavigationPage">
            <Setter Property="BarBackgroundColor" Value="{StaticResource NavigationPrimary}" />
            <Setter Property="BarTextColor" Value="White" />
        </Style>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="Brands">
            <On Platform="Android"
      Value="BrandsRegular.otf#Regular" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="Regular">
            <On Platform="Android"
      Value="FreeRegular.otf#Regular" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="Solid">
            <On Platform="Android"
      Value="FreeSolid.otf#Regular" />
        </OnPlatform>

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

答:
You don't need to create a new ContentPage, just create a FontImageSource object and set the values accordingly then pass this object to the IconImageSource of your contenido Page.

Also, you will need to get the StaticResource from the App Resources Dictionary.

Something like this should work:

```<code>var solidFontFamily = Application.Current.Resources["Solid"] as OnPlatform<string>;
contenido.IconImageSource = new FontImageSource() { FontFamily = solidFontFamily, Glyph= "\uf108" };
</code>```

Hope this helps.-

Body:
Currently I can measure the impressive font icons on my page with tabs from XAML code as follows:

<ContentPage.IconImageSource>
    <FontImageSource  FontFamily="{StaticResource Solid }" Glyph="" ></FontImageSource>
</ContentPage.IconImageSource>

That way I can already put icons in my applications, but I want to do it from the codebehind because that tabbed page will have to be created from certain actions and I did it in the following way:

 contenido.IconImageSource  = new ContentPage().IconImageSource {
    new FontImageSource().FontFamily = "\uf108";
};

but in the first "{" I get the error that says "I expected one ; "

Update

code App.xaml

<Application.Resources>
    <ResourceDictionary>

        <Color x:Key="NavigationPrimary">#2196F3</Color>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="Brands">
            <On Platform="Android"
      Value="BrandsRegular.otf#Regular" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="Regular">
            <On Platform="Android"
      Value="FreeRegular.otf#Regular" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="Solid">
            <On Platform="Android"
      Value="FreeSolid.otf#Regular" />
        </OnPlatform>

    </ResourceDictionary>
</Application.Resources>

Body:
You don't need to create a new ContentPage, just create a FontImageSource object and set the values accordingly then pass this object to the IconImageSource of your contenido Page.

Also, you will need to get the StaticResource from the App Resources Dictionary.

Something like this should work:

var solidFontFamily = Application.Current.Resources["Solid"] as OnPlatform<string>;
contenido.IconImageSource = new FontImageSource() { FontFamily = solidFontFamily, Glyph= "\uf108" };

Hope this helps.-


问:
In R plotly subplot graph, how to show only one legend?
I have a basic subplot with two graphs, both have a legend by default, but I want to see only one of them.

I tried this :

```<code>require(plotly)
p1 <- plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species) %>% layout(showlegend = FALSE)
p2 <-  plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species) %>% layout(showlegend = TRUE)
subplot(p1,p2)
subplot(p2,p1)
</code>```

But it doesn't work : it seems as if only one showlegend attribute was handled, so if I start with p1 I have two legend, if I start with p2 I have two.

Any ideas ?

答:
Maybe you can try a simple method. (plotly 4.9.2)

```<code>subplot(style(p1, showlegend = F), p2)
</code>```

It will just show the legend of p2. Hope this works.

Body:
I have a basic subplot with two graphs, both have a legend by default, but I want to see only one of them.

I tried this :

require(plotly)
p1 <- plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species) %>% layout(showlegend = FALSE)
p2 <-  plot_ly(data=iris,x=~Sepal.Length,y=~Sepal.Width,split=~Species) %>% layout(showlegend = TRUE)
subplot(p1,p2)
subplot(p2,p1)

But it doesn't work : it seems as if only one showlegend attribute was handled, so if I start with p1 I have two legend, if I start with p2 I have two.

Any ideas ?

Body:
Maybe you can try a simple method. (plotly 4.9.2)

subplot(style(p1, showlegend = F), p2)

It will just show the legend of p2. Hope this works.


问:
How to route mails outside Mac Os X Server host
I have a mac osx server at my office. I have only one email address configured on it because it's an email address outside my GSuite account. That email address was created for sending mails from a php script (I don't want to pay to Google for that email address because I don't need all of the Google Services on it). I configured PHP Mailer for sending mails using that email account.

It's connecting perfectly fine, authentication is correct, etc., but there is one problem: if I send mails to @mydomain.com it says that account doesn't exist, but it does exist, only that it is hosted on GSuite. If I send mails outside mydomain, it works fine.

Question is: how do I route those mails to look up for the correct MX récords? I mean, how to make those @mydomain.com emails reach the GSuite host?

答:
You can have multiple MX records per domain. It is possible. They will use priorities. You can even have multiple email servers checking emails from each other.

However, you case with hosted emails this won't work. Google is not going to let you do this.

You will have to pay.


问:
Select data from specific row of grouped and joined table in MySQL
I have two tables, customers and orders which are inner joined. A customer can have several orders associated with them. In my selection, I then group by customers.id. I need to select the most recent order of each customer, but also the amount of money spent in that order. Currently, I can select the most recent order_date but do not know how to select the amount in the same row as the order_date.

This is my current query:

```<code>SELECT
    first_name,
    last_name,
    email,
    MAX(order_date) AS recent_order,
    amount -- this needs to select amount associated with recent_order
FROM customers
JOIN orders
    ON customers.id = orders.customer_id
GROUP BY customers.id;
</code>```

The query selects the most recent date, but does not select the amount associated with the most recent order_date.

Table declarations:

```<code>CREATE TABLE customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    email VARCHAR(100)
);

CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_date DATE,
    amount DECIMAL(8,2),
    customer_id INT,
    FOREIGN KEY(customer_id) REFERENCES customers(id)
);
</code>```

答:
Use this:

SELECT TOP 1
    t1.first_name,
    t1.last_name,
    t1.email,
    t2.order_date,
    t2.amount
FROM customers t1
JOIN orders t2
    ON t1.id = t2.customer_id
ORDER BY
    t2.order_date
```

Add a GROUP BY t1.id if the intent is to return all rows with the most recent order_date. Omit this if every order is resented by a single row in orders. Note this will not sum the amounts. You will have to do that in code or else use a different query. Also note that performance of this query will be affected by configuration of indexes. This query may not be performant if order_date is not part of an index and the table contains a large data set.

Body:
I have two tables, customers and orders which are inner joined. A customer can have several orders associated with them. In my selection, I then group by customers.id. I need to select the most recent order of each customer, but also the amount of money spent in that order. Currently, I can select the most recent order_date but do not know how to select the amount in the same row as the order_date.

This is my current query:

SELECT
    first_name,
    last_name,
    email,
    MAX(order_date) AS recent_order,
    amount -- this needs to select amount associated with recent_order
FROM customers
JOIN orders
    ON customers.id = orders.customer_id
GROUP BY customers.id;

The query selects the most recent date, but does not select the amount associated with the most recent order_date.

Table declarations:

CREATE TABLE customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    email VARCHAR(100)
);

CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_date DATE,
    amount DECIMAL(8,2),
    customer_id INT,
    FOREIGN KEY(customer_id) REFERENCES customers(id)
);

Body:
Use this:

SELECT TOP 1
    t1.first_name,
    t1.last_name,
    t1.email,
    t2.order_date,
    t2.amount
FROM customers t1
JOIN orders t2
    ON t1.id = t2.customer_id
ORDER BY
    t2.order_date

Add a GROUP BY t1.id if the intent is to return all rows with the most recent order_date. Omit this if every order is resented by a single row in orders. Note this will not sum the amounts. You will have to do that in code or else use a different query. Also note that performance of this query will be affected by configuration of indexes. This query may not be performant if order_date is not part of an index and the table contains a large data set.


问:
Refactoring gatsby-node File into separate files not working
Trying to refactor my gatsby-node file, by outsourcing a bit of code. Right now trying to do this in my gatsby-node:

```<code>const createBlogPostPages = require("./gatsby-utils/createBlogPostPages");

exports.createPages = async ({ actions, graphql, reporter }) => {
  //...some code
  await createBlogPostPages({ actions, graphql, reporter });
  //...some code
}
</code>```

and my createBlogPostPages, which is in a different file, looks like so:

```<code>const path = require("path");

module.exports = async function({ actions, graphql, reporter }) {
  const { createPage } = actions;

  const blogArticles = await graphql(`
    {
      allMdx(filter: { fileAbsolutePath: { regex: "/content/blog/.*/" } }) {
        edges {
          node {
            id
            fileAbsolutePath
            fields {
              slug
            }
            frontmatter {
              title
              tags
              date
              tagline
            }
          }
        }
      }
    }
  `);

  blogArticles.data.allMdx.edges.forEach(({ node }) => {
    let imageFileName = ... //some stuff

    createPage({
      path: `${node.fields.slug}`,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        slug: `${node.fields.slug}`,
        id: node.id,
        imageFileName: imageFileName
      }
    });
  });
};
</code>```

All of this works when its directly in gatsby-node.
However, having moved stuff, I now get:

"gatsby-node.js" threw an error while running the createPages
  lifecycle:

blogArticles is not defined

ReferenceError: blogArticles is not defined

gatsby-node.js:177 Object.exports.createPages
  /Users/kohlisch/blogproject/gatsby-node.js:177:19

next_tick.js:68 process._tickCallback
  internal/process/next_tick.js:68:7

So it looks like it's not waiting for the graphql query to resolve? Or what might this be? I just basically want to move a few things out of my gatsby-node file, into separate functions, so that its not so cluttered. Is this not possible?

答:
There are two rules you need to follow when importing in gatsby-node.js:

1. Use node.js require syntax.

./src/components/util/gatsby-node-functions

const importedFunction = () => {
  return Date.now();
};

module.exports.importedFunction = importedFunction;
```

<p><code>gatsby-node.js</code></p>

<pre class="lang-js prettyprint-override"><code>const { importedFunction } = require(`./src/components/util/gatsby-node-functions`);

// ...
// Use your imported functions
console.log(importedFunction());
</code>```

Reference: Gatsby repo issue, also incluces hack how to use ES6 import statement if you want to add complexity just for using an import statement.

2. Do not pass gatsby-node.js specific attributes to your imported functions

If you attempt to outsource for example, your createPages function, actions will be undefined:

const importedFunction = (actions, node) => {
    const {createPage} = actions; // actions is undefined
    createPage({
      path: `${node.fields.slug}`,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        slug: `${node.fields.slug}`,
        id: node.id,
      }
    });
};

module.exports.importedFunction = importedFunction;
```

Feel free to speculate why you cannot pass the attributes. The Gatsby documentation mentions "Redux" for handling state. Maybe Redux does not supply state outside your gatsby-node.js. Correct me if I'm wrong

Body:
Trying to refactor my gatsby-node file, by outsourcing a bit of code. Right now trying to do this in my gatsby-node:

const createBlogPostPages = require("./gatsby-utils/createBlogPostPages");

exports.createPages = async ({ actions, graphql, reporter }) => {
  //...some code
  await createBlogPostPages({ actions, graphql, reporter });
  //...some code
}

and my createBlogPostPages, which is in a different file, looks like so:

const path = require("path");

module.exports = async function({ actions, graphql, reporter }) {
  const { createPage } = actions;

  const blogArticles = await graphql(`
    {
      allMdx(filter: { fileAbsolutePath: { regex: "/content/blog/.*/" } }) {
        edges {
          node {
            id
            fileAbsolutePath
            fields {
              slug
            }
            frontmatter {
              title
              tags
              date
              tagline
            }
          }
        }
      }
    }
  `);

  blogArticles.data.allMdx.edges.forEach(({ node }) => {
    let imageFileName = ... //some stuff

    createPage({
      path: `${node.fields.slug}`,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        slug: `${node.fields.slug}`,
        id: node.id,
        imageFileName: imageFileName
      }
    });
  });
};

All of this works when its directly in gatsby-node.
However, having moved stuff, I now get:

"gatsby-node.js" threw an error while running the createPages
  lifecycle:

blogArticles is not defined

ReferenceError: blogArticles is not defined

gatsby-node.js:177 Object.exports.createPages
  /Users/kohlisch/blogproject/gatsby-node.js:177:19

next_tick.js:68 process._tickCallback
  internal/process/next_tick.js:68:7

So it looks like it's not waiting for the graphql query to resolve? Or what might this be? I just basically want to move a few things out of my gatsby-node file, into separate functions, so that its not so cluttered. Is this not possible?

Body:
There are two rules you need to follow when importing in gatsby-node.js:

1. Use node.js require syntax.

./src/components/util/gatsby-node-functions

const importedFunction = () => {
  return Date.now();
};

module.exports.importedFunction = importedFunction;

gatsby-node.js

const { importedFunction } = require(`./src/components/util/gatsby-node-functions`);

// ...
// Use your imported functions
console.log(importedFunction());

Reference: Gatsby repo issue, also incluces hack how to use ES6 import statement if you want to add complexity just for using an import statement.

2. Do not pass gatsby-node.js specific attributes to your imported functions

If you attempt to outsource for example, your createPages function, actions will be undefined:

const importedFunction = (actions, node) => {
    const {createPage} = actions; // actions is undefined
    createPage({
      path: `${node.fields.slug}`,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        slug: `${node.fields.slug}`,
        id: node.id,
      }
    });
};

module.exports.importedFunction = importedFunction;

Feel free to speculate why you cannot pass the attributes. The Gatsby documentation mentions "Redux" for handling state. Maybe Redux does not supply state outside your gatsby-node.js. Correct me if I'm wrong


问:
If I have the same package name in Nexus private repo as it is in the npm publish repo, which one takes priority when I install?
I am setting up nexus npm repository, and created npm-group = npm-private+npm-registry (proxy to npm offical registry).

It comes to me thinking that if I publish my own package and name it say "jest" to my private repo,
what happens if I do npm install jest? Does it take the private fake one or the one published in official site?

Thanks

答:
You need to use scopes for your  private packages. You prefix them with @yournamespace (for instance: "name": "@yournamespace/jest"), and you adjust your npmrc accordingly:

```<code>; Set a new registry for a scoped package
@yournamespace:registry=https://mycustomregistry.example.org
</code>```

Using this scheme, you could use separate npm repositories, one for the proxy to the official npmjs repo, and one for your private packages.

Otherwise, if you override a package name, it will shadow the one that is proxified, so you will fetch your private package instead of the official one.

Body:
You need to use scopes for your  private packages. You prefix them with @yournamespace (for instance: "name": "@yournamespace/jest"), and you adjust your npmrc accordingly:

; Set a new registry for a scoped package
@yournamespace:registry=https://mycustomregistry.example.org

Using this scheme, you could use separate npm repositories, one for the proxy to the official npmjs repo, and one for your private packages.

Otherwise, if you override a package name, it will shadow the one that is proxified, so you will fetch your private package instead of the official one.


问:
IntelliJ target bytecode reverting
For a project that I'm currently working on, IntelliJ gave me the compile error Error:java: javacTask: source release 8 requires target release 1.8. I went into Settings>Build, Execution, Deployment>Compiler>Java and saw that the target bytecode version for one of my modules was set to 1.5, so I changed it to 1.8, compiled, and it worked. But then the next day, I got the same error. I went into settings and the target bytecode for that one module was back at 1.5. I changed it to 1.8 and it compiled/ran just fine. This has now happened multiple times and I am frustrated by the number of times I have to go into settings to manually change the target bytecode version.

Why does the target bytecode version keep reverting? I don't have 1.5 specified in the pom or anywhere else, so I am baffled as to why the bytecode version keeps getting set to 1.5.

答:
FYI.

I still had this problem despite setting the pom.xml with both the settings above from the answers as mentioned by @isapir and @carlos-a-ibarra respectively.

I discovered this was due to an Intellij setting:

This config can be found in Build,Execution,Deployment > Build Tools > Maven > Importing

By default, it is set to the 'Internal JRE' setting, which in the latest version of Idea is 11. I had to select it to use the 1.8 JDK the project was configured to use.

This is annoying, because if you have a mix of 11 and 8 projects, you'll have to manually toggle this setting back and forth.

It caused the module output to always fall back to 11 every time the pom.xml was reimported.

It's a really annoying bug in IntelliJ.

Title: IntelliJ target bytecode reverting


问:
Populating a vector with numbers and conditions in C++
Working on a business class assignment where we're using Excel to solve a problem with the following setup and conditions, but I wanted to find solutions by writing some code in C++ which is what I'm most familiar from some school courses.

We have 4 stores where we need to invest 10 million dollars. The main conditions are:

It is necessary to invest at least 1mil per store.

The investments in the 4 stores must total 10 million.

Following the rules above, the most one can invest in a single store is 7 million

Each store has its own unique return of investment percentages based off the amount of money invested per store.
In other words, there is a large number of combinations that can be obtained by investing in each store. Repetition of numbers does not matter as long as the total is 10 per combination, but the order of the numbers does matter.

If my math is right, the total number of combinations is 7^4 = 2401, but the number of working solutions
is lesser due to the condition that each combination must equal 10 as a sum.

What I'm trying to do in C++ is use loops to populate each row with 4 numbers such that their sum equals 10 (millions), for example:

7  1   1   1

1  7   1   1

1  1   7   1

1  1   1   7

6  2   1   1

6  1   2   1

6  1   1   2

5  3   1   1

5  1   3   1

5  1   1   3

5  1   2   2

5  2   1   2

5  2   2   1

I'd appreciate advice on how to tackle this. Still not quite sure if using loops is a good idea whilst using an array (2D Array/Vector perhaps?) I've a vague idea that maybe recursive functions would facilitate a solution.

Thanks for taking some time to read, I appreciate any and all advice for coming up with solutions.

Edit:
Here's some code I worked on to just get 50 rows of numbers randomized. Still have to implement the conditions where valid row combinations must be the sum total of 10 between the 4;

```<code>int main(){
    const int rows = 50;
    int values[rows][4];

    for (int i = 0; i < 50; i++) {
        for (int j = 0; j <= 3; j++){
            values[i][j]= (rand() % 7 + 1);
            cout << values[i][j] << " ";
        }
        cout << endl;
    }
}
</code>```

答:
You can calculate this recursively. For each level, you have:

A target sum

The number of elements in that level

The minimum value each individual element can have

First, we determine our return type. What's your final output? Looks like a vector of vectors to me. So our recursive function will return a the same.

Second, we determine the result of our degenerate case (at the "bottom" of the recursion), when the number of elements in this level is 1.

```<code>std::vector<std::vector<std::size_t>> recursive_combinations(std::size_t sum, std::size_t min_val, std::size_t num_elements)
{
    std::vector<std::vector<std::size_t>> result {};
    if (num_elements == 1)
    {
        result.push_back(std::vector<std::size_t>{sum});
        return result;
    }

    ...non-degenerate case goes here...

    return result;
}
</code>```

Next, we determine what happens when this level has more than 1 element in it. Split the sum into all possible pairs of the "first" element and the "remaining" group. e.g., if we have a target sum of 5, 3 num_elements, and a min_val of 1, we'd generate the pairs {1,4}, {2,3}, and {3,2}, where the first number in each pair is for the first element, and the second number in each pair is the remaining sum left over for the remaining group.

Recursively call the recursive_combinations function using this second number as the new sum, and num_elements - 1 as the new num_elements to find the vector of vectors for the remaining group, and for each vector in the return vector, append the first element from the above set.

Body:
Working on a business class assignment where we're using Excel to solve a problem with the following setup and conditions, but I wanted to find solutions by writing some code in C++ which is what I'm most familiar from some school courses.

We have 4 stores where we need to invest 10 million dollars. The main conditions are:

It is necessary to invest at least 1mil per store.

The investments in the 4 stores must total 10 million.

Following the rules above, the most one can invest in a single store is 7 million

Each store has its own unique return of investment percentages based off the amount of money invested per store.
In other words, there is a large number of combinations that can be obtained by investing in each store. Repetition of numbers does not matter as long as the total is 10 per combination, but the order of the numbers does matter.

If my math is right, the total number of combinations is 7^4 = 2401, but the number of working solutions
is lesser due to the condition that each combination must equal 10 as a sum.

What I'm trying to do in C++ is use loops to populate each row with 4 numbers such that their sum equals 10 (millions), for example:

7  1   1   1

1  7   1   1

1  1   7   1

1  1   1   7

6  2   1   1

6  1   2   1

6  1   1   2

5  3   1   1

5  1   3   1

5  1   1   3

5  1   2   2

5  2   1   2

5  2   2   1

I'd appreciate advice on how to tackle this. Still not quite sure if using loops is a good idea whilst using an array (2D Array/Vector perhaps?) I've a vague idea that maybe recursive functions would facilitate a solution.

Thanks for taking some time to read, I appreciate any and all advice for coming up with solutions.

Edit:
Here's some code I worked on to just get 50 rows of numbers randomized. Still have to implement the conditions where valid row combinations must be the sum total of 10 between the 4;

int main(){
    const int rows = 50;
    int values[rows][4];

    for (int i = 0; i < 50; i++) {
        for (int j = 0; j <= 3; j++){
            values[i][j]= (rand() % 7 + 1);
            cout << values[i][j] << " ";
        }
        cout << endl;
    }
}

Body:
You can calculate this recursively. For each level, you have:

A target sum

The number of elements in that level

The minimum value each individual element can have

First, we determine our return type. What's your final output? Looks like a vector of vectors to me. So our recursive function will return a the same.

Second, we determine the result of our degenerate case (at the "bottom" of the recursion), when the number of elements in this level is 1.

std::vector<std::vector<std::size_t>> recursive_combinations(std::size_t sum, std::size_t min_val, std::size_t num_elements)
{
    std::vector<std::vector<std::size_t>> result {};
    if (num_elements == 1)
    {
        result.push_back(std::vector<std::size_t>{sum});
        return result;
    }

    ...non-degenerate case goes here...

    return result;
}

Next, we determine what happens when this level has more than 1 element in it. Split the sum into all possible pairs of the "first" element and the "remaining" group. e.g., if we have a target sum of 5, 3 num_elements, and a min_val of 1, we'd generate the pairs {1,4}, {2,3}, and {3,2}, where the first number in each pair is for the first element, and the second number in each pair is the remaining sum left over for the remaining group.

Recursively call the recursive_combinations function using this second number as the new sum, and num_elements - 1 as the new num_elements to find the vector of vectors for the remaining group, and for each vector in the return vector, append the first element from the above set.


问:
Choosing minimum length k of array for merge sort where use of insertion sort to sort the subarrays is more optimal than standard merge sort
This is a question from Introduction to Algorithms By Cormen. But this isn't a homework problem instead self-study.

There is an array of length n. Consider a modification to merge sort in which n/k sublists each of length k are sorted using insertion sort and then merged using merging mechanism, where k is a value to be determined.

The relationship between n and k isn't known. The length of array is n. k sublists of n/k means n * (n/k) equals n elements of the array. Hence k is simply a limit at which the splitting of array for use with merge-sort is stopped and instead insertion-sort is used because of its smaller constant factor.

I was able to do the mathematical proof that the modified algorithm works in Θ(n*k + n*lg(n/k)) worst-case time. Now the book went on to say to

find the largest value of k as a function of n for which this modified algorithm has the same running time as standard merge sort, in terms of Θ notation. How should we choose k in practice?

Now this got me thinking for a lot of time but I couldn't come up with anything. I tried to solve

n*k + n*lg(n/k) = n*lg(n) for a relationship. I thought that finding an equality for the 2 running times would give me the limit and greater can be checked using simple hit-and-trial.

I solved it like this

```<code>n k + n lg(n/k) = n  lg(n)

k + lg(n/k) = lg(n)

lg(2^k) + lg(n/k) = lg(n)

(2^k * n)/k = n

2^k = k
</code>```

But it gave me 2 ^ k = k which doesn't show any relationship. What is the relationship? I think I might have taken the wrong equation for finding the relationship.

I can implement the algorithm and I suppose adding an if (length_Array < k) statement in the merge_sort function here(Github link of merge sort implementation) for calling insertion sort would be good enough. But how do I choose k in real life?

答:
maybe k should be lg(n)

theta(nk + nlog(n/k)) have two terms, we have the assumption that k>=1, so the second term is less than nlog(n).

only when k=lg(n), the whole result is theta(nlog(n))

Body:
This is a question from Introduction to Algorithms By Cormen. But this isn't a homework problem instead self-study.

There is an array of length n. Consider a modification to merge sort in which n/k sublists each of length k are sorted using insertion sort and then merged using merging mechanism, where k is a value to be determined.

The relationship between n and k isn't known. The length of array is n. k sublists of n/k means n * (n/k) equals n elements of the array. Hence k is simply a limit at which the splitting of array for use with merge-sort is stopped and instead insertion-sort is used because of its smaller constant factor.

I was able to do the mathematical proof that the modified algorithm works in Θ(n*k + n*lg(n/k)) worst-case time. Now the book went on to say to

find the largest value of k as a function of n for which this modified algorithm has the same running time as standard merge sort, in terms of Θ notation. How should we choose k in practice?

Now this got me thinking for a lot of time but I couldn't come up with anything. I tried to solve

n*k + n*lg(n/k) = n*lg(n) for a relationship. I thought that finding an equality for the 2 running times would give me the limit and greater can be checked using simple hit-and-trial.

I solved it like this

n k + n lg(n/k) = n  lg(n)

k + lg(n/k) = lg(n)

lg(2^k) + lg(n/k) = lg(n)

(2^k * n)/k = n

2^k = k

But it gave me 2 ^ k = k which doesn't show any relationship. What is the relationship? I think I might have taken the wrong equation for finding the relationship.

I can implement the algorithm and I suppose adding an if (length_Array < k) statement in the merge_sort function here(Github link of merge sort implementation) for calling insertion sort would be good enough. But how do I choose k in real life?


问:
Adding pause/resume support in an Android Game
I am trying to add Pause/Resume support to my Android game. How do I pause the current  thread when user presses pause option and resume the thread when the use chooses resume option? Any suggestions/ideas would be of great help.</p>

答:
Try looking at the source for ReplicaIsland or the sample code in the LunarLander example. These two are popular examples for starting points.

Also, make sure you understand how threads work and if you really want to pause the thread. Another approach would be to simply pause the drawing / updating while the thread still runs. Some code like this may be what you're looking for:

```<code>@Override
public void run()
{
    while (mRun)
    {
        Canvas c = null;
        try
        {
            c = mSurfaceHolder.lockCanvas(null);
            synchronized (mSurfaceHolder)
            {
                if (mMode == STATE_RUNNING)
                {
                  updatePhysics();
                }
                doDraw(c);
            }
        } finally {
          // ...
        }
    }
}
</code>```

That's a modified version of the run() function in the LunarLander example.

The main point of interest is where the updatePhysics() function only gets called if mMode == STATE_RUNNING. Simply changing mMode will cause the physics to stop updating and effectively pause the game.

I think this is more or less what @vivek was describing.

Body:
Try looking at the source for ReplicaIsland or the sample code in the LunarLander example. These two are popular examples for starting points.

Also, make sure you understand how threads work and if you really want to pause the thread. Another approach would be to simply pause the drawing / updating while the thread still runs. Some code like this may be what you're looking for:

@Override
public void run()
{
    while (mRun)
    {
        Canvas c = null;
        try
        {
            c = mSurfaceHolder.lockCanvas(null);
            synchronized (mSurfaceHolder)
            {
                if (mMode == STATE_RUNNING)
                {
                  updatePhysics();
                }
                doDraw(c);
            }
        } finally {
          // ...
        }
    }
}

That's a modified version of the run() function in the LunarLander example.

The main point of interest is where the updatePhysics() function only gets called if mMode == STATE_RUNNING. Simply changing mMode will cause the physics to stop updating and effectively pause the game.

I think this is more or less what @vivek was describing.


问:
How to print subcommand result automatically?
I have Java CLI application based on cliche library and I want to migrate it to picocli.

My application was based on cliche so I have a lot of methods with asg.cliche.Command annotation which return some result. cliche prints command methods's result automatically so result was printed in command line. I replaced asg.cliche.Command annotations by picocli.CommandLine.Command and I see that picocli does not print command methods's results.
I have following class:

```<code>import picocli.CommandLine;

@CommandLine.Command(subcommandsRepeatable = true)
public class Foo
{

    public static void main( String[] args )
    {
        new CommandLine( new Foo() ).execute( args );
    }

    @CommandLine.Command
    public String sayHello()
    {
        return "Hello";
    }

    @CommandLine.Command
    public String sayGoodbye()
    {
        return "GoodBye";
    }
}
</code>```

when I call java -cp myJar.jar Foo sayHello sayGoodbye I do not see any output.
I see three solutions:
 1. Modify each methods to print result instead of return it.

```<code>import picocli.CommandLine;

@CommandLine.Command( subcommandsRepeatable = true )
public class Foo2
{

    public static void main( String[] args )
    {
        new CommandLine( new Foo2() ).execute( args );
    }

    @CommandLine.Command
    public void sayHello()
    {
        System.out.println( "Hello" );
    }

    @CommandLine.Command
    public void sayGoodbye()
    {
        System.out.println( "GoodBye" );
    }
}
</code>```

I am not happy with this solution. I prefer not modify my methods.

Retrieve results after execution.

```<code>public static void main( String[] args )
    {
        final CommandLine commandLine = new CommandLine( new Foo() );
        commandLine.execute( args );
        CommandLine.ParseResult parseResult = commandLine.getParseResult();
        for( CommandLine.ParseResult pr : parseResult.subcommands() )
        {
            System.out.println( pr.commandSpec().commandLine()
                .getExecutionResult()
                .toString() );
        }
    }
</code>```

I see a few problems with this solution. The main problem is formatting. Execution result can be null, array, collection. The second problem is that results are printed after execution of all subcommands. If second subcommand throws exception then I firstly see exception stack trace  and after that I see result of first subcommand.

Ask on stackoverflow if there is some better solution. I do not believe that there is no any configuration option in picocli which enable results printing.

答:
Personally, I like your first solution best, it is simple and easy to maintain. Maybe introduce a helper method for the printing and formatting so the command methods can look like this:

    @CommandLine.Command
    public String sayGoodbye()
    {
        return printValue("GoodBye");
    }
```

<p>You already found the <code>CommandLine.getParseResult</code> method; perhaps a helper method could assist with the formatting there as well. </p>

<p>There is a third option, but it is unfortunately quite a bit more complex: you can create a custom <code>IExecutionStrategy</code> that prints the result of each command after executing it. It involves copying a lot of code from the picocli internals and it’s not really a realistic solution; I just mention it for completeness. </p>

<pre class="lang-java prettyprint-override"><code>// extend RunLast to handle requests for help/version and exit code stuff
class PrintingExecutionStrategy extends CommandLine.RunLast {
    @Override
    protected List<Object> handle(ParseResult parseResult) throws ExecutionException {
        // Simplified: executes only the last subcommand (so no repeating subcommands).
        // Look at RunLast.executeUserObjectOfLastSubcommandWithSameParent if you need repeating subcommands.
        List<CommandLine> parsedCommands = parseResult.asCommandLineList();
        CommandLine last = parsedCommands.get(parsedCommands.size() - 1);
        return execute(last, new ArrayList<Object>());
    }

    // copied from CommandLine.executeUserObject,
    // modified to print the execution result
    private List<Object> execute(CommandLine cmd, List<Object> executionResultList) throws Exception {
        Object command = parsed.getCommand();
        if (command instanceof Runnable) {
            try {
                ((Runnable) command).run();
                parsed.setExecutionResult(null); // 4.0
                executionResultList.add(null); // for compatibility with picocli 2.x
                return executionResultList;
            } catch (ParameterException ex) {
                throw ex;
            } catch (ExecutionException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Error while running command (" + command + "): " + ex, ex);
            }
        } else if (command instanceof Callable) {
            try {
                @SuppressWarnings("unchecked") Callable<Object> callable = (Callable<Object>) command;
                Object executionResult = callable.call();

                System.out.println(executionResult); <-------- print result

                parsed.setExecutionResult(executionResult);
                executionResultList.add(executionResult);
                return executionResultList;
            } catch (ParameterException ex) {
                throw ex;
            } catch (ExecutionException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + ex, ex);
            }
        } else if (command instanceof Method) {
            try {
                Method method = (Method) command;
                Object[] parsedArgs = parsed.getCommandSpec().argValues();
                Object executionResult;
                if (Modifier.isStatic(method.getModifiers())) {
                    executionResult = method.invoke(null, parsedArgs); // invoke static method
                } else if (parsed.getCommandSpec().parent() != null) {
                    executionResult = method.invoke(parsed.getCommandSpec().parent().userObject(), parsedArgs);
                } else {
                    executionResult = method.invoke(parsed.factory.create(method.getDeclaringClass()), parsedArgs);
                }

                System.out.println(executionResult); <-------- print result

                parsed.setExecutionResult(executionResult);
                executionResultList.add(executionResult);
                return executionResultList;
            } catch (InvocationTargetException ex) {
                Throwable t = ex.getTargetException();
                if (t instanceof ParameterException) {
                    throw (ParameterException) t;
                } else if (t instanceof ExecutionException) {
                    throw (ExecutionException) t;
                } else {
                    throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + t, t);
                }
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Unhandled error while calling command (" + command + "): " + ex, ex);
            }
        }
        throw new ExecutionException(parsed, "Parsed command (" + command + ") is not a Method, Runnable or Callable");
    }
}
</code>```

Use it like this:

public static void main(String... args) {
    new CommandLine(new Foo())
        .setExecutionStrategy(new PrintingExecutionStrategy())
        .execute(args);
}
```

<p>I wouldn’t recommend the above. </p>

<p>Update: I thought of another, fourth, option (actually a variation of your 2nd solution). You can specify a custom <code>IExecutionExceptionHandler</code> that doesn’t print the stacktrace, but instead stores the exception so you can print the stacktrace after printing the command results. Something like this:</p>

<pre class="lang-java prettyprint-override"><code>class MyHandler extends IExecutionExceptionHandler() {
    Exception exception;
    public int handleExecutionException(Exception ex,
                                         CommandLine commandLine,
                                         ParseResult parseResult) {
         //ex.printStackTrace(); // no stack trace
         exception = ex;
    }
}
</code>```

Use it like this:

public static void main(String... args) {
    MyHandler handler = new MyHandler();
    CommandLine cmd = new CommandLine(new Foo())
        .setExecutionExceptionHandler(handler);
    cmd.execute(args);

    ParseResult parseResult = cmd.getParseResult();
    for( ParseResult pr : parseResult.subcommands() )
    {
        System.out.println( pr.commandSpec().commandLine()
                .getExecutionResult()
                .toString() );
    }

    if (handler.exception != null) {
        handler.exception.printStackTrace();
    }
}
```

Body:
I have Java CLI application based on cliche library and I want to migrate it to picocli.

My application was based on cliche so I have a lot of methods with asg.cliche.Command annotation which return some result. cliche prints command methods's result automatically so result was printed in command line. I replaced asg.cliche.Command annotations by picocli.CommandLine.Command and I see that picocli does not print command methods's results.
I have following class:

import picocli.CommandLine;

@CommandLine.Command(subcommandsRepeatable = true)
public class Foo
{

    public static void main( String[] args )
    {
        new CommandLine( new Foo() ).execute( args );
    }

    @CommandLine.Command
    public String sayHello()
    {
        return "Hello";
    }

    @CommandLine.Command
    public String sayGoodbye()
    {
        return "GoodBye";
    }
}

when I call java -cp myJar.jar Foo sayHello sayGoodbye I do not see any output.
I see three solutions:
 1. Modify each methods to print result instead of return it.

import picocli.CommandLine;

@CommandLine.Command( subcommandsRepeatable = true )
public class Foo2
{

    public static void main( String[] args )
    {
        new CommandLine( new Foo2() ).execute( args );
    }

    @CommandLine.Command
    public void sayHello()
    {
        System.out.println( "Hello" );
    }

    @CommandLine.Command
    public void sayGoodbye()
    {
        System.out.println( "GoodBye" );
    }
}

I am not happy with this solution. I prefer not modify my methods.

Retrieve results after execution.

public static void main( String[] args )
    {
        final CommandLine commandLine = new CommandLine( new Foo() );
        commandLine.execute( args );
        CommandLine.ParseResult parseResult = commandLine.getParseResult();
        for( CommandLine.ParseResult pr : parseResult.subcommands() )
        {
            System.out.println( pr.commandSpec().commandLine()
                .getExecutionResult()
                .toString() );
        }
    }

I see a few problems with this solution. The main problem is formatting. Execution result can be null, array, collection. The second problem is that results are printed after execution of all subcommands. If second subcommand throws exception then I firstly see exception stack trace  and after that I see result of first subcommand.

Ask on stackoverflow if there is some better solution. I do not believe that there is no any configuration option in picocli which enable results printing.

Body:
Personally, I like your first solution best, it is simple and easy to maintain. Maybe introduce a helper method for the printing and formatting so the command methods can look like this:

    @CommandLine.Command
    public String sayGoodbye()
    {
        return printValue("GoodBye");
    }

You already found the CommandLine.getParseResult method; perhaps a helper method could assist with the formatting there as well.

There is a third option, but it is unfortunately quite a bit more complex: you can create a custom IExecutionStrategy that prints the result of each command after executing it. It involves copying a lot of code from the picocli internals and it’s not really a realistic solution; I just mention it for completeness.

// extend RunLast to handle requests for help/version and exit code stuff
class PrintingExecutionStrategy extends CommandLine.RunLast {
    @Override
    protected List<Object> handle(ParseResult parseResult) throws ExecutionException {
        // Simplified: executes only the last subcommand (so no repeating subcommands).
        // Look at RunLast.executeUserObjectOfLastSubcommandWithSameParent if you need repeating subcommands.
        List<CommandLine> parsedCommands = parseResult.asCommandLineList();
        CommandLine last = parsedCommands.get(parsedCommands.size() - 1);
        return execute(last, new ArrayList<Object>());
    }

    // copied from CommandLine.executeUserObject,
    // modified to print the execution result
    private List<Object> execute(CommandLine cmd, List<Object> executionResultList) throws Exception {
        Object command = parsed.getCommand();
        if (command instanceof Runnable) {
            try {
                ((Runnable) command).run();
                parsed.setExecutionResult(null); // 4.0
                executionResultList.add(null); // for compatibility with picocli 2.x
                return executionResultList;
            } catch (ParameterException ex) {
                throw ex;
            } catch (ExecutionException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Error while running command (" + command + "): " + ex, ex);
            }
        } else if (command instanceof Callable) {
            try {
                @SuppressWarnings("unchecked") Callable<Object> callable = (Callable<Object>) command;
                Object executionResult = callable.call();

                System.out.println(executionResult); <-------- print result

                parsed.setExecutionResult(executionResult);
                executionResultList.add(executionResult);
                return executionResultList;
            } catch (ParameterException ex) {
                throw ex;
            } catch (ExecutionException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + ex, ex);
            }
        } else if (command instanceof Method) {
            try {
                Method method = (Method) command;
                Object[] parsedArgs = parsed.getCommandSpec().argValues();
                Object executionResult;
                if (Modifier.isStatic(method.getModifiers())) {
                    executionResult = method.invoke(null, parsedArgs); // invoke static method
                } else if (parsed.getCommandSpec().parent() != null) {
                    executionResult = method.invoke(parsed.getCommandSpec().parent().userObject(), parsedArgs);
                } else {
                    executionResult = method.invoke(parsed.factory.create(method.getDeclaringClass()), parsedArgs);
                }

                System.out.println(executionResult); <-------- print result

                parsed.setExecutionResult(executionResult);
                executionResultList.add(executionResult);
                return executionResultList;
            } catch (InvocationTargetException ex) {
                Throwable t = ex.getTargetException();
                if (t instanceof ParameterException) {
                    throw (ParameterException) t;
                } else if (t instanceof ExecutionException) {
                    throw (ExecutionException) t;
                } else {
                    throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + t, t);
                }
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Unhandled error while calling command (" + command + "): " + ex, ex);
            }
        }
        throw new ExecutionException(parsed, "Parsed command (" + command + ") is not a Method, Runnable or Callable");
    }
}

Use it like this:

public static void main(String... args) {
    new CommandLine(new Foo())
        .setExecutionStrategy(new PrintingExecutionStrategy())
        .execute(args);
}

I wouldn’t recommend the above.

Update: I thought of another, fourth, option (actually a variation of your 2nd solution). You can specify a custom IExecutionExceptionHandler that doesn’t print the stacktrace, but instead stores the exception so you can print the stacktrace after printing the command results. Something like this:

class MyHandler extends IExecutionExceptionHandler() {
    Exception exception;
    public int handleExecutionException(Exception ex,
                                         CommandLine commandLine,
                                         ParseResult parseResult) {
         //ex.printStackTrace(); // no stack trace
         exception = ex;
    }
}

Use it like this:

public static void main(String... args) {
    MyHandler handler = new MyHandler();
    CommandLine cmd = new CommandLine(new Foo())
        .setExecutionExceptionHandler(handler);
    cmd.execute(args);

    ParseResult parseResult = cmd.getParseResult();
    for( ParseResult pr : parseResult.subcommands() )
    {
        System.out.println( pr.commandSpec().commandLine()
                .getExecutionResult()
                .toString() );
    }

    if (handler.exception != null) {
        handler.exception.printStackTrace();
    }
}