问:
Fault Tolerance in Flink
How can we configure a Flink application to start/restart only the pods/(sub)tasks that crashed instead of restarting the whole job i.e. restart all the tasks/sub-tasks in the job/pipeline including that tasks that are healthy. It does not make sense and feels unnecessary to try to restart the healthy tasks along with the crashed ones. The stream processing application processes messages from Kafka and writes the output back to Kafka and runs on Flink 1.13.5 and a Kubernetes resource manager - using Lyft's Kubernetes operator to schedule and run the Flink job. We tried setting the property, **jobmanager.execution.failover-strategy** to **region** and did not help.

答:
Flink only supports partial restarts to the extent that this is possible without sacrificing completely correct, exactly-once results.

After recovery, failed tasks are restarted from the latest checkpoint. Their inputs are rewound, and they will reproduce previously emitted results. If healthy downstream consumers of those failed tasks aren't also reset and restarted from that same checkpoint, then they will end up producing duplicate/inflated results.

With streaming jobs, only with embarrassingly parallel pipelines will have you disjoint pipelined regions. Any use of keyBy or rebalancing (e.g., to change the parallelism) will produce a job with a single failure region.

Title: Fault Tolerance in Flink


来源: stackexchange

问:
update Jenkins from 1.424 to 1.426,it don't work
Jenkins:http://jenkins-ci.org/changelog
What's new in 1.426 (2011/08/15)

Auto Install JDK asks for Oracle account, but the link goes 404.
(issue 10556)

Record and display who aborted builds.

Added API token support. (issue 9363)

Maven Plugin can use settings and global settings files provided by
the config provider plugin Fixed background of title image (issue
9571)
when i run mvn project,failed.

13:10:22  Waiting for Jenkins to finish collecting data
13:10:23  channel stopped
13:10:25  FATAL: null
13:10:27  java.lang.NullPointerException
13:10:27    at hudson.maven.MavenModuleSetBuild$RunnerImpl.doRun(MavenModuleSetBuild.java:833)
13:10:27    at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:448)
13:10:27    at hudson.model.Run.run(Run.java:1376)
13:10:27    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:479)
13:10:27    at hudson.model.ResourceController.execute(ResourceController.java:88)
13:10:27    at hudson.model.Executor.run(Executor.java:230)

i rollback 1.424,it work.

答:
This also happened in our environment after upgrading to 1.426. (Windows running a multi-slave-setup).

The issue is now registered in the Jenkins issue tracker:

JENKINS-10715
Finishing with a Null Pointer Exception after a successful build., and the duplicate

JENKINS-10755
NPE after successful project build with maven

ContentLicense: CC BY-SA 3.0


问:
Compose creating new ViewModel instance
I work in a project that's slowly adopting Jetpack Compose. It's mostly a single Activity multiple Fragments app where we use the Android's navigation component to handle transitions to each screen (Fragment). Whenever we can, we are only replacing the Fragments' XML layout with Composables.

The cases up until now were handling like the following:

A. Fragments show composables and handle navigation:

```<code>class ScreenFragment : Fragment() {

    // For observing events that trigger navigation
    private val viewModel by lazyViewModel { ScreenViewModel() }

    override fun onCreateView( ... ): View {
        return ComposeView(requireContext()).apply {

            setViewCompositionStrategy(DisposeOnLifecycleDestroyed(viewLifecycleOwner))

            setContent {
                AppTheme {
                    Screen(onBackPressed = { findNavController().navigateUp() })
                }
            }
        }
    }
    ...

}
</code>```

B. Composable that handles everything else UI related:

```<code>@Composable
fun CreatePassword(
    onBackPressed: () -> Unit,
) {

    // For observing UI states and events
    val viewModel: CreatePasswordViewModel = viewModel()
    ...
}

</code>```

As you can see, we have a reference for the screen's ViewModel in both our Fragments and our Composables. Up until now, this has been working fine, the composable viewModel() function was always returning the same existing instance of the Fragment's ViewModel.

The problems came when we needed the reference of a ViewModel scoped to an Activity on the composable:

We create the ViewModel on the Activity:

```<code>class MainActivity : AppCompatActivity() {

    private val viewModel by lazyViewModel { MainViewModel() }
    ...
}
</code>```

Get a reference for the MainActivity's ViewModel on the Fragment like

```<code>class MainFragment : Fragment() {

    private val viewModel: MainViewModel by viewModels(::requireActivity)
    ...
}
</code>```

We get the reference of the ViewModel for composables as shown above (item B)

By doing so the Fragment has the same instance of the Activity's but the composable doesn't.

My questions is,
would it be possible to get the reference of the Activity's ViewModel inside the composable? For now I'm simply passing down the Fragment's ViewModel as a parameter to my main composable screen.

答:
Sounds like a classic dependency problem, at this point I would consider using some sort of Dependency Injection library and make sure to provide the viewModel instance as a singleton.

I can recommend Koin:
https://insert-koin.io/

Or, more recently and trendy Hilt:
https://developer.android.com/training/dependency-injection/hilt-android

Once using a good DI you can get an instance of the viewModel in your compose functions.

ContentLicense: CC BY-SA 4.0

Title: Compose creating new ViewModel instance

Body:
I work in a project that's slowly adopting Jetpack Compose. It's mostly a single Activity multiple Fragments app where we use the Android's navigation component to handle transitions to each screen (Fragment). Whenever we can, we are only replacing the Fragments' XML layout with Composables.

The cases up until now were handling like the following:

A. Fragments show composables and handle navigation:

class ScreenFragment : Fragment() {

    // For observing events that trigger navigation
    private val viewModel by lazyViewModel { ScreenViewModel() }

    override fun onCreateView( ... ): View {
        return ComposeView(requireContext()).apply {

            setViewCompositionStrategy(DisposeOnLifecycleDestroyed(viewLifecycleOwner))

            setContent {
                AppTheme {
                    Screen(onBackPressed = { findNavController().navigateUp() })
                }
            }
        }
    }
    ...

}

B. Composable that handles everything else UI related:

@Composable
fun CreatePassword(
    onBackPressed: () -> Unit,
) {

    // For observing UI states and events
    val viewModel: CreatePasswordViewModel = viewModel()
    ...
}

As you can see, we have a reference for the screen's ViewModel in both our Fragments and our Composables. Up until now, this has been working fine, the composable viewModel() function was always returning the same existing instance of the Fragment's ViewModel.

The problems came when we needed the reference of a ViewModel scoped to an Activity on the composable:

We create the ViewModel on the Activity:

class MainActivity : AppCompatActivity() {

    private val viewModel by lazyViewModel { MainViewModel() }
    ...
}

Get a reference for the MainActivity's ViewModel on the Fragment like

class MainFragment : Fragment() {

    private val viewModel: MainViewModel by viewModels(::requireActivity)
    ...
}

We get the reference of the ViewModel for composables as shown above (item B)

By doing so the Fragment has the same instance of the Activity's but the composable doesn't.

My questions is,
would it be possible to get the reference of the Activity's ViewModel inside the composable? For now I'm simply passing down the Fragment's ViewModel as a parameter to my main composable screen.


问:
How does scikit-learn handle multiple n_jobs arguments?
I have made a pipeline in scikit-learn that looks as follows:

```<code>estimators2 = [
    ('tfidf', TfidfVectorizer(tokenizer=lambda string: string.split())),
    ('clf', SGDClassifier(n_jobs=13, early_stopping=True, class_weight='balanced'))
]
parameters2 = {
    'tfidf__min_df': np.arange(10, 30, 10),
    'tfidf__max_df': np.arange(0.75, 0.9, 0.05),
    'tfidf__ngram_range': [(1, 1), (2, 2), (3, 3)],
    'clf__alpha': (1e-2, 1e-3)
}

p2 = Pipeline(estimators2)
grid2 = RandomizedSearchCV(p2, param_distributions=parameters2,
                           scoring='balanced_accuracy', n_iter=20, cv=3, n_jobs=13, pre_dispatch='n_jobs')
</code>```

In this pipeline, there is two times the argument n_jobs? How are they handled by scikit-learn?

答:
You can try using accelerated implementations of algorithms that introduce their internal threading - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

scikit-learn-intelex is based on TBB for parallelization and can utilize entire system for accelerated algorithms. So you would be able to go without joblib parallelization while still getting better performance.

First install package

pip install scikit-learn-intelex
```
<p>And then add in your python script</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
patch_sklearn()
</code>```

Body:
I have made a pipeline in scikit-learn that looks as follows:

estimators2 = [
    ('tfidf', TfidfVectorizer(tokenizer=lambda string: string.split())),
    ('clf', SGDClassifier(n_jobs=13, early_stopping=True, class_weight='balanced'))
]
parameters2 = {
    'tfidf__min_df': np.arange(10, 30, 10),
    'tfidf__max_df': np.arange(0.75, 0.9, 0.05),
    'tfidf__ngram_range': [(1, 1), (2, 2), (3, 3)],
    'clf__alpha': (1e-2, 1e-3)
}

p2 = Pipeline(estimators2)
grid2 = RandomizedSearchCV(p2, param_distributions=parameters2,
                           scoring='balanced_accuracy', n_iter=20, cv=3, n_jobs=13, pre_dispatch='n_jobs')

In this pipeline, there is two times the argument n_jobs? How are they handled by scikit-learn?

Body:
You can try using accelerated implementations of algorithms that introduce their internal threading - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

scikit-learn-intelex is based on TBB for parallelization and can utilize entire system for accelerated algorithms. So you would be able to go without joblib parallelization while still getting better performance.

First install package

pip install scikit-learn-intelex

And then add in your python script

from sklearnex import patch_sklearn
patch_sklearn()


问:
How do you remove and add then a class to two list elements on click
How do you remove and add a class to both the below lists simultaneously for the coresponding list item in order on click. eg click the 2nd list item and the change occurs on the second list item on the other list

At the moment using the below I can only get this to happen on one of the li tags on any one click

```<code>$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function() {
      $("ul.control li").removeClass("active");
      $(this).addClass("active");
      $("ul.markers li").removeClass("active");
      $(this).addClass("active");

});
</code>```

Here is the markup for the two lists

```<code><ul id="tabs" class="control">
    <li class="active"><a href="#tab1">Tab1</a></li>
    <li><a href="#tab2">Tab2</a></li>
    <li><a href="#tab3">Tab3</a></li>
    <li><a href="#tab4">Tab4</a></li>
</ul>

<ul id="tabs" class="markers">
  <li class="active">1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
</code>```

Many thanks in advance for any help.

答:
First of all, IDs have to be unique. So in your case I would "convert" the id "tabs" to a CSS class.

But now to your question. That is how I would solve it:

```<code>$(function() {
    var lists = $(".control, .markers");

    lists.click(function(ev) {
        var el = (ev.srcElement.nodeName === "LI" ? ev.srcElement : ev.srcElement.parentNode);
        $(".active",lists).removeClass("active");
        $("li:eq(" + $(el).index() + ")", lists).addClass("active");
    });
});
</code>```

example on jsfiddle.net

Body:
How do you remove and add a class to both the below lists simultaneously for the coresponding list item in order on click. eg click the 2nd list item and the change occurs on the second list item on the other list

At the moment using the below I can only get this to happen on one of the li tags on any one click

$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function() {
      $("ul.control li").removeClass("active");
      $(this).addClass("active");
      $("ul.markers li").removeClass("active");
      $(this).addClass("active");

});

Here is the markup for the two lists

Tab1

Tab2

Tab3

Tab4

1

2

3

4

Many thanks in advance for any help.

Body:
First of all, IDs have to be unique. So in your case I would "convert" the id "tabs" to a CSS class.

But now to your question. That is how I would solve it:

$(function() {
    var lists = $(".control, .markers");

    lists.click(function(ev) {
        var el = (ev.srcElement.nodeName === "LI" ? ev.srcElement : ev.srcElement.parentNode);
        $(".active",lists).removeClass("active");
        $("li:eq(" + $(el).index() + ")", lists).addClass("active");
    });
});

example on jsfiddle.net


问:
Aligning elements left and center with flexbox
I'm using flexbox to align my child elements. What I'd like to do is center one element and leave the other aligned to the very left. Normally I would just set the left element using margin-right: auto. The problem is that pushes the center element off center. Is this possible without using absolute positioning?

HTML & CSS

#parent {
  align-items: center;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  width: 500px;
}
#left {
  margin-right: auto;
}
#center {
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
</div></code>```

答:
Solution 1: give 50% width to center element and use justify-content:space-between

#parent {
  display: flex;
  justify-content: space-between;
}

#center {
  flex-basis: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
</div></code>```

Solution 2: Add one dummy element and hide it.

#parent {
  display: flex;
  justify-content: space-between;
}

#right {
 visibility:hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
  <span id="right">Right</span>
</div></code>```

Body:
I'm using flexbox to align my child elements. What I'd like to do is center one element and leave the other aligned to the very left. Normally I would just set the left element using margin-right: auto. The problem is that pushes the center element off center. Is this possible without using absolute positioning?

HTML & CSS

#parent {
  align-items: center;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  width: 500px;
}
#left {
  margin-right: auto;
}
#center {
  margin: auto;
}

  Left
  Center

Body:
Solution 1: give 50% width to center element and use justify-content:space-between

#parent {
  display: flex;
  justify-content: space-between;
}

#center {
  flex-basis: 50%;
}

<div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
</div>

Solution 2: Add one dummy element and hide it.

#parent {
  display: flex;
  justify-content: space-between;
}

#right {
 visibility:hidden;
}

<div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
  <span id="right">Right</span>
</div>


问:
'java.io.IOException: parseAlgParameters failed: PBE AlgorithmParameters not available' on RHEL 8.3 with FIPS mode enabled
Recently, I discovered that on one of the servers, Java 11 has been updated:

```<code>From: java-11-openjdk-headless-1:11.0.13.0.8-1.el8_4.x86_64
To:   java-11-openjdk-headless-1:11.0.14.0.9-2.el8_5.x86_64
</code>```

So from 11.0.13.0.8-1 to 11.0.14.0.9-2. Host is running on RHEL 8.3 with FIPS mode enabled. Before, this code snippet was able to create JKS keystore (public certificate and private key, + CA certificate) and truststore (CA certificate) for Kafka:

```<code>openssl pkcs12 -export -in kafka.cer -inkey kafka.key -out kafka.p12 -name kafka -password pass:(...)
keytool -importkeystore -srckeystore kafka.p12 -destkeystore kafka.keystore.jks -srcstoretype pkcs12 -alias kafka -deststoretype pkcs12 -srcstorepass (...) -deststorepass (...) -noprompt
keytool -keystore kafka.keystore.jks -alias CARoot -import -file ca.cer -storepass (...) -keypass (...) -noprompt
keytool -keystore kafka.truststore.jks -alias CARoot -import -file ca.cer -storepass (...) -keypass (...) -noprompt
</code>```

Certificate and private key are obtained from different source, RSA 2048-bit. Signature algorithm is: SHA-256 with RSA.

After update of OpenJDK 11, I no longer can generate the keystore with above snippet due to the following error:

```<code>keytool error: java.io.IOException: parseAlgParameters failed: PBE AlgorithmParameters not available
java.io.IOException: parseAlgParameters failed: PBE AlgorithmParameters not available
        at java.base/sun.security.pkcs12.PKCS12KeyStore.parseAlgParameters(PKCS12KeyStore.java:839)
        at java.base/sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:2074)
        at java.base/sun.security.util.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:222)
        at java.base/java.security.KeyStore.load(KeyStore.java:1479)
        at java.base/java.security.KeyStore.getInstance(KeyStore.java:1807)
        at java.base/java.security.KeyStore.getInstance(KeyStore.java:1687)
        at java.base/sun.security.tools.keytool.Main.doCommands(Main.java:928)
        at java.base/sun.security.tools.keytool.Main.run(Main.java:412)
        at java.base/sun.security.tools.keytool.Main.main(Main.java:405)
Caused by: java.security.NoSuchAlgorithmException: PBE AlgorithmParameters not available
        at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
        at java.base/java.security.Security.getImpl(Security.java:730)
        at java.base/java.security.AlgorithmParameters.getInstance(AlgorithmParameters.java:158)
        at java.base/sun.security.pkcs12.PKCS12KeyStore.parseAlgParameters(PKCS12KeyStore.java:833)
        ... 8 more
</code>```

I can confirm that downgrading Java to previous version allows the above snippet to be executed. I am wondering what happened in between versions that right now the keystore cannot be generated?

Does anybody have experience with running Kafka with TLS on RHEL with FIPS? Is there any other keystore that can be generated for Kafka to enable TLS on a FIPS-enabled host?

Thanks in advance for your reply.

答:
Although I don't have RHEL (or anything else enforcing FIPS) this might be due to the fact Java crypto (specifically SunJCE) implements AlgorithmParameters PBE as an alias for PBEwithMD5andDES (I'm guessing because that's the only implemented scheme from PKCS5v1/PBES1 where this parameter form was defined, although PKCS12 adopted it) and MD5 is not Approved.

If so, you should be able to avoid this by creating the PKCS12 with PBES2 encryption, which uses different parameters. (Any PKCS12 created by 8u301 11.0.12 or 16 up should already use PBES2 by default in all environments; for lower versions the key default was SHA1and3-keyTripleDES which AFAIK is Approved but the cert default was SHA1and40-bitRC2 which isn't, so I'm not sure what does or should happen under FIPS. To increase the confusion, Java calls them SHA1andDESede and SHA1andRC2_40.)

In OpenSSL through 1.1.1 pkcs12 -export add -keypbe aes-256-cbc -certpbe aes-256-cbc or similar (because those are 'plain' ciphers not true PBE schemes, OpenSSL automatically uses PBES2 for them). Or, OpenSSL 3.0.x automatically uses these PBES2 schemes (and presumably higher versions will, when they come along).

BTW, your -importkeystore step doesn't really accomplish anything; although you use the name .jks on the output it actually is PKCS12 just like the input. It may be defaulting to different encryption, but if the input was acceptable to keytool it would be equally acceptable to any sane Java program. And since j9 in 2017 you don't need -srcstoretype for a file-based store because it's now automatic, and you don't need -deststoretype pkcs12 because it's the default.

Body:
Recently, I discovered that on one of the servers, Java 11 has been updated:

From: java-11-openjdk-headless-1:11.0.13.0.8-1.el8_4.x86_64
To:   java-11-openjdk-headless-1:11.0.14.0.9-2.el8_5.x86_64

So from 11.0.13.0.8-1 to 11.0.14.0.9-2. Host is running on RHEL 8.3 with FIPS mode enabled. Before, this code snippet was able to create JKS keystore (public certificate and private key, + CA certificate) and truststore (CA certificate) for Kafka:

openssl pkcs12 -export -in kafka.cer -inkey kafka.key -out kafka.p12 -name kafka -password pass:(...)
keytool -importkeystore -srckeystore kafka.p12 -destkeystore kafka.keystore.jks -srcstoretype pkcs12 -alias kafka -deststoretype pkcs12 -srcstorepass (...) -deststorepass (...) -noprompt
keytool -keystore kafka.keystore.jks -alias CARoot -import -file ca.cer -storepass (...) -keypass (...) -noprompt
keytool -keystore kafka.truststore.jks -alias CARoot -import -file ca.cer -storepass (...) -keypass (...) -noprompt

Certificate and private key are obtained from different source, RSA 2048-bit. Signature algorithm is: SHA-256 with RSA.

After update of OpenJDK 11, I no longer can generate the keystore with above snippet due to the following error:

keytool error: java.io.IOException: parseAlgParameters failed: PBE AlgorithmParameters not available
java.io.IOException: parseAlgParameters failed: PBE AlgorithmParameters not available
        at java.base/sun.security.pkcs12.PKCS12KeyStore.parseAlgParameters(PKCS12KeyStore.java:839)
        at java.base/sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:2074)
        at java.base/sun.security.util.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:222)
        at java.base/java.security.KeyStore.load(KeyStore.java:1479)
        at java.base/java.security.KeyStore.getInstance(KeyStore.java:1807)
        at java.base/java.security.KeyStore.getInstance(KeyStore.java:1687)
        at java.base/sun.security.tools.keytool.Main.doCommands(Main.java:928)
        at java.base/sun.security.tools.keytool.Main.run(Main.java:412)
        at java.base/sun.security.tools.keytool.Main.main(Main.java:405)
Caused by: java.security.NoSuchAlgorithmException: PBE AlgorithmParameters not available
        at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
        at java.base/java.security.Security.getImpl(Security.java:730)
        at java.base/java.security.AlgorithmParameters.getInstance(AlgorithmParameters.java:158)
        at java.base/sun.security.pkcs12.PKCS12KeyStore.parseAlgParameters(PKCS12KeyStore.java:833)
        ... 8 more

I can confirm that downgrading Java to previous version allows the above snippet to be executed. I am wondering what happened in between versions that right now the keystore cannot be generated?

Does anybody have experience with running Kafka with TLS on RHEL with FIPS? Is there any other keystore that can be generated for Kafka to enable TLS on a FIPS-enabled host?

Thanks in advance for your reply.


问:
How to find and replace all occurrences of a substring in a string?
I need to search a string and edit the formatting of it.

So far I can replace the first occurrence of the string, but I am unable to do so with the next occurrences of this string.

This is what I have working, sort of:

```<code>if(chartDataString.find("*A") == string::npos){ return;}
else{chartDataString.replace(chartDataString.find("*A"), 3,"[A]\n");}
</code>```

If it doesn't find the string, nothing prints at all, so that's not good.

I know I need to loop through the entire string chartDataString and replace all occurrences.  I know there are a lot of similar posts to this but I don't understand  (like this Replace substring with another substring C++)

I've also tried to do something like this to loop over the string:

```<code>string toSearch = chartDataString;
string toFind = "*A:";
for (int i = 0; i<toSearch.length() - toFind.length(); i++){
   if(toSearch.substr(i, toFind.length()) == toFind){
       chartDataString.replace(chartDataString.find(toFind), 3, "[A]\n");
   }
}
</code>```

EDIT
taking into consideration suggestions, this in theory should work, but I don't know why it doesn't

```<code>size_t startPos=0;
string myString = "*A";
while(string::npos != (startPos = chartDataString.find(myString, startPos))){
    chartDataString.replace(chartDataString.find(myString, startPos), 3, "*A\n");
    startPos = startPos + myString.length();
}
</code>```

答:
Below is a complete display of how find, string::replace and replace working.

There is no direct implementation of replaceAll in cpp.

We can tweak replace to perform our intent:

```<code>string original = "A abc abc abc A";
string test = original;
cout << endl << "Original string: " << original;  //output: A abc abc abc A

//FINDING INDEX WHERE QUERY SUBSTRING FOUND
int index = test.find("a");
cout << endl << "index: " << index; //output: 2
int outOfBoundIndex = test.find("xyz");
cout << endl << "outOfBoundIndex: " << outOfBoundIndex; //output: -1

//REPLACE SINGLE OCCURENCES
string queryString = "abc";
int queryStringLength = queryString.size();
index = test.find(queryString);
if(index > -1 && index < (test.size() - 1))
    test.replace(index, queryStringLength, "xyz");

cout << endl << endl << "first occurrence \'abc\' replaced to \'xyz\': " << test;  //output: A xyz abc abc A

//REPLACE ALL OCCURRENCES
test = original;

//there is a cpp utility function to replace all occurrence of single character. It will not work for replacing all occurences of string.
replace(test.begin(), test.end(), 'a', 'X');
cout << endl << endl << "Replacing all occurences of character \'a\' with \'X\': " << test;  //output: A Xbc Xbc Xbc A
test = original;
index = test.find("abc");
while(index > -1 && index < (test.size() - 1)){
    test.replace(index, queryStringLength, "xyz");
    index = test.find("abc");
}
cout << endl << "replaceAll implementation: " << test;  //output: A xyz xyz xyz A
</code>```

Body:
I need to search a string and edit the formatting of it.

So far I can replace the first occurrence of the string, but I am unable to do so with the next occurrences of this string.

This is what I have working, sort of:

if(chartDataString.find("*A") == string::npos){ return;}
else{chartDataString.replace(chartDataString.find("*A"), 3,"[A]\n");}

If it doesn't find the string, nothing prints at all, so that's not good.

I know I need to loop through the entire string chartDataString and replace all occurrences.  I know there are a lot of similar posts to this but I don't understand  (like this Replace substring with another substring C++)

I've also tried to do something like this to loop over the string:

string toSearch = chartDataString;
string toFind = "*A:";
for (int i = 0; i<toSearch.length() - toFind.length(); i++){
   if(toSearch.substr(i, toFind.length()) == toFind){
       chartDataString.replace(chartDataString.find(toFind), 3, "[A]\n");
   }
}

EDIT
taking into consideration suggestions, this in theory should work, but I don't know why it doesn't

size_t startPos=0;
string myString = "*A";
while(string::npos != (startPos = chartDataString.find(myString, startPos))){
    chartDataString.replace(chartDataString.find(myString, startPos), 3, "*A\n");
    startPos = startPos + myString.length();
}

Body:
Below is a complete display of how find, string::replace and replace working.

There is no direct implementation of replaceAll in cpp.

We can tweak replace to perform our intent:

string original = "A abc abc abc A";
string test = original;
cout << endl << "Original string: " << original;  //output: A abc abc abc A

//FINDING INDEX WHERE QUERY SUBSTRING FOUND
int index = test.find("a");
cout << endl << "index: " << index; //output: 2
int outOfBoundIndex = test.find("xyz");
cout << endl << "outOfBoundIndex: " << outOfBoundIndex; //output: -1

//REPLACE SINGLE OCCURENCES
string queryString = "abc";
int queryStringLength = queryString.size();
index = test.find(queryString);
if(index > -1 && index < (test.size() - 1))
    test.replace(index, queryStringLength, "xyz");

cout << endl << endl << "first occurrence \'abc\' replaced to \'xyz\': " << test;  //output: A xyz abc abc A

//REPLACE ALL OCCURRENCES
test = original;

//there is a cpp utility function to replace all occurrence of single character. It will not work for replacing all occurences of string.
replace(test.begin(), test.end(), 'a', 'X');
cout << endl << endl << "Replacing all occurences of character \'a\' with \'X\': " << test;  //output: A Xbc Xbc Xbc A
test = original;
index = test.find("abc");
while(index > -1 && index < (test.size() - 1)){
    test.replace(index, queryStringLength, "xyz");
    index = test.find("abc");
}
cout << endl << "replaceAll implementation: " << test;  //output: A xyz xyz xyz A


问:
How to perform logging in ConfigureServices method of Startup.cs in ASP.NET Core 5.0
Constructor injection of a logger into Startup works in earlier versions of ASP.NET Core because a separate DI container is created for the Web Host. As of now only one container is created for Generic Host, see the breaking change announcement.

Startup.cs

```<code>public class Startup
{
    /// <summary> The configuration. </summary>
    public IConfiguration Configuration { get; }

    /// <summary> The web host environment. </summary>
    public IWebHostEnvironment WebHostEnvironment { get; }

    public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
    {
        Configuration = configuration;
        WebHostEnvironment = webHostEnvironment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddServices(Configuration);    // This is a custom method, that adds multiple services to the container.
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) =>
    app.UseComponents(env, Configuration, logger);
}
</code>```

Now as per the MSDN, I have modified my Startup.cs as follows:

```<code>public class Startup
{
    /// <summary> The configuration. </summary>
    public IConfiguration Configuration { get; }

    public ILogger<Startup> Logger { get; set; }

    /// <summary> The web host environment. </summary>
    public IWebHostEnvironment WebHostEnvironment { get; }

    public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
    {
        Configuration = configuration;
        WebHostEnvironment = webHostEnvironment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton((container) =>
        {
            var logger = container.GetRequiredService<ILogger<MyService>>();
            return new Startup(Configuration, WebHostEnvironment) { Logger = logger };
        });    // I know this is incorrect, but that my question- how do I correctly access logger in here?
        services.AddServices(Configuration, Logger);    // Logger => null
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) =>
    app.UseComponents(env, Configuration, logger);
}
</code>```

StartupExtension.ConfigureServices.cs

```<code>public static partial class StartupExtension
{
    #region Internal Method
    /// <summary> Adds all the services required by the DemoUsageApp. </summary>
    /// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
    /// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
    /// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
    /// <returns></returns>
    internal static IServiceCollection AddServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {
        services.AddDotNetCoreServices(configuration, logger);
        services.AddCrossCuttingServices(configuration, logger);

        return services;
    }
    #endregion Internal Method

    #region Private Methods
    /// <summary> Adds .NET Core services. </summary>
    /// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
    /// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
    /// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
    /// <returns></returns>
    private static IServiceCollection AddDotNetCoreServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {
        logger.LogInformation("----  Adding .NET Core components  ----");

        services.AddMvc();
        services.AddControllers();

        logger.LogInformation("----  Successfully added .NET Core components  ----");

        return services;
    }

    /// <summary> Adds Cross-Cutting services. </summary>
    /// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
    /// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
    /// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
    /// <returns></returns>
    private static IServiceCollection AddCrossCuttingServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {
        logger.LogInformation("----  Adding Cross-Cutting components  ----");

        services.AddSql(configuration, logger);    //This is a extension methods, that adds Sql services (which are also completely custom) to the application.

        logger.LogInformation("----  Successfully added Cross-Cutting components  ----");

        return services;
    }
    #endregion Private Methods
}
</code>```

Question- How do I access Logger in ConfigureServices method of Startup.cs so that I can pass it to other custom extension methods that add custom services to the container?

NOTE: Solution requested for Microsoft and Serilog Logger (optional).

Update 1: As @MathewBeck pointed out in his 2nd comment, I already have the following structure of Program.cs:

```<code>public class Program
{
    #region Public Methods
    /// <summary> Main method, the entry-point of the application. </summary>
    /// <param name="args">The args <see cref="string[]"/></param>
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        var logger = host.Services.GetRequiredService<ILogger<Program>>();
        logger.LogInformation("Host created.");

        host.Run();
    }

    /// <summary> Creates the host builder. </summary>
    /// <param name="args">The args <see cref="string[]"/></param>
    /// <returns></returns>
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            //.ConfigureLogging(loggingBuilder =>
            //{
            //    loggingBuilder.ClearProviders();
            //    loggingBuilder.AddConsole();
            //    loggingBuilder.AddDebug();
            //    loggingBuilder.AddEventLog();
            //    loggingBuilder.AddEventSourceLogger();
            //})
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                webBuilder.UseConfiguration(GetConfiguration());
            });
    #endregion Public Methods

    #region Private Methods
    /// <summary> Gets the configuration. </summary>
    /// <returns></returns>
    private static IConfiguration GetConfiguration()
    {
        var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", true, true)
            .AddJsonFile($"appsettings.{env}.json", true, true);

        return builder.Build();
    }
    #endregion Private Methods
}
</code>```

答:
ASP.NET 5.0

I have used Control Startup class activation feature introduced in .NET 5.0 -

To quote MSDN documentation -

An additional UseStartup overload has been added that lets an app provide a factory method for controlling Startup class activation. Controlling Startup class activation is useful to pass additional parameters to Startup that are initialized along with the host

```<code>public class Program
{
    public static async Task Main(String[] args)
    {
        var loggerFactory = LoggerFactory
            .Create(builder =>
            {
                builder.ClearProviders();
                builder.AddConsole();
            });
        var logger = loggerFactory.CreateLogger<Program>();
        var host = Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup(context => new Startup(ILogger<Program> logger, /*based on the ctor of startup one can pass the required arguments here*/)
            })
            .Build();

        await host.RunAsync();
    }
}
</code>```

Body:
Constructor injection of a logger into Startup works in earlier versions of ASP.NET Core because a separate DI container is created for the Web Host. As of now only one container is created for Generic Host, see the breaking change announcement.

Startup.cs

public class Startup
{
    ///  The configuration.
    public IConfiguration Configuration { get; }

    ///  The web host environment.
    public IWebHostEnvironment WebHostEnvironment { get; }

    public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
    {
        Configuration = configuration;
        WebHostEnvironment = webHostEnvironment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddServices(Configuration);    // This is a custom method, that adds multiple services to the container.
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) =>
    app.UseComponents(env, Configuration, logger);
}

Now as per the MSDN, I have modified my Startup.cs as follows:

public class Startup
{
    ///  The configuration.
    public IConfiguration Configuration { get; }

    public ILogger<Startup> Logger { get; set; }

    ///  The web host environment.
    public IWebHostEnvironment WebHostEnvironment { get; }

    public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
    {
        Configuration = configuration;
        WebHostEnvironment = webHostEnvironment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton((container) =>
        {
            var logger = container.GetRequiredService<ILogger<MyService>>();
            return new Startup(Configuration, WebHostEnvironment) { Logger = logger };
        });    // I know this is incorrect, but that my question- how do I correctly access logger in here?
        services.AddServices(Configuration, Logger);    // Logger => null
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) =>
    app.UseComponents(env, Configuration, logger);
}

StartupExtension.ConfigureServices.cs

public static partial class StartupExtension
{
    #region Internal Method
    ///  Adds all the services required by the DemoUsageApp.
    /// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
    /// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
    /// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
    /// <returns></returns>
    internal static IServiceCollection AddServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {
        services.AddDotNetCoreServices(configuration, logger);
        services.AddCrossCuttingServices(configuration, logger);

        return services;
    }
    #endregion Internal Method

    #region Private Methods
    ///  Adds .NET Core services.
    /// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
    /// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
    /// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
    /// <returns></returns>
    private static IServiceCollection AddDotNetCoreServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {
        logger.LogInformation("----  Adding .NET Core components  ----");

        services.AddMvc();
        services.AddControllers();

        logger.LogInformation("----  Successfully added .NET Core components  ----");

        return services;
    }

    ///  Adds Cross-Cutting services.
    /// <param name="services">The services, <see cref="IServiceCollection"/>.</param>
    /// <param name="configuration">The configuration, <see cref="IConfiguration"/>.</param>
    /// <param name="logger">The logger, <see cref="ILogger{Startup}"/>.</param>
    /// <returns></returns>
    private static IServiceCollection AddCrossCuttingServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {
        logger.LogInformation("----  Adding Cross-Cutting components  ----");

        services.AddSql(configuration, logger);    //This is a extension methods, that adds Sql services (which are also completely custom) to the application.

        logger.LogInformation("----  Successfully added Cross-Cutting components  ----");

        return services;
    }
    #endregion Private Methods
}

Question- How do I access Logger in ConfigureServices method of Startup.cs so that I can pass it to other custom extension methods that add custom services to the container?

NOTE: Solution requested for Microsoft and Serilog Logger (optional).

Update 1: As @MathewBeck pointed out in his 2nd comment, I already have the following structure of Program.cs:

public class Program
{
    #region Public Methods
    ///  Main method, the entry-point of the application.
    /// <param name="args">The args <see cref="string[]"/></param>
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        var logger = host.Services.GetRequiredService<ILogger<Program>>();
        logger.LogInformation("Host created.");

        host.Run();
    }

    ///  Creates the host builder.
    /// <param name="args">The args <see cref="string[]"/></param>
    /// <returns></returns>
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            //.ConfigureLogging(loggingBuilder =>
            //{
            //    loggingBuilder.ClearProviders();
            //    loggingBuilder.AddConsole();
            //    loggingBuilder.AddDebug();
            //    loggingBuilder.AddEventLog();
            //    loggingBuilder.AddEventSourceLogger();
            //})
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                webBuilder.UseConfiguration(GetConfiguration());
            });
    #endregion Public Methods

    #region Private Methods
    ///  Gets the configuration.
    /// <returns></returns>
    private static IConfiguration GetConfiguration()
    {
        var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", true, true)
            .AddJsonFile($"appsettings.{env}.json", true, true);

        return builder.Build();
    }
    #endregion Private Methods
}

Body:
ASP.NET 5.0

I have used Control Startup class activation feature introduced in .NET 5.0 -

To quote MSDN documentation -

An additional UseStartup overload has been added that lets an app provide a factory method for controlling Startup class activation. Controlling Startup class activation is useful to pass additional parameters to Startup that are initialized along with the host

public class Program
{
    public static async Task Main(String[] args)
    {
        var loggerFactory = LoggerFactory
            .Create(builder =>
            {
                builder.ClearProviders();
                builder.AddConsole();
            });
        var logger = loggerFactory.CreateLogger<Program>();
        var host = Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup(context => new Startup(ILogger<Program> logger, /*based on the ctor of startup one can pass the required arguments here*/)
            })
            .Build();

        await host.RunAsync();
    }
}


问:
netty dependency brings old version
I am using a recent dependency of grpc-netty.
The issue is it is bringing older versions of io.netty dependencies (4.1.27)
I looked in the grpc-netty project and the used io.netty dependency version is 4.1.63.
Any idea what can be the reason for having this dependencies bring older versions of transitive dependencies?

Thank you

答:
```<code><dependency>
    <groupId>xxx</groupId>
    <artifactId>xxx</artifactId>
    <exclusions>
       <exclusion>
         <groupId>io.netty</groupId>
         <artifactId>netty-codec-http2</artifactId>
       </exclusion>
    </exclusions>
</dependency>
</code>```

You need exclusions tag

Title: netty dependency brings old version

Body:
<dependency>
    <groupId>xxx</groupId>
    <artifactId>xxx</artifactId>
    <exclusions>
       <exclusion>
         <groupId>io.netty</groupId>
         <artifactId>netty-codec-http2</artifactId>
       </exclusion>
    </exclusions>
</dependency>

You need exclusions tag


问:
Docker : How to run a Bokeh server inside Docker container and expose the output
I have a Bokeh python code that imports data from excel file and projects my supplier locations on Google maps. The excel file is stored on my local host in the folder C:\Python where the Python code is picking it from.This code works fine with I open command prompt and use the command "Bokeh serve --show Gmaps_Bokeh.py".
However, when I build the docker file to do that same and map the port 5006 to 2000 I cannot see anything in my browser.

I have created a Docker folder on my host that contains Gmaps_Bokeh.py , Sid.xls and Dockerfile and in my Dockerfile I am copying all the contents in /Python directory of container.

The docker terminal shows the following

```<code>$ docker run -p 5006:2000 sid
2019-11-03 20:38:43,329 Starting Bokeh server version 1.3.4 (running on
Tornado 6.0.3)
2019-11-03 20:38:43,334 Bokeh app running at:
http://localhost:5006/Gmaps_Bokeh
2019-11-03 20:38:43,334 Starting Bokeh server with process id: 1
</code>```

Dockerfile contents

```<code> FROM python
 RUN pip install bokeh
 RUN pip install gmaps
 RUN pip install pandas
 RUN pip install xlrd
 WORKDIR /Python
 COPY . /Python
 EXPOSE 2000
 CMD ["bokeh", "serve","/Python/Gmaps_Bokeh.py"]
</code>```

答:
It seems to me you have your ports messed up. Think of the host and container ports separately.

As seen in the console output once you run the container inside your container, you have bokeh which publishes on port 5006 (here localhost is from the point of view of the container). This is what you need to expose in your Dockerfile (thus it should be EXPOSE 5006). So far you're inside the container and don't know anything about port 2000.

If you want to expose your container port 5006 (where bokeh serves) to a host system port 2000, you would do this as in @Tony's comment using -p 2000:5006 in your docker run command and look for it with http://localhost:2000 in your browser.

One important clarification that should glue all this together: localhost when requested from the host system (where you run your browser) is different from localhost when requested from the container (where the bokeh console output comes from).

Body:
I have a Bokeh python code that imports data from excel file and projects my supplier locations on Google maps. The excel file is stored on my local host in the folder C:\Python where the Python code is picking it from.This code works fine with I open command prompt and use the command "Bokeh serve --show Gmaps_Bokeh.py".
However, when I build the docker file to do that same and map the port 5006 to 2000 I cannot see anything in my browser.

I have created a Docker folder on my host that contains Gmaps_Bokeh.py , Sid.xls and Dockerfile and in my Dockerfile I am copying all the contents in /Python directory of container.

The docker terminal shows the following

$ docker run -p 5006:2000 sid
2019-11-03 20:38:43,329 Starting Bokeh server version 1.3.4 (running on
Tornado 6.0.3)
2019-11-03 20:38:43,334 Bokeh app running at:
http://localhost:5006/Gmaps_Bokeh
2019-11-03 20:38:43,334 Starting Bokeh server with process id: 1

Dockerfile contents

 FROM python
 RUN pip install bokeh
 RUN pip install gmaps
 RUN pip install pandas
 RUN pip install xlrd
 WORKDIR /Python
 COPY . /Python
 EXPOSE 2000
 CMD ["bokeh", "serve","/Python/Gmaps_Bokeh.py"]


问:
c++ const convert

Possible Duplicate:

  why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

I have a function:

```<code>bool isCirclePolygonIntersection(const Point*, const int*, const Point*,
                                 const Point**, const int*);
</code>```

and I'm trying to call it like this:

```<code>isCirclePolygonIntersection(p, &r, poly_coord, poly, &poly_size)
</code>```

where poly defined like this:

```<code>Point** poly = new Point*[poly_size];
</code>```

and there is a compiler error when I'm trying to compile it:

```<code>error C2664: 'isCirclePolygonIntersection' : cannot convert parameter 4 from 'Point **' to 'const Point **'
1>          Conversion loses qualifiers
</code>```

from what I've learned is that you cannot give const argument to function when a function expects a non const argument, but it's fine otherwise.
Does anyone knows what is the problem??
Thanks.

答:
An implicit conversion from Point** to const Point** would open a hole in the type system, hence there is no such conversion in C++.

For details, see Why am I getting an error converting a Foo** → Foo const**?

Changing const Point** to const Point * const * will fix your problem.

By the way, why the additional indirection? That is, why do you use an array of pointers? I would suggest a std::vector<Point> instead. Or is Point a polymorphic base class?

Title: c++ const convert

Body:
Possible Duplicate:

  why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

I have a function:

bool isCirclePolygonIntersection(const Point*, const int*, const Point*,
                                 const Point**, const int*);

and I'm trying to call it like this:

isCirclePolygonIntersection(p, &r, poly_coord, poly, &poly_size)

where poly defined like this:

Point** poly = new Point*[poly_size];

and there is a compiler error when I'm trying to compile it:

error C2664: 'isCirclePolygonIntersection' : cannot convert parameter 4 from 'Point **' to 'const Point **'
1>          Conversion loses qualifiers

from what I've learned is that you cannot give const argument to function when a function expects a non const argument, but it's fine otherwise.
Does anyone knows what is the problem??
Thanks.


问:
Useless Kotlin delegate
I'm trying to understand why we have feature as delegate in Kotlin.
This example is similar to wiki example https://en.wikipedia.org/wiki/Delegation_pattern

Check this commented fragment, I don't need it for using area function on bounds so why we should use  : ClosedShape by bounds ?

```<code>interface ClosedShape {
    fun area(): Int
}

class Rectangle(val width: Int, val height: Int) : ClosedShape {
    override fun area() = width * height
}

class Window(private val bounds: ClosedShape)  /*: ClosedShape by bounds */ {
    init {
        bounds.area()
    }
}
</code>```

答:
I don't need it for using area function on bounds

The point is not about whether you can use area on bounds or not. Sure, if all you want to do is to call bounds.area(), you don't need : ClosedShape by bounds.

Here's a little hypothetical situation, based on ClosedShape and Window, where using the by syntax to implement an interface is helpful.

Notice how a Window is bounded by a Rectangle. Wouldn't it make sense for Window to also be a ClosedShape? If we have a function that works on ClosedShape, wouldn't it be nice if we can directly pass a Window to it, rather than passing window.bounds?

```<code>fun printArea(shape: ClosedShape) {
    println(shape.area())
}

// we could write this:
printArea(window)

// rather than:
printArea(window.bounds)
</code>```

This would mean that Window would implement ClosedShape. We could implement it without using a delegate:

```<code>class Window(private val bounds: ClosedShape) : ClosedShape {
    override fun area() = bounds.area()
}
</code>```

But that would be very tedious if ClosedShape had many more methods than area. Imagine having to implement 20 methods, all of which just calls that same method on bounds:

```<code>class Window(private val bounds: ClosedShape) : ClosedShape {
    override fun area() = bounds.area()
    override fun perimeter() = bounds.perimeter()
    override fun numberOfSides() = bounds.numberOfSides()
    override fun isConcave() = bounds.isConcave()
    override fun contains(point: Point) = bounds.contains(point)
    override fun methodWithALotOfParameters(x: Int, y: String, z: Boolean) = bounds.methodWithALotOfParameters(x, y, z)
    override fun color() = bounds.color()
    // and so on...
}
</code>```

You can also imagine how horrible this would get, if the delegate isn't as short as bounds, but something like bounds.someProperty.anotherProperty.

The by syntax eliminates all that tedious work, letting you just write:

```<code>class Window(private val bounds: ClosedShape) : ClosedShape by bounds
</code>```

And that's it! You can now use any Window as a ClosedShape.

Title: Useless Kotlin delegate

Body:
I'm trying to understand why we have feature as delegate in Kotlin.
This example is similar to wiki example https://en.wikipedia.org/wiki/Delegation_pattern

Check this commented fragment, I don't need it for using area function on bounds so why we should use  : ClosedShape by bounds ?

interface ClosedShape {
    fun area(): Int
}

class Rectangle(val width: Int, val height: Int) : ClosedShape {
    override fun area() = width * height
}

class Window(private val bounds: ClosedShape)  /*: ClosedShape by bounds */ {
    init {
        bounds.area()
    }
}

Body:
I don't need it for using area function on bounds

The point is not about whether you can use area on bounds or not. Sure, if all you want to do is to call bounds.area(), you don't need : ClosedShape by bounds.

Here's a little hypothetical situation, based on ClosedShape and Window, where using the by syntax to implement an interface is helpful.

Notice how a Window is bounded by a Rectangle. Wouldn't it make sense for Window to also be a ClosedShape? If we have a function that works on ClosedShape, wouldn't it be nice if we can directly pass a Window to it, rather than passing window.bounds?

fun printArea(shape: ClosedShape) {
    println(shape.area())
}

// we could write this:
printArea(window)

// rather than:
printArea(window.bounds)

This would mean that Window would implement ClosedShape. We could implement it without using a delegate:

class Window(private val bounds: ClosedShape) : ClosedShape {
    override fun area() = bounds.area()
}

But that would be very tedious if ClosedShape had many more methods than area. Imagine having to implement 20 methods, all of which just calls that same method on bounds:

class Window(private val bounds: ClosedShape) : ClosedShape {
    override fun area() = bounds.area()
    override fun perimeter() = bounds.perimeter()
    override fun numberOfSides() = bounds.numberOfSides()
    override fun isConcave() = bounds.isConcave()
    override fun contains(point: Point) = bounds.contains(point)
    override fun methodWithALotOfParameters(x: Int, y: String, z: Boolean) = bounds.methodWithALotOfParameters(x, y, z)
    override fun color() = bounds.color()
    // and so on...
}

You can also imagine how horrible this would get, if the delegate isn't as short as bounds, but something like bounds.someProperty.anotherProperty.

The by syntax eliminates all that tedious work, letting you just write:

class Window(private val bounds: ClosedShape) : ClosedShape by bounds

And that's it! You can now use any Window as a ClosedShape.


问:
Excel not detecting alternating duplicates in three columns
I have a spreadsheet with three columns: year, name1, name2. Each entry represents a pair. I've noticed that there are duplicates in the data that Excel does not detect, namely:

So the only pair in year 1986 is ABW-AIA. However, in the data I've got two entries: ABW-AIA and AIA-ABW. I would like to remove either ABW-AIA or AIA-ABW, so I am only left with one entry. I would like to repeat the same process with many other pairs. How can I do this?

I'll greatly appreciate any help!

答:
If you have O365, you could follow this approach.  There may very well be a more elegant way (i.e. a single step) but this did work for me.

If your data is in columns A to C (and for my test data, I only had 4 rows worth) ...

Cell E1 = =TRANSPOSE(SORT(TRANSPOSE(A1:C1),,1)) (fill down)

Cell I1 = =UNIQUE(E1:G4)


问:
Django - Variable cached with "with" template tag isn't evaluated
I'm following along this article, and I have a form like this:

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
    <legend>
{{ question.question_text }}
</legend>
    {% if error_message %}
{{ error_message }}
{% endif %}
    {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
        {{ choice.choice_text }}

    {% endfor %}
</fieldset>
<input type="submit" value="Vote">
</form>
```

I figured, since there are multiple instances of "choice{{ forloop.counter }}", I can cache it with with template tag and use it as a variable. But as you can see, the variable forloop.counter inside the with template tag isn't evaluated.

The expected result was this:

How can I fix this?

答:
The variable using {{ }} cannot be used inside {% %}Built-in tag[Django-doc] but we can use the variable inside {% %} if it is already available in the template. So we have to get the value before and we can set that value using with[Django-doc]. But the value you are getting is dynamic with every loop you get new value with {{forloop.counter}} and the same thing we cannot use {{ }} inside {% %}.So you can concatenate the values differently i.e. {{forloop.counter}} and choice.
For concatenate we can use add Built-in filter[Django-doc] as documented

Adds the argument to the value. This filter will first try to coerce both values to integers. If this fails, it’ll attempt to add the values together anyway. This will work on some data types (strings, list, etc.) and fail on others.

But the problem with add is  as Warned as

Strings that can be coerced to integers will be summed, not concatenated,

So we have to convert the {{forloop.counter}} to string first before concatenation and we can use stringformat[Django-doc] for that and store the value and use that value as

```<code>{% for choice in question.choice_set.all %}
    {% with counter=forloop.counter|stringformat:"s" %}
    {% with choice_id="choice"|add:counter %}
    <input type="radio" name="choice" id={{choice_id}} value="{{ choice.id }}">
    <label for={{choice_id}}>{{ choice.choice_text }}</label><br>
    {% endwith %}
    {% endwith %}
{% endfor %}
</code>```

Body:
I'm following along this article, and I have a form like this:

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
    <legend>
{{ question.question_text }}
</legend>
    {% if error_message %}
{{ error_message }}
{% endif %}
    {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
        {{ choice.choice_text }}

    {% endfor %}
</fieldset>
<input type="submit" value="Vote">
</form>

I figured, since there are multiple instances of "choice{{ forloop.counter }}", I can cache it with with template tag and use it as a variable. But as you can see, the variable forloop.counter inside the with template tag isn't evaluated.

The expected result was this:

How can I fix this?

Body:
The variable using {{ }} cannot be used inside {% %}Built-in tag[Django-doc] but we can use the variable inside {% %} if it is already available in the template. So we have to get the value before and we can set that value using with[Django-doc]. But the value you are getting is dynamic with every loop you get new value with {{forloop.counter}} and the same thing we cannot use {{ }} inside {% %}.So you can concatenate the values differently i.e. {{forloop.counter}} and choice.
For concatenate we can use add Built-in filter[Django-doc] as documented

Adds the argument to the value. This filter will first try to coerce both values to integers. If this fails, it’ll attempt to add the values together anyway. This will work on some data types (strings, list, etc.) and fail on others.

But the problem with add is  as Warned as

Strings that can be coerced to integers will be summed, not concatenated,

So we have to convert the {{forloop.counter}} to string first before concatenation and we can use stringformat[Django-doc] for that and store the value and use that value as

{% for choice in question.choice_set.all %}
    {% with counter=forloop.counter|stringformat:"s" %}
    {% with choice_id="choice"|add:counter %}
    <input type="radio" name="choice" id={{choice_id}} value="{{ choice.id }}">
    <label for={{choice_id}}>{{ choice.choice_text }}</label><br>
    {% endwith %}
    {% endwith %}
{% endfor %}


问:
How to Send this kind of Json Response
How To Send the Kind of api response when i am sending then the first letter become small
I want response key VehicleNumber but i am getting vehicleNumber
the First letter small i ma getting

```<code>    "status": "1",
    "data": [
        {
            "VehicleNumber": "DL1ZD1455",
            "Address": "gurgaon sector 48,sector 48, gurgaon",
            "Latitude": 28.42682,
            "Longitude": 77.03228,
            "Alerttime": "dd/MM/yyyy HH:mm:ss",
            "Speed": "21.000",
        }
    ],
    "message": "Success"
}```

i am getting this kind of response
```

{
"status": "1",
"data": [
{
"address": "Lucknow Airport Terminal,Uttar Pradesh",
"vehicleNumber": "DL1PD3231",
"speed": "0",
"latitude": 26.76383,
"longitude": 80.88558,
"alerttime": "2021-12-19 17:16:41"
}
],
"message": "Success"
}

答:
You can extend com.fasterxml.jackson.databind.PropertyNamingStrategy and override translate method and do something like this:</p>
```<code>public static class UpperCaseJsonStrategy extends PropertyNamingStrategyBase {
    @Override
    public String translate(String input) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
}
</code>```

Title: How to Send this kind of Json Response

Body:
How To Send the Kind of api response when i am sending then the first letter become small
I want response key VehicleNumber but i am getting vehicleNumber
the First letter small i ma getting

    "status": "1",
    "data": [
        {
            "VehicleNumber": "DL1ZD1455",
            "Address": "gurgaon sector 48,sector 48, gurgaon",
            "Latitude": 28.42682,
            "Longitude": 77.03228,
            "Alerttime": "dd/MM/yyyy HH:mm:ss",
            "Speed": "21.000",
        }
    ],
    "message": "Success"
}```

i am getting this kind of response

{
"status": "1",
"data": [
{
"address": "Lucknow Airport Terminal,Uttar Pradesh",
"vehicleNumber": "DL1PD3231",
"speed": "0",
"latitude": 26.76383,
"longitude": 80.88558,
"alerttime": "2021-12-19 17:16:41"
}
],
"message": "Success"
}

Body:
You can extend com.fasterxml.jackson.databind.PropertyNamingStrategy and override translate method and do something like this:

public static class UpperCaseJsonStrategy extends PropertyNamingStrategyBase {
    @Override
    public String translate(String input) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
}


问:
Losing focus of NSView after setFrame of NSWindow
I am switching my NSWindow from normal mode to fullscreen, by setting its frame (I know there is a method for the view to go fullscreen, but it needs to be this way)

In my NSOpenGLView I am tracking the onMouseMove event...

After switching to fullscreen (or back), I have to click the view (inside window), to receive the mouseMove event. It looks like it is going out of focus, but I don't understand why (I am just using setFrame) and how to make it focused again, without the user needing to click the window.

Code in my NSOpenGLView (NSView):

```<code>    if (!fullscreenOn) {
        //!switch to fullscreen mode
        NSRect mainDisplayRect = [[[self window] screen] frame];
        [[self window] setStyleMask:NSBorderlessWindowMask];

        [[self window] setFrame:[[self window] frameRectForContentRect:mainDisplayRect] display:YES animate:NO];

        [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock];

        fullscreenOn = YES;

    } else {

        [[self window] setStyleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTexturedBackgroundWindowMask];

        [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationDefault];

        ... some code for the right size ...
        [[self window] setFrame:frame display: YES animate: YES];

        fullscreenOn = NO;
    }
</code>```

答: the problem was with setting [[self window] setStyleMask:NSBorderlessWindowMask]; which cause this behaviour... making the window borderless by default fixed the problem</p>

Body:
I am switching my NSWindow from normal mode to fullscreen, by setting its frame (I know there is a method for the view to go fullscreen, but it needs to be this way)

In my NSOpenGLView I am tracking the onMouseMove event...

After switching to fullscreen (or back), I have to click the view (inside window), to receive the mouseMove event. It looks like it is going out of focus, but I don't understand why (I am just using setFrame) and how to make it focused again, without the user needing to click the window.

Code in my NSOpenGLView (NSView):

    if (!fullscreenOn) {
        //!switch to fullscreen mode
        NSRect mainDisplayRect = [[[self window] screen] frame];
        [[self window] setStyleMask:NSBorderlessWindowMask];

        [[self window] setFrame:[[self window] frameRectForContentRect:mainDisplayRect] display:YES animate:NO];

        [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock];

        fullscreenOn = YES;

    } else {

        [[self window] setStyleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSTexturedBackgroundWindowMask];

        [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationDefault];

        ... some code for the right size ...
        [[self window] setFrame:frame display: YES animate: YES];

        fullscreenOn = NO;
    }


问:
Why I still get the 200 response status code instead of 404?
I just making delete query to mysql with sequelize.

```<code>const model = require('../../../config/model/index');
const controller = {};

controller.drop =  async function(req, res) {
  try {
    await model.activitys.destroy({
      where: {
        id: req.params.id
      }
    })
    check_id = model.activitys.findAll({
      where: {
        id: req.params.id
      }
    })
    if(check_id!=null){
      res.status(200).json({
        status: "Success",
        message: "Success",
        data: {}
      })
    }else{
      res.status(404).json({
        status: "Not Found",
        message: `Activity with ID ${id} Not Found`,
        data: {}
      })
    }
  } catch (error) {
    res.status(404).json({
      status: "Error",
      message: error.message
    })
  }
}

module.exports = controller;
</code>```

I want to delete the data on DB from id parameters, it's work for deleting the data. But when I try to delete by id that not exist in my DB, it's still get the 200 status code.

How to make that will return 404 status code if there's no data exists in DB ?

答:
If you want to check if a single record exists in DB then use findOne or findByPk instead of findAll. findAll always returns an array (either empty or not) and that means it's always not equal to null:

check_id = model.activitys.findOne({
      where: {
        id: req.params.id
      }
    })
```

Body:
I just making delete query to mysql with sequelize.

const model = require('../../../config/model/index');
const controller = {};

controller.drop =  async function(req, res) {
  try {
    await model.activitys.destroy({
      where: {
        id: req.params.id
      }
    })
    check_id = model.activitys.findAll({
      where: {
        id: req.params.id
      }
    })
    if(check_id!=null){
      res.status(200).json({
        status: "Success",
        message: "Success",
        data: {}
      })
    }else{
      res.status(404).json({
        status: "Not Found",
        message: `Activity with ID ${id} Not Found`,
        data: {}
      })
    }
  } catch (error) {
    res.status(404).json({
      status: "Error",
      message: error.message
    })
  }
}

module.exports = controller;

I want to delete the data on DB from id parameters, it's work for deleting the data. But when I try to delete by id that not exist in my DB, it's still get the 200 status code.

How to make that will return 404 status code if there's no data exists in DB ?


问:
array.push doesn't seem to work on Nodejs Express
I'm using a local database and Google API to build my own API, but I can't push objects into the "channels" array. I want the response to look something like this:

```<code>    [
       { id: 0, url: 'gwJ-mrP6_Ng', channelname: 'name1' },
       { id: 1, url: 'YPYwU2jeXIc', channelname: 'name2' },
       { id: 3, url: 'z3U0udLH974', channelname: 'name3' },
       { id: 2, url: 'AUHlDIuMLNY', channelname: 'name4' },
       { id: 4, url: 'vQEH_EksBbo', channelname: 'name5' }
    ]
</code>```

And this is my code which I'm struggling with:

```<code>    app.get('/api/video/channels', (req, res) => {
        var channels = [];
        db.query(`SELECT video_url FROM videos`, (err, data) => {
            if (err) console.log(err);
            else {
                data.map((v, i) =>
                    axios.get(`https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=${v.video_url}&key=${process.env.YT_API_KEY}`)
                        .then(res => channels.push({ "id": i, "url": v.video_url, "channelname": res.data.items[0].snippet.channelTitle }))
                )
                res.send(channels);
            }
        })
    })
</code>```

console.log works, but the response always shows a blank array ( [] ).
What is the problem with my code?

Thanks for your attention and help.

答:
You have to use await to fulfill the result. try to change something like the below:

app.get('/api/video/channels', (req, res) => {
  var channels = [];
  db.query(`SELECT video_url FROM videos`, async (err, data) => {
    if (err) console.log(err);
    else {
      for (let i = 0; i < data.length; ++i) {
        let res = await axios.get(`https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=${data[i].video_url}&key=${process.env.YT_API_KEY}`)
        channels.push({ "id": i, "url": data[i].video_url, "channelname": res.data.items[0].snippet.channelTitle });
      }
      res.send(channels);
    }
  })
})
```

Body:
I'm using a local database and Google API to build my own API, but I can't push objects into the "channels" array. I want the response to look something like this:

    [
       { id: 0, url: 'gwJ-mrP6_Ng', channelname: 'name1' },
       { id: 1, url: 'YPYwU2jeXIc', channelname: 'name2' },
       { id: 3, url: 'z3U0udLH974', channelname: 'name3' },
       { id: 2, url: 'AUHlDIuMLNY', channelname: 'name4' },
       { id: 4, url: 'vQEH_EksBbo', channelname: 'name5' }
    ]

And this is my code which I'm struggling with:

    app.get('/api/video/channels', (req, res) => {
        var channels = [];
        db.query(`SELECT video_url FROM videos`, (err, data) => {
            if (err) console.log(err);
            else {
                data.map((v, i) =>
                    axios.get(`https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=${v.video_url}&key=${process.env.YT_API_KEY}`)
                        .then(res => channels.push({ "id": i, "url": v.video_url, "channelname": res.data.items[0].snippet.channelTitle }))
                )
                res.send(channels);
            }
        })
    })

console.log works, but the response always shows a blank array ( [] ).
What is the problem with my code?

Thanks for your attention and help.


问:
Mocha.js - How to save a global variable?
I'm working with Mocha.js for testing in a Node.js - Express.js - Firebase

I need a token from Firebase to access the API endpoints, I have a before hook in all my files, but after about 250 tests, probably calling the authentication endpoint multiple times, I'm getting rate limited by firebase.

I want to get the token once and use it in all my tests.

The tests are spread in different files, I have an index.js that requires them all.
I'm aware of Root Level Hooks, but how can I save the token and use it in all my separate files?

Thanks!

答:
Create a JSON file in your test root directory.

Import the file.

Append a token property with the token value.

Then import it anywhere to access the token property .


问:
I want to ignore default preferences set by the user in react-native
I am making an app in react-native but wherever I'm using text I want that to be constant as I set it.
For e.g - I don't want my text to be scaled if the user has increased the default font size of his device. In one word - I just want to all the default user preferences/settings on his device.

Thanks!

答:
Use allowFontScaling prop

```<code><Text allowFontScaling={false} />
</code>```

The doc

Edit:

I don't know any way to configure the setting for the whole app. The best I could come up with is creating your own Text component and changing the Text import statement.

```<code>export function MyText(props) {
    return <Text {...props} allowFontScaling={false} />
}
</code>```

import { Text } from "react-native" // change this line to
import { MyText as Text } from "../location/to/your/component"
```

Body:
Use allowFontScaling prop

<Text allowFontScaling={false} />

The doc

Edit:

I don't know any way to configure the setting for the whole app. The best I could come up with is creating your own Text component and changing the Text import statement.

export function MyText(props) {
    return <Text {...props} allowFontScaling={false} />
}

import { Text } from "react-native" // change this line to
import { MyText as Text } from "../location/to/your/component"


问:
Why does -INT_MIN = INT_MIN in a signed, two's complement representation?
I still haven't found a reason why the lowest signed negative number doesn't have an equivalent signed positive number?
I mean in a 3 digit binary number for simplicity
100 is -4? but we can't have a positive 4 in signed format because we can't. It overflows.
So how do we know two's complement 1000 is -4 1000 0000 is  -128 and so on? We have no original positive number</p>

答:
This answer is just a summary.

In N bit 2's complement:

The negative range is [-2^{N-1}, -1] which has cardinality 2^{N}/2.

The positive range is [0, 2^{N-1}-1] which again has cardinality 2^{N}/2.

and the overall range [-2^{N-1}, 2^{N-1}-1] must have the cardinality 2^{N}. Performing N bit operations on any number out of this range will cause an overflow.

And notice that when all the number in this signed range is added with a bias 2^{N-1} we get an unsigned range [0, 2^{N-1}].


问:
Microsoft Access can't save design changes because another user has the file open... but I am the only user?
Just a little background: I am using Access 2010 to create forms and VBA code in an Access 2003 format database. For some reason, Access 2007 format databases always corrupt on me when I make changes and save them with a particular group of objects, but that's for another discussion.

When writing VBA code in this Access 2003 database, any time my code breaks (via breakpoint or an unhandled error) and I make a correction, Access tells me that it can't save back to the database because another user has it open. However, I am the only user working on the database; this is a local copy of the database and it's sitting on my desktop.

The LDB file can't be deleted because Access is using it. When I first load the database, I see my machine name and "Admin" when opening the LDB in a text or hex editor. After a break, I see that plus a duplicate entry, but this time around "admin" has a lower-case "A."

Closing the database and reopening it fixes the problem but makes it needlessly cumbersome to debug my code. Anyone else encounter this issue and/or have a fix for it?

答: In your VBA Try checking that all your open Connections to the database are closed. Until the connection is open the LDB fill will be there.</p>


问:
I tried running my flutter app on an Emulator and it showed the following error
A problem occurred configuring root project 'android'.

Could not resolve all artifacts for configuration ':classpath'.
Could not resolve com.android.tools.build:gradle:4.1.0.
Required by:
project :
> Could not resolve com.android.tools.build:gradle:4.1.0.
> Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/4.1.0/gradle-4.1.0.pom'.
> Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/4.1.0/gradle-4.1.0.pom'.
> Remote host terminated the handshake

答:
To solve this I open the app in android studio for editing and the artifacts are automatically downloaded.

There might be other workarounds but this works for me.

How to open flutter app for editing?

https://stackoverflow.com/questions/60462318/cant-find-open-for-editing-in-android-studio#:~:text=Got%20to%20your,the%20IDE.%20Source.


问:
why qt application always new widgets instead of on stack?
there. I've seen this example from qt: https://doc.qt.io/qt-5/qtwidgets-widgets-calculator-example.html, and wonder why qt always create widgets with new instead of allocating on stack

```<code>Button *Calculator::createButton(const QString &text, const char *member)
{
    Button *button = new Button(text);
    connect(button, SIGNAL(clicked()), this, member);
    return button;
}
</code>```

create widget on stack is faster, and in this question: QT-specific difference of stack vs. heap attributes?
Mike's answer says that create on stack is perfectly fine, but why official documents use new mostly?

答:
This is simple: because you want the widget to live even after this function scope is finished and QObjects are not copyable. The following code does not work because you cannot copy the object.

```<code>Button Calculator::createButton(const QString &text)
{
    Button button(text); // allocated on stack, it is OK so far...
    return button; // nope, you cannot copy that! it does not compile.
}
</code>```

The following code does not work either because you would be passing a deleted object.

```<code>Button *Calculator::createButton(const QString &text)
{
  Button button(text); // allocated on stack, it is OK so far...
  return &button; // ... returning pointer, still OK...
  // Oh no! End of scope here, the object gets murdered now.
  // whoever holds the pointer to it, holds a dead, invalid object.
}
</code>```

The object gets deleted at the end of scope and you would be passing a pointer to freed, hence invalid memory.

The example you referred to

```<code>class Widget2 : public QWidget
{
Q_OBJECT
public:
    Widget2(QWidget* parent = nullptr);

private:
    QPushButton button;
};
</code>```

does not necessarily mean that the button is created on the stack. It depends on how the instance of Widget2 is created. If it is on the stack, then also button is on the stack. If it is newed on the heap, then also button is on the heap. The difference from the "normal" case where button is declared and kept as a pointer is that in the example above they are allocated together in one allocation. Yes, it is negligibly faster but it is just a premature optimization. Allocation of widgets will never ever be your bottleneck, believe me. Btw. most objects in Qt are implemented using PIMPL idiom to preserve binary compatibility, so they internally allocate their private objects on the heap anyway.

Yes, you can keep your button as a NON-pointer member. This is legal. But it is not wise. There is an issue with this approach: you must #include all the subwidgets in the header and you cannot forward-declare them. Which definitely makes you compile time longer. But that is not the main problem, you can wait a little. The bigger problem is that you are introducing building dependencies which makes your code less composable. Imagine you have your custom widgets split into multiple libraries - then everything what you #include in your headers visible to other modules also requires to be visible to these modules. This soon becomes unmanageable mess because you will not be able to hide/encapsulate implementation details. And the fact that your widget uses some button certainly is an implementation detail. Just keep as little details in your header as possible. Keeping a pointer (can be forward-declared) is definitely less of a burden than keeping a non-pointer member (must be #included!). Moreover if you keep a pointer, then you can use substitution principle and this pointer can actually point to any subclass instance. In little toy applications or school homeworks this does not matter but when you are designing a really large application wit lots of modules and submodules organized as libraries or when you are writing libraries which are to be used by others, then these things REALLY DO matter. This makes the difference between well maintainable and totally unmaintainable code.

In my practice I have encountered only two usecases where widgets are actually allocated on the stack. First is when they are created in main() where you can write:

```<code>int main() {
  QApplication app;
  MainWindow w; // it is really on the stack
  w.show();
  return app.exec();
  // here is the main window automatically destroyed
}
</code>```

Another case is when you open a display a modal dialog with a blocking event loop using exec().

```<code>void showSomeMessage() {
  QMessageBox box; // yes, we should set a parent here, for sake of simplicity I omitted it
  // etc. set text and button here
  box.exec(); // blocking here, we are waiting for user interaction
  // end of scope - we are done here, we do not need the message box any more
  // so it is perfectly fine it gets automatically deleted here
}
</code>```

These cases are perfectly fine. Actually, as you can see blocking exec() in both these cases, they are very similar.

Conclusion: it is better to declare member QObjects or QWidgets via pointers and always forward-declare them in your headers instead of #includeing their headers. This way you can design more composable, maintainable and future-proof code. You will not see any significant difference in small toy projects, but you will benefit from this good practice when your codebase grows larger. Even better habit is to keep them via QPointer (which a special Qt weak pointer), which has twofold benefit: 1) it is automatically initialized to nullptr and 2) when the objects gets destroyed, the pointer is automatically set to nullptr so you can easily check if it is alive. Plus QPointer provides implicit conversions to raw pointer so it does not affect the way you write your code. It is a very handy class.

Body:
there. I've seen this example from qt: https://doc.qt.io/qt-5/qtwidgets-widgets-calculator-example.html, and wonder why qt always create widgets with new instead of allocating on stack

Button *Calculator::createButton(const QString &text, const char *member)
{
    Button *button = new Button(text);
    connect(button, SIGNAL(clicked()), this, member);
    return button;
}

create widget on stack is faster, and in this question: QT-specific difference of stack vs. heap attributes?
Mike's answer says that create on stack is perfectly fine, but why official documents use new mostly?

Body:
This is simple: because you want the widget to live even after this function scope is finished and QObjects are not copyable. The following code does not work because you cannot copy the object.

Button Calculator::createButton(const QString &text)
{
    Button button(text); // allocated on stack, it is OK so far...
    return button; // nope, you cannot copy that! it does not compile.
}

The following code does not work either because you would be passing a deleted object.

Button *Calculator::createButton(const QString &text)
{
  Button button(text); // allocated on stack, it is OK so far...
  return &button; // ... returning pointer, still OK...
  // Oh no! End of scope here, the object gets murdered now.
  // whoever holds the pointer to it, holds a dead, invalid object.
}

The object gets deleted at the end of scope and you would be passing a pointer to freed, hence invalid memory.

The example you referred to

class Widget2 : public QWidget
{
Q_OBJECT
public:
    Widget2(QWidget* parent = nullptr);

private:
    QPushButton button;
};

does not necessarily mean that the button is created on the stack. It depends on how the instance of Widget2 is created. If it is on the stack, then also button is on the stack. If it is newed on the heap, then also button is on the heap. The difference from the "normal" case where button is declared and kept as a pointer is that in the example above they are allocated together in one allocation. Yes, it is negligibly faster but it is just a premature optimization. Allocation of widgets will never ever be your bottleneck, believe me. Btw. most objects in Qt are implemented using PIMPL idiom to preserve binary compatibility, so they internally allocate their private objects on the heap anyway.

Yes, you can keep your button as a NON-pointer member. This is legal. But it is not wise. There is an issue with this approach: you must #include all the subwidgets in the header and you cannot forward-declare them. Which definitely makes you compile time longer. But that is not the main problem, you can wait a little. The bigger problem is that you are introducing building dependencies which makes your code less composable. Imagine you have your custom widgets split into multiple libraries - then everything what you #include in your headers visible to other modules also requires to be visible to these modules. This soon becomes unmanageable mess because you will not be able to hide/encapsulate implementation details. And the fact that your widget uses some button certainly is an implementation detail. Just keep as little details in your header as possible. Keeping a pointer (can be forward-declared) is definitely less of a burden than keeping a non-pointer member (must be #included!). Moreover if you keep a pointer, then you can use substitution principle and this pointer can actually point to any subclass instance. In little toy applications or school homeworks this does not matter but when you are designing a really large application wit lots of modules and submodules organized as libraries or when you are writing libraries which are to be used by others, then these things REALLY DO matter. This makes the difference between well maintainable and totally unmaintainable code.

In my practice I have encountered only two usecases where widgets are actually allocated on the stack. First is when they are created in main() where you can write:

int main() {
  QApplication app;
  MainWindow w; // it is really on the stack
  w.show();
  return app.exec();
  // here is the main window automatically destroyed
}

Another case is when you open a display a modal dialog with a blocking event loop using exec().

void showSomeMessage() {
  QMessageBox box; // yes, we should set a parent here, for sake of simplicity I omitted it
  // etc. set text and button here
  box.exec(); // blocking here, we are waiting for user interaction
  // end of scope - we are done here, we do not need the message box any more
  // so it is perfectly fine it gets automatically deleted here
}

These cases are perfectly fine. Actually, as you can see blocking exec() in both these cases, they are very similar.

Conclusion: it is better to declare member QObjects or QWidgets via pointers and always forward-declare them in your headers instead of #includeing their headers. This way you can design more composable, maintainable and future-proof code. You will not see any significant difference in small toy projects, but you will benefit from this good practice when your codebase grows larger. Even better habit is to keep them via QPointer (which a special Qt weak pointer), which has twofold benefit: 1) it is automatically initialized to nullptr and 2) when the objects gets destroyed, the pointer is automatically set to nullptr so you can easily check if it is alive. Plus QPointer provides implicit conversions to raw pointer so it does not affect the way you write your code. It is a very handy class.


问:
Why R is Producing Weird and Not Total Row Number
I have a data frame produced from dput. Ideally, when running this dput, the test data frame should have 12 rows with row number 1:12. However, when running this, row 9 to 12 will be produced as row 5.1, 6.1, 7.1 and 8.1. I am sure that the contents of each row are different. I have sf geometry object for each row in this data frame. I am wondering what is the potential reason for causing this issue?

Thanks in advance!

example code (it's very long and exceed the limit of StackOverflow, I will put it into Google drive link):

https://drive.google.com/file/d/12XduN3iukE2VHu8yuf2ZfIwrlnu9wLjD/view?usp=sharing

screenshot of the problem rows:

答:
Isn't it because row names are explicitly named in your data frame?</p>
```<code>      .Names = character(0)
    ),
    row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "5.1", "6.1", "7.1", "8.1"),
    class = c("sf", "data.frame")
  ),
</code>```

Body:
Isn't it because row names are explicitly named in your data frame?

      .Names = character(0)
    ),
    row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "5.1", "6.1", "7.1", "8.1"),
    class = c("sf", "data.frame")
  ),


问:
How to convert List<String> to Map<String, Int> in Kotlin?
For example I have a list of strings like:

val list = listOf("a", "b", "a", "b" "a" "c")
and I need to convert it to a Map, where the strings are the keys and values are count of repetitions. So i have to got Map like [a = 3] [b = 2] [c = 1]

答:
```<code>val list = listOf("a", "b", "a", "b", "a", "c")

val result = list.groupingBy { it }.eachCount()

// result is Map<String, Int> looking like this: {a=3, b=2, c=1}
</code>```

Edit: for counts bigger than 1 add a filter condition to the map

```<code>val result = list.groupingBy { it }.eachCount().filter { it.value > 1 }

// result is now: {a=3, b=2}
</code>```

Body:
val list = listOf("a", "b", "a", "b", "a", "c")

val result = list.groupingBy { it }.eachCount()

// result is Map<String, Int> looking like this: {a=3, b=2, c=1}

Edit: for counts bigger than 1 add a filter condition to the map

val result = list.groupingBy { it }.eachCount().filter { it.value > 1 }

// result is now: {a=3, b=2}


问:
Is there a maximum limit to a python array? How to handle large data?
I'm using a simple python array to store words fetched from a file.

```<code>words=[]
words.append(new_word)
</code>```

This code snippet works perfectly for files with small word counts. However when running the script for larger files, it hangs after some time.(when the array length is around 111166 and the letter count inside the array is high)

Is there a maximum limit for a python array?
Is there a workaround to for this?

Thanks in advance.

答:
sys.maxsize is the maximum indices that lists can have:

An integer giving the maximum value a variable of type
Py_ssize_t can take. It’s usually 2**31 - 1 on a 32-bit platform and
2**63 - 1 on a 64-bit platform.

But apparently this shouldn't be your problem. There is something else going on with your code. sys.maxsize is much bigger than 111166.

.append() is also O(1) which doesn't slow your code. But when lists become larger than the place they have, new location in memory is allocated for them. This happens rarely.

Body:
I'm using a simple python array to store words fetched from a file.

words=[]
words.append(new_word)

This code snippet works perfectly for files with small word counts. However when running the script for larger files, it hangs after some time.(when the array length is around 111166 and the letter count inside the array is high)

Is there a maximum limit for a python array?
Is there a workaround to for this?

Thanks in advance.


问:
What am I doing wrong when trying to deserialize json into a c# list?
I have a Product class:

```<code>class Product
    {
        public string Name;
    }
</code>```

A Product List class:

```<code>   class ProductDataFile
    {
        public List<Product>? products;

    }
</code>```

And a class for loading json into these classes:

```<code>public void LoadProducts()
 {
   string jsonString = File.ReadAllText(FileLoc);
   ProductDataFile? productDataFile= JsonSerializer.Deserialize<ProductDataFile>(jsonString);
   var ProductName = productDataFile.products.First().Name;
 }

</code>```

This throws a "System.ArgumentNullException: Value cannot be null. (Parameter 'source')". I used the debugger and products is null, so that seems to be the problem.

My Json looks something like this:

```<code>{
  "listOfProducts": "List of products",
  "products": [
    {
      "Name": "product one"
    }
  ]
}
```
```

答:
The library Newtonsoft.json method of JsonSerializer.Deserialize need to use properties instead of fields, otherwise you might not Deserialize anything from your JSON data.

```<code>class Product
{
    public string Name {get;set;}
}

class ProductDataFile
{
    public List<Product>? products {get;set;}

}
</code>```

I would suggest you use json2csharp, it can easy to get the model by JSON and make sure it will be work.

Body:
I have a Product class:

class Product
    {
        public string Name;
    }

A Product List class:

   class ProductDataFile
    {
        public List<Product>? products;

    }

And a class for loading json into these classes:

public void LoadProducts()
 {
   string jsonString = File.ReadAllText(FileLoc);
   ProductDataFile? productDataFile= JsonSerializer.Deserialize<ProductDataFile>(jsonString);
   var ProductName = productDataFile.products.First().Name;
 }

This throws a "System.ArgumentNullException: Value cannot be null. (Parameter 'source')". I used the debugger and products is null, so that seems to be the problem.

My Json looks something like this:

{
  "listOfProducts": "List of products",
  "products": [
    {
      "Name": "product one"
    }
  ]
}
```

Body:
The library Newtonsoft.json method of JsonSerializer.Deserialize need to use properties instead of fields, otherwise you might not Deserialize anything from your JSON data.

class Product
{
    public string Name {get;set;}
}

class ProductDataFile
{
    public List<Product>? products {get;set;}

}

I would suggest you use json2csharp, it can easy to get the model by JSON and make sure it will be work.