问:
Android build failing on AppCenter but building fine on Android studio
When I run my Android build from my Android studio it builds absolutely file.

When I run the same source which is checked into github from AppCenter it fails with the following error on Gradle.

Does anyone have any clue as to why this would be happening?

============================================================================== Task         : Gradle Description  : Build using a Gradle wrapper
  script Version      : 1.128.0 Author       : Microsoft Corporation
  Help         : More
  Information
  ============================================================================== SYSTEMVSSCONNECTION exists true
  [command]/Users/vsts/agent/2.148.1/work/1/s/android/gradlew
  -DMOBILECENTER_BUILD_VERSION=17 -DAPPCENTER_BUILD_VERSION=17 -p android clean :app:assembleDevKernelDebug Starting a Gradle Daemon
  (subsequent builds will be faster) Gradle 4.4 Parallel execution with
  configuration on demand is an incubating feature. Download
  https://jcenter.bintray.com/de/undercouch/gradle-download-task/2.0.0/gradle-download-task-2.0.0.pom
  Download
  https://dl.google.com/dl/android/maven2/com/android/tools/build/transform-api/2.0.0-deprecated-use-gradle-api/transform-api-2.0.0-deprecated-use-gradle-api.pom
  Resolved com.android.tools.build:gradle:3.1.4 in :classpath  Resolved
  com.google.gms:google-services:3.2.1 in :classpath  Resolved
  de.undercouch:gradle-download-task:2.0.0 in :classpath  Download
  https://jcenter.bintray.com/de/undercouch/gradle-download-task/2.0.0/gradle-download-task-2.0.0.jar
  Download
  https://dl.google.com/dl/android/maven2/com/android/tools/build/transform-api/2.0.0-deprecated-use-gradle-api/transform-api-2.0.0-deprecated-use-gradle-api.jar
  Project android at : is either no Android app project or build version
  has not been set to override. Skipping... Resolved
  com.android.tools.build:gradle:3.2.1 in
  :@react-native-community_netinfo:classpath  Project
  @react-native-community_netinfo at :@react-native-community_netinfo is
  either no Android app project or build version has not been set to
  override. Skipping... Download
  https://maven.fabric.io/public/io/fabric/tools/gradle/maven-metadata.xml
  Download
  https://maven.fabric.io/public/io/fabric/tools/gradle/1.28.1/gradle-1.28.1.pom
  Resolved io.fabric.tools:gradle:1.28.1 in :app:classpath  Download
  https://maven.fabric.io/public/io/fabric/tools/gradle/1.28.1/gradle-1.28.1.jar
  Could not find google-services.json while looking in
  [src/prod/min/sdk/dev/kernel/debug, src/prod/min/sdk/dev/debug,
  src/prod/min/sdk/dev/kernel, src/prod/min/sdk/dev/kernelDebug,
  src/prod/min/sdk/debug, src/prod/min/sdk/dev,
  src/prod/min/sdk/devDebug, src/prod/min/debug, src/prod/min/sdk,
  src/prod/min/sdkDebug, src/prodMinSdkDevKernel/debug,
  src/debug/prodMinSdkDevKernel, src/prod/debug, src/prod/min,
  src/prod/minDebug, src/prodMinSdkDevKernel, src/debug,
  src/prodMinSdkDevKernelDebug, src/prod, src/prodDebug]
  registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Could not find
  google-services.json while looking in
  [src/prod/min/sdk/dev/kernel/release, src/prod/min/sdk/dev/release,
  src/prod/min/sdk/dev/kernel, src/prod/min/sdk/dev/kernelRelease,
  src/prod/min/sdk/release, src/prod/min/sdk/dev,
  src/prod/min/sdk/devRelease, src/prod/min/release, src/prod/min/sdk,
  src/prod/min/sdkRelease, src/prodMinSdkDevKernel/release,
  src/release/prodMinSdkDevKernel, src/prod/release, src/prod/min,
  src/prod/minRelease, src/prodMinSdkDevKernel, src/release,
  src/prodMinSdkDevKernelRelease, src/prod, src/prodRelease]
  registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Could not find
  google-services.json while looking in
  [src/prod/min/sdk/prod/kernel/debug, src/prod/min/sdk/prod/debug,
  src/prod/min/sdk/prod/kernel, src/prod/min/sdk/prod/kernelDebug,
  src/prod/min/sdk/debug, src/prod/min/sdk/prod,
  src/prod/min/sdk/prodDebug, src/prod/min/debug, src/prod/min/sdk,
  src/prod/min/sdkDebug, src/prodMinSdkProdKernel/debug,
  src/debug/prodMinSdkProdKernel, src/prod/debug, src/prod/min,
  src/prod/minDebug, src/prodMinSdkProdKernel, src/debug,
  src/prodMinSdkProdKernelDebug, src/prod, src/prodDebug]
  registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Could not find
  google-services.json while looking in
  [src/prod/min/sdk/prod/kernel/release, src/prod/min/sdk/prod/release,
  src/prod/min/sdk/prod/kernel, src/prod/min/sdk/prod/kernelRelease,
  src/prod/min/sdk/release, src/prod/min/sdk/prod,
  src/prod/min/sdk/prodRelease, src/prod/min/release, src/prod/min/sdk,
  src/prod/min/sdkRelease, src/prodMinSdkProdKernel/release,
  src/release/prodMinSdkProdKernel, src/prod/release, src/prod/min,
  src/prod/minRelease, src/prodMinSdkProdKernel, src/release,
  src/prodMinSdkProdKernelRelease, src/prod, src/prodRelease]
  registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Could not find
  google-services.json while looking in
  [src/dev/min/sdk/dev/kernel/debug, src/dev/min/sdk/dev/debug,
  src/dev/min/sdk/dev/kernel, src/dev/min/sdk/dev/kernelDebug,
  src/dev/min/sdk/debug, src/dev/min/sdk/dev, src/dev/min/sdk/devDebug,
  src/dev/min/debug, src/dev/min/sdk, src/dev/min/sdkDebug,
  src/devMinSdkDevKernel/debug, src/debug/devMinSdkDevKernel,
  src/dev/debug, src/dev/min, src/dev/minDebug, src/devMinSdkDevKernel,
  src/debug, src/devMinSdkDevKernelDebug, src/dev, src/devDebug]
  registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Could not find
  google-services.json while looking in
  [src/dev/min/sdk/dev/kernel/release, src/dev/min/sdk/dev/release,
  src/dev/min/sdk/dev/kernel, src/dev/min/sdk/dev/kernelRelease,
  src/dev/min/sdk/release, src/dev/min/sdk/dev,
  src/dev/min/sdk/devRelease, src/dev/min/release, src/dev/min/sdk,
  src/dev/min/sdkRelease, src/devMinSdkDevKernel/release,
  src/release/devMinSdkDevKernel, src/dev/release, src/dev/min,
  src/dev/minRelease, src/devMinSdkDevKernel, src/release,
  src/devMinSdkDevKernelRelease, src/dev, src/devRelease]
  registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Could not find
  google-services.json while looking in
  [src/dev/min/sdk/prod/kernel/debug, src/dev/min/sdk/prod/debug,
  src/dev/min/sdk/prod/kernel, src/dev/min/sdk/prod/kernelDebug,
  src/dev/min/sdk/debug, src/dev/min/sdk/prod,
  src/dev/min/sdk/prodDebug, src/dev/min/debug, src/dev/min/sdk,
  src/dev/min/sdkDebug, src/devMinSdkProdKernel/debug,
  src/debug/devMinSdkProdKernel, src/dev/debug, src/dev/min,
  src/dev/minDebug, src/devMinSdkProdKernel, src/debug,
  src/devMinSdkProdKernelDebug, src/dev, src/devDebug]
  registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Could not find
  google-services.json while looking in
  [src/dev/min/sdk/prod/kernel/release, src/dev/min/sdk/prod/release,
  src/dev/min/sdk/prod/kernel, src/dev/min/sdk/prod/kernelRelease,
  src/dev/min/sdk/release, src/dev/min/sdk/prod,
  src/dev/min/sdk/prodRelease, src/dev/min/release, src/dev/min/sdk,
  src/dev/min/sdkRelease, src/devMinSdkProdKernel/release,
  src/release/devMinSdkProdKernel, src/dev/release, src/dev/min,
  src/dev/minRelease, src/devMinSdkProdKernel, src/release,
  src/devMinSdkProdKernelRelease, src/dev, src/devRelease]
  registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Project appcenter at
  :appcenter is either no Android app project or build version has not
  been set to override. Skipping... Project appcenter-analytics at
  :appcenter-analytics is either no Android app project or build version
  has not been set to override. Skipping... Project appcenter-crashes at
  :appcenter-crashes is either no Android app project or build version
  has not been set to override. Skipping... Resolved
  com.android.tools.build:gradle:3.1.4 in
  :react-native-vector-icons:classpath  Project
  react-native-vector-icons at :react-native-vector-icons is either no
  Android app project or build version has not been set to override.
  Skipping... WARNING: The specified Android SDK Build Tools version
  (26.0.3) is ignored, as it is below the minimum supported version
  (27.0.3) for Android Gradle Plugin 3.1.4. Android SDK Build Tools
  27.0.3 will be used. To suppress this warning, remove "buildToolsVersion '26.0.3'" from your build.gradle file, as each
  version of the Android Gradle Plugin now has a default version of the
  build tools.

FAILURE: Build failed with an exception.

What went wrong: Task 'assembleDevKernelDebug' not found in project ':app'.

Try: Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 42s Error:
  /Users/vsts/agent/2.148.1/work/1/s/android/gradlew failed with return
  code: 1
      at ChildProcess. (/Users/vsts/agent/2.148.1/work/_tasks/Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4/1.128.0/node_modules/vsts-task-lib/toolrunner.js:569:30)
      at emitTwo (events.js:106:13)
      at ChildProcess.emit (events.js:191:7)
      at maybeClose (internal/child_process.js:886:16)
      at Socket. (internal/child_process.js:342:11)
      at emitOne (events.js:96:13)
      at Socket.emit (events.js:188:7)
      at Pipe._handle.close [as _onclose] (net.js:497:12)

[error]Error: /Users/vsts/agent/2.148.1/work/1/s/android/gradlew failed with return code: 1

答:
You probably have invalid build variants. Go to your build.gradle, it should look like this.

```<code>  flavorDimensions 'remoteKernel'
  productFlavors {
    devKernel {
      dimension 'remoteKernel'
    }
    prodKernel {
      dimension 'remoteKernel'
    }
  }
</code>```

This will change again in the next version of expo.

Body:
You probably have invalid build variants. Go to your build.gradle, it should look like this.

  flavorDimensions 'remoteKernel'
  productFlavors {
    devKernel {
      dimension 'remoteKernel'
    }
    prodKernel {
      dimension 'remoteKernel'
    }
  }

This will change again in the next version of expo.


来源: stackexchange

问:
Python Writing over Serial Port as Hex not ASCII
I am trying to poll data from an instrument that uses ModBus protocol via pyserial. I need to know how to prevent pyserial from sending the command in ascii.

Here is what I have done:

Using RealTerm, I connected to the instrument and sent this command and hit "Send as Numbers": 0x33 0x03 0x9D 0xA4 0x00 0x02 0xAE 0x56. Sending this line as numbers was able to poll the data correctly: 33 03 04 BE CE 5C A8 94 99; for example, "BE CE 5C A8" translates to -0.4030, which is the number that the instrument shows on its screen.

Using RealTerm and the same command, if I hit "Send as ASCII", the polled data would be incorrect: 30 F8 04 33 CC 44 A0 04 48
16 78 B0 04 85 DA, which I cannot relate to the number shown on the instrument's screen.

Going back to Python and pyserial, when I tried writing over the serial port using serial.write("0x33 0x03 0x9D 0xA4 0x00 0x02 0xAE 0x56"), I got the same data as in step 2.

Therefore, it seems to me that serial.write() sends the command as ASCII. Does anyone know how I can send this data in a similar manner to RealTerm step 1?

答:
You can use bytes or byte array:</p>

```<code>msg = bytes.fromhex("33 03 9D A4 00 02 AE 56")
serial.write(msg)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use bytes or byte array:

msg = bytes.fromhex("33 03 9D A4 00 02 AE 56")
serial.write(msg)


问:
How to produce javax.faces.ViewState hidden field without 'id' and 'autocomplete' attributes
This is what I have in the output HTML document (produced by JSF 2.0/Mojarra 2.0.3):

```<code><input type="hidden" name="javax.faces.ViewState"
id="javax.faces.ViewState" value="4267906931114993858:-6309146738430577631"
autocomplete="off" />
</code>```

My document should be XHTML 1.1 compliant, where attribute autocomplete is not valid and id attribute is duplicated over all forms. How to instruct JSF to produce everything strictly compliant to XHTML?

答: The non unique use if the ID javax.faces.ViewState is a bug that appears Oracle will not fix. They have closed these tickets.  No workaround.</p>

ContentLicense: CC BY-SA 3.0

Body:
This is what I have in the output HTML document (produced by JSF 2.0/Mojarra 2.0.3):

<input type="hidden" name="javax.faces.ViewState"
id="javax.faces.ViewState" value="4267906931114993858:-6309146738430577631"
autocomplete="off" />

My document should be XHTML 1.1 compliant, where attribute autocomplete is not valid and id attribute is duplicated over all forms. How to instruct JSF to produce everything strictly compliant to XHTML?


问:
'Network unreachable' on Play Store published app, but debug version works
I cannot connect to my Chromecast Audio using the Play Store published version of my app, but I can on the USB-debugging version on the same phone. Both versions can access the network, i.e. they both successfully find the IP address of the Chromecast device.

Same phone, Chromecast, network and code. It's just the Play Store published APK/Bundle that cannot connect.

In the Logcat I see:

```<code>2019-05-27 11:05:12.753 9203-9370/? W/System.err: java.net.ConnectException: failed to connect to /192.168.100.109 (port 8009) from /:: (port 0): connect failed: ENETUNREACH (Network is unreachable)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:138)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:129)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:357)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:201)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:183)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.Socket.connect(Socket.java:616)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.connect(OpenSSLSocketImpl.java:263)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.connect(OpenSSLSocketImpl.java:250)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.y.connect(Unknown Source:55)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.y.d(Unknown Source:4)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.z.a(Unknown Source:28)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.z.j(Unknown Source:5)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.z.e(Unknown Source:0)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at [my app's name].j.e(Unknown Source:29)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at [my app's name].j.b(Unknown Source:0)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at [my app's name].f.run(Unknown Source:3)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at java.lang.Thread.run(Thread.java:784)
2019-05-27 11:05:12.754 9203-9370/? W/System.err: Caused by: android.system.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at libcore.io.Linux.connect(Native Method)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:126)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:152)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:130)
</code>```

Clearly, my app can access the network as it finds the AVR/Chromecast Audio's IP address (192.168.100.109). I have also given it INTERNET permission in the manifest. I am also using minifyEnabled true and shrinkResources true in my build.gradle file.

I am using ChromeCast Java API v2 for convenience, rather than the official Cast SDK, if this makes any difference.

EDIT: Solved. It was the option minifyEnabled true in the build.gradle (Module: app) file (i.e. ProGuard) not liking the ChromeCast Java API v2 library.

答:
Enabling the option minifyEnabled true in the build.gradle (Module: app) file was the problem. ProGuard and the ChromeCast Java API v2 library don't work well together, so one needs to add exclusions to the proguard-rules.pro file if one wants to use the minifyEnabled option:

```<code>-keep class su.litvak.chromecast.**
-keepclassmembers class su.litvak.chromecast.** {*;}
</code>```

Many thanks to the accepted answer to this question by user random.

Body:
I cannot connect to my Chromecast Audio using the Play Store published version of my app, but I can on the USB-debugging version on the same phone. Both versions can access the network, i.e. they both successfully find the IP address of the Chromecast device.

Same phone, Chromecast, network and code. It's just the Play Store published APK/Bundle that cannot connect.

In the Logcat I see:

2019-05-27 11:05:12.753 9203-9370/? W/System.err: java.net.ConnectException: failed to connect to /192.168.100.109 (port 8009) from /:: (port 0): connect failed: ENETUNREACH (Network is unreachable)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:138)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:129)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:357)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:201)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:183)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at java.net.Socket.connect(Socket.java:616)
2019-05-27 11:05:12.753 9203-9370/? W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.connect(OpenSSLSocketImpl.java:263)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.connect(OpenSSLSocketImpl.java:250)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.y.connect(Unknown Source:55)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.y.d(Unknown Source:4)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.z.a(Unknown Source:28)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.z.j(Unknown Source:5)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at f.a.a.a.a.z.e(Unknown Source:0)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at [my app's name].j.e(Unknown Source:29)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at [my app's name].j.b(Unknown Source:0)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at [my app's name].f.run(Unknown Source:3)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at java.lang.Thread.run(Thread.java:784)
2019-05-27 11:05:12.754 9203-9370/? W/System.err: Caused by: android.system.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at libcore.io.Linux.connect(Native Method)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:126)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:152)
2019-05-27 11:05:12.754 9203-9370/? W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:130)

Clearly, my app can access the network as it finds the AVR/Chromecast Audio's IP address (192.168.100.109). I have also given it INTERNET permission in the manifest. I am also using minifyEnabled true and shrinkResources true in my build.gradle file.

I am using ChromeCast Java API v2 for convenience, rather than the official Cast SDK, if this makes any difference.

EDIT: Solved. It was the option minifyEnabled true in the build.gradle (Module: app) file (i.e. ProGuard) not liking the ChromeCast Java API v2 library.

Body:
Enabling the option minifyEnabled true in the build.gradle (Module: app) file was the problem. ProGuard and the ChromeCast Java API v2 library don't work well together, so one needs to add exclusions to the proguard-rules.pro file if one wants to use the minifyEnabled option:

-keep class su.litvak.chromecast.**
-keepclassmembers class su.litvak.chromecast.** {*;}

Many thanks to the accepted answer to this question by user random.


问:
Set the maximum size for a boost priority queue
I am trying to find top n items of a list that gets populated dynamically. I thought priority-queue would be a good way to go about this. Since I need only top n, there is no point in storing anything more than the 'n' items required for my calculation. I am unable to find anything in the boost library that seems to be able to set the limit for the priority queue

I tried using the reserve(element_count) function. The doc said that the function is used to "reserve space for the element_count elements". But that did not work the way I thought it would

This is some sample code that I am writing. This is NOT THE USE CASE though.

int main()
{
        int maxSize = 2; // Priority Queue (pq) is expected to hold a maximum of 2 elements at any time
        boost::heap::priority_queue<int> pq; // Declaration
        pq.reserve(maxSize); // I assumed this would reserve space only for 2 elements and anything more would over write the existing ones based on comparison
        pq.push(3);
        pq.push(2);
        pq.push(1); // Push should fail
        cout << "Size = " <<pq.size() << " Max Size = " << (int)pq.max_size();
        for (int i=0; i<maxSize; i++)
        {
                int a = pq.top();
                pq.pop();
                cout << a <<"\n";
        }
        return 0;
}
```

I expected the result to be:

Size = 2 Max Size = 2

3

2

But what I get is:

Size = 3 Max Size = -1

3

2

What am I missing?

答: reserve doesn't work the way you think it does. It just pre-allocates (reserves) space for the items. If more items are added greater than what was reserved, then it will increase the capacity to accomodate the new items.

Body:
I am trying to find top n items of a list that gets populated dynamically. I thought priority-queue would be a good way to go about this. Since I need only top n, there is no point in storing anything more than the 'n' items required for my calculation. I am unable to find anything in the boost library that seems to be able to set the limit for the priority queue

I tried using the reserve(element_count) function. The doc said that the function is used to "reserve space for the element_count elements". But that did not work the way I thought it would

This is some sample code that I am writing. This is NOT THE USE CASE though.

int main()
{
        int maxSize = 2; // Priority Queue (pq) is expected to hold a maximum of 2 elements at any time
        boost::heap::priority_queue<int> pq; // Declaration
        pq.reserve(maxSize); // I assumed this would reserve space only for 2 elements and anything more would over write the existing ones based on comparison
        pq.push(3);
        pq.push(2);
        pq.push(1); // Push should fail
        cout << "Size = " <<pq.size() << " Max Size = " << (int)pq.max_size();
        for (int i=0; i<maxSize; i++)
        {
                int a = pq.top();
                pq.pop();
                cout << a <<"\n";
        }
        return 0;
}

I expected the result to be:

Size = 2 Max Size = 2

3

2

But what I get is:

Size = 3 Max Size = -1

3

2

What am I missing?


问:
Laravel: vue components not rendering
My vue components are not rendering on the page, despite following tutorials. I have the following layout (master.blade.php):

```<code><html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Mileage</title>
    <link rel="stylesheet" href="{{ mix('/css/app.css') }}" media="all">
</head>

<body>
    <div id="app">
        <example-component></example-component>
    </div>
    <script src="{{ mix('/js/app.js') }}"></script>
</body>
</html>
</code>```

The layout is returned by the following controller (I use CAS for login):

```<code><?php

namespace App\Http\Controllers;

use App\LkpStaff;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function login()
    {
        if (!cas()->isAuthenticated())
        {
            cas()->authenticate();
        }

        $user = cas()->user();

        $dbUser = LkpStaff::where('user_name', $user)->first(['staff_refid']);

        if ($dbUser)
        {
            $userId = $dbUser->staff_refid;
        }else
        {
            $userId = $this->createNewUser($user);
        }

        session()->put('casUser', $user);
        session()->put('userId', $userId);

        return view('master', [
            'casUser' => $user,
            'userId' => $userId
        ]);
    }
}
</code>```

The CAS login works as intended, so that's not a problem. I am simply trying to render the example component that comes with laravel (ExampleComponent.vue):

```<code><template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        I'm an example component.
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>
</code>```

My app.js file registers the component as expected:

```<code>require('./bootstrap');

window.Vue = require('vue');

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
    el: '#app'
});
</code>```

My package.json is the following:

```<code>{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.18",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^4.0.7",
        "lodash": "^4.17.5",
        "popper.js": "^1.12",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.15.2",
        "sass-loader": "^7.1.0",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    },
    "dependencies": {
        "bulma": "^0.7.0",
        "font-awesome": "^4.7.0",
        "laravel-blade-compiler": "^1.0.10",
        "moment": "^2.24.0",
        "purify-css": "^1.2.5"
    }
}
</code>```

I used npm install and npm run dev. I served the project with php artisan serve. The page looks like this (in the browser console):

```<code><html><head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <meta name="csrf-token" content="gLzt6ZloAyL7kFEVuO0tHlv6XqlsCMlELSx9Eqg6">
    <title>Mileage</title>
    <link rel="stylesheet" href="/css/app.css" media="all">
</head>

<body>
    <div id="app">
        <example-component></example-component>
    </div>
    <script src="/js/app.js"></script>

</body></html>
</code>```

As you can see, the component is not rendered. There are no errors in the console either. Is there anything I can do short of creating a new project?

答: try to add div element below of template and inside of the div enter your code and then in your terminal enter npm run watch or npm run dev wait until the compiled message comes up in your terminal if their is error it will prompt you</p>

Title: Laravel: vue components not rendering

Body:
My vue components are not rendering on the page, despite following tutorials. I have the following layout (master.blade.php):

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Mileage</title>
    <link rel="stylesheet" href="{{ mix('/css/app.css') }}" media="all">

        <example-component></example-component>

The layout is returned by the following controller (I use CAS for login):

<?php

namespace App\Http\Controllers;

use App\LkpStaff;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function login()
    {
        if (!cas()->isAuthenticated())
        {
            cas()->authenticate();
        }

        $user = cas()->user();

        $dbUser = LkpStaff::where('user_name', $user)->first(['staff_refid']);

        if ($dbUser)
        {
            $userId = $dbUser->staff_refid;
        }else
        {
            $userId = $this->createNewUser($user);
        }

        session()->put('casUser', $user);
        session()->put('userId', $userId);

        return view('master', [
            'casUser' => $user,
            'userId' => $userId
        ]);
    }
}

The CAS login works as intended, so that's not a problem. I am simply trying to render the example component that comes with laravel (ExampleComponent.vue):

<template>

Example Component

                        I'm an example component.

</template>

My app.js file registers the component as expected:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
    el: '#app'
});

My package.json is the following:

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.18",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^4.0.7",
        "lodash": "^4.17.5",
        "popper.js": "^1.12",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.15.2",
        "sass-loader": "^7.1.0",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    },
    "dependencies": {
        "bulma": "^0.7.0",
        "font-awesome": "^4.7.0",
        "laravel-blade-compiler": "^1.0.10",
        "moment": "^2.24.0",
        "purify-css": "^1.2.5"
    }
}

I used npm install and npm run dev. I served the project with php artisan serve. The page looks like this (in the browser console):

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <meta name="csrf-token" content="gLzt6ZloAyL7kFEVuO0tHlv6XqlsCMlELSx9Eqg6">
    <title>Mileage</title>
    <link rel="stylesheet" href="/css/app.css" media="all">

        <example-component></example-component>

As you can see, the component is not rendered. There are no errors in the console either. Is there anything I can do short of creating a new project?


问:
TCPDF -> How to style with CSS
I want to style my PDF file that I created with TCPDF. The class doesn't seem to support many styling's. I would like the style to be like left: 10px; and others like that. Does anyone have a solutions for this issue?

I'm styling now with a table, what is not very handy. Can anyone help me out?

答: I have served many of my hours and find that TCPDF does not support padding and margin properties of css. TCPDF support very limited version of css.</p>

Title: TCPDF -> How to style with CSS


问:
How to find Icon names for Font Awesome to import with React?
I have added Font Awesome icon library to my react project.
As per the documentation, i am creating a library but not able to add icons as i dont know the icon name to import.

For eg - On website icon is "coffee". But to add to library i need to use -

library.add(faCoffee)

then i can use it as -

How do i find the icon React name i.e. faCoffee for coffee?

```<code>import ReactDOM from 'react-dom'
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { faCheckSquare, faCoffee } from '@fortawesome/free-solid-svg-icons'

library.add(fab, faCheckSquare, faCoffee);

<FontAwesome icon="coffee" />
</code>```

答:
fa is a shortform for font awesome i believe. You can find all the icon names from here
here

If you want to use the icon, all you need to do is append with fa while importing and while using it, use it without fa.

See sandbox here

Body:
I have added Font Awesome icon library to my react project.
As per the documentation, i am creating a library but not able to add icons as i dont know the icon name to import.

For eg - On website icon is "coffee". But to add to library i need to use -

library.add(faCoffee)

then i can use it as -

How do i find the icon React name i.e. faCoffee for coffee?

import ReactDOM from 'react-dom'
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { faCheckSquare, faCoffee } from '@fortawesome/free-solid-svg-icons'

library.add(fab, faCheckSquare, faCoffee);

<FontAwesome icon="coffee" />


问:
One BigDecimal approximately equals another Bigdecimal
I'm extensively using BigDecimals. I often need to make long calculations and then compare results. Due to these long calculations, the answer is not 1 but rather 0.9999999.... That's why I can't compare BigDecimals exactly but only to a certain error.

How can I check whether one BigDecimal lies within an epsilon of the other one?

Remark: I'm already aware of answer.subtract(expected).abs().compareTo(epsilon) < 0. But I have to write it over and over again and I'm looking for an easier way to do it.

答:
No Div 0 problems

```<code>public static boolean almostEqual(BigDecimal a, BigDecimal b) {
    int scale = Math.min(a.scale(), b.scale()) -1;
    return a.setScale(scale, RoundingMode.HALF_UP)
               .compareTo(b.setScale(scale, RoundingMode.HALF_UP)) == 0;

}
</code>```

And scale be controlled

Body:
No Div 0 problems

public static boolean almostEqual(BigDecimal a, BigDecimal b) {
    int scale = Math.min(a.scale(), b.scale()) -1;
    return a.setScale(scale, RoundingMode.HALF_UP)
               .compareTo(b.setScale(scale, RoundingMode.HALF_UP)) == 0;

}

And scale be controlled


问:
What is in the meaning of `return "DONE"` at the end of a function in Python?
For context, this code is written on a video within the channel Numberphile by Matt Parker talking about multiplication persistence. The code is written in Python 2, and my question is about the line return "DONE".

Evidently, this prevents an infinite loop from being generated, as it is clear running an example (below) with and without that line:

```<code>def per(n, steps = 0):
    if len(str(n)) == 1:
        print "TOTAL STEPS " + str(steps)
        return "DONE"

    steps += 1
    digits = [int(i) for i in str(n)]

    result = 1
    for j in digits:
        result *= j
    print result
    per (result, steps)

per(27)

# 14
# 4
# TOTAL STEPS 2
</code>```

Now, the same code without the line return "DONE" would not end the loop, and yield:

```<code>14
4
TOTAL STEPS 2
4
TOTAL STEPS 3
4
TOTAL STEPS 4
4
TOTAL STEPS 5
4
TOTAL STEPS 6
4
TOTAL STEPS 7
4
TOTAL STEPS 8
4
TOTAL STEPS 9
4
TOTAL STEPS 10
4
TOTAL STEPS 11
4
TOTAL STEPS 12
4
TOTAL STEPS 13
4
TOTAL STEPS 14
4
...
</code>```

My question is about the meaning of 'return "HOME"'. Does it simply mean STOP. Is there any meaning of "HOME" in there?

答:
The return inside the if statement is just a termination for your recursive function - have you noticed that you are calling per(x) inside itself?

If we take out the return, the function will not terminate, and Python will raise a max recursive exception.

Now your function does this: if length of n is 1, terminate; otherwise, call another per function until somewhere it meets your termination condition.

But your per is not actually returning anything when len(str(n)) != 1. By default, a function implicitly returns None. So even though per(1) returns "Done", the returned value will not be propagated to the function which calls it.

To make it clearer, what you might need is (which guarantees the return value will be consistent with different input):

```<code>def per(n, steps=0):
    if len(str(n)) == 1:
        return "Done"
    # some other code
    return per(result, steps)
</code>```

And another definition is also consistent:

```<code>def per(n, steps=0):
    if len(str(n)) == 1:
        return # None
    # some other code
    per(result, steps)
    # implicitly return None
</code>```

Body:
For context, this code is written on a video within the channel Numberphile by Matt Parker talking about multiplication persistence. The code is written in Python 2, and my question is about the line return "DONE".

Evidently, this prevents an infinite loop from being generated, as it is clear running an example (below) with and without that line:

def per(n, steps = 0):
    if len(str(n)) == 1:
        print "TOTAL STEPS " + str(steps)
        return "DONE"

    steps += 1
    digits = [int(i) for i in str(n)]

    result = 1
    for j in digits:
        result *= j
    print result
    per (result, steps)

per(27)

# 14
# 4
# TOTAL STEPS 2

Now, the same code without the line return "DONE" would not end the loop, and yield:

14
4
TOTAL STEPS 2
4
TOTAL STEPS 3
4
TOTAL STEPS 4
4
TOTAL STEPS 5
4
TOTAL STEPS 6
4
TOTAL STEPS 7
4
TOTAL STEPS 8
4
TOTAL STEPS 9
4
TOTAL STEPS 10
4
TOTAL STEPS 11
4
TOTAL STEPS 12
4
TOTAL STEPS 13
4
TOTAL STEPS 14
4
...

My question is about the meaning of 'return "HOME"'. Does it simply mean STOP. Is there any meaning of "HOME" in there?

Body:
The return inside the if statement is just a termination for your recursive function - have you noticed that you are calling per(x) inside itself?

If we take out the return, the function will not terminate, and Python will raise a max recursive exception.

Now your function does this: if length of n is 1, terminate; otherwise, call another per function until somewhere it meets your termination condition.

But your per is not actually returning anything when len(str(n)) != 1. By default, a function implicitly returns None. So even though per(1) returns "Done", the returned value will not be propagated to the function which calls it.

To make it clearer, what you might need is (which guarantees the return value will be consistent with different input):

def per(n, steps=0):
    if len(str(n)) == 1:
        return "Done"
    # some other code
    return per(result, steps)

And another definition is also consistent:

def per(n, steps=0):
    if len(str(n)) == 1:
        return # None
    # some other code
    per(result, steps)
    # implicitly return None


问:
compute all permutations of a list in a dataframe column
I am trying to compute all permutations of a list or column in a df while keeping an id column.</p>

```<code>input df
    id    list
    1     foo bar
    2     dog cat

desired df output
    id    list
    1     foo bar
    1     bar foo
    2     dog cat
    2     cat dog
</code>```

答:
You can use a list comprehension with permutations:

```<code>from itertools import permutations

df = pd.DataFrame({'id': [1, 2], 'list': [['foo', 'bar'], ['cat', 'dog']]})

>>> pd.DataFrame([[id_, list(perm)]
                  for id_, list_items in df.values for perm in permutations(list_items)],
                 columns=['id', 'list'])
   id        list
0   1  [foo, bar]
1   1  [bar, foo]
2   2  [cat, dog]
3   2  [dog, cat]
</code>```

Depending on the exact structure of the list contents, you may first need to parse.

Body:
I am trying to compute all permutations of a list or column in a df while keeping an id column.

input df
    id    list
    1     foo bar
    2     dog cat

desired df output
    id    list
    1     foo bar
    1     bar foo
    2     dog cat
    2     cat dog

Body:
You can use a list comprehension with permutations:

from itertools import permutations

df = pd.DataFrame({'id': [1, 2], 'list': [['foo', 'bar'], ['cat', 'dog']]})

>>> pd.DataFrame([[id_, list(perm)]
                  for id_, list_items in df.values for perm in permutations(list_items)],
                 columns=['id', 'list'])
   id        list
0   1  [foo, bar]
1   1  [bar, foo]
2   2  [cat, dog]
3   2  [dog, cat]

Depending on the exact structure of the list contents, you may first need to parse.


问:
Ansible apt Task: Failed to Lock apt for Exclusive Operation
I have written an Ansible playbook that includes running apt-get dist-upgrade. I made sure to have become: true and become_user: root at the top of the playbook in order to get sudo access to run the upgrade. This works fine locally on my Vagrant VMs, but when running on our production systems (Ubuntu 16.04) we get the following error:

Failed to lock apt for exclusive operation

Our current workaround is to SSH into the machine and then manually run sudo apt-get dist-upgrade. Then exit the SSH session and run the ansible playbook again and it works.

Other tasks in our playbook require sudo access and work fine. It is just the apt command that fails. We have tried rebooting the machines and replacing become: true and become_user: root with sudo: yes to no avail.

Any ideas on how to solve this problem? I'll include the pertinent parts of our playbook below.

```<code>- become: true
  become_user: root
  name: Setup the mongo database servers
  hosts: sgmongo-{{ customer }}-ciadmin
  tasks:
    -
      name: Ensure OS is upgraded with all patches
      apt: upgrade=dist update_cache=yes
</code>```

答:
I do it by calling a shell script with Ansible like so:

```<code>- script: ./files/bash_scripts/monitor_automatic_updates_status.sh
</code>```

The script in question that Ansible calls is here:

```<code>#!/bin/bash
#Debian automatically checks for updates on first boot. This ensures that has completed before continuing.
#If it hasn't finished in 10 minutes, the script will exit ungracefully.
timeout=$(($(date +%s) + 600))

while pgrep apt > /dev/null; do

    time=$(date +%s)

    if [[ $time -ge $timeout ]];
    then
        exit 1
    fi

    sleep 1
done;
exit 0
</code>```

It just continually checks if apt is running on the system or not. And, when it finally finishes running, allows Ansible to continue.

Body:
I have written an Ansible playbook that includes running apt-get dist-upgrade. I made sure to have become: true and become_user: root at the top of the playbook in order to get sudo access to run the upgrade. This works fine locally on my Vagrant VMs, but when running on our production systems (Ubuntu 16.04) we get the following error:

Failed to lock apt for exclusive operation

Our current workaround is to SSH into the machine and then manually run sudo apt-get dist-upgrade. Then exit the SSH session and run the ansible playbook again and it works.

Other tasks in our playbook require sudo access and work fine. It is just the apt command that fails. We have tried rebooting the machines and replacing become: true and become_user: root with sudo: yes to no avail.

Any ideas on how to solve this problem? I'll include the pertinent parts of our playbook below.

- become: true
  become_user: root
  name: Setup the mongo database servers
  hosts: sgmongo-{{ customer }}-ciadmin
  tasks:
    -
      name: Ensure OS is upgraded with all patches
      apt: upgrade=dist update_cache=yes

Body:
I do it by calling a shell script with Ansible like so:

- script: ./files/bash_scripts/monitor_automatic_updates_status.sh

The script in question that Ansible calls is here:

#!/bin/bash
#Debian automatically checks for updates on first boot. This ensures that has completed before continuing.
#If it hasn't finished in 10 minutes, the script will exit ungracefully.
timeout=$(($(date +%s) + 600))

while pgrep apt > /dev/null; do

    time=$(date +%s)

    if [[ $time -ge $timeout ]];
    then
        exit 1
    fi

    sleep 1
done;
exit 0

It just continually checks if apt is running on the system or not. And, when it finally finishes running, allows Ansible to continue.


问:
How to line up the empty cells with filled cells for array of data structure?
I'm trying to line up the empty cells with filled cells for an array in data structure. Please help!! This is the code I have so far:

```<code>\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{matrix,backgrounds}

\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw, minimum size=8mm},
             nodes in empty cells,
             row 1/.style={nodes={draw=none}},]
{
  0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\
  2 & 4 & 4 & 5 &  &  &  & &\\
};
\end{tikzpicture}
\end{document}
</code>```

It comes out look like this:The boxes did not line up1

I want to line up the boxes, how can I do that???

答:
I first suggest that you post questions regarding LaTeX on tex.stackexchange.com.

The fix to your problem is very simple! You are missing anchor=center in the nodes={...}.

```<code>\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,backgrounds}

\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw, minimum size=8mm,anchor=center},
             nodes in empty cells, minimum height = 1cm,
             row 1/.style={nodes={draw=none}},]
{
  0 & 1 & 2 & 3 & 4 & 5 & 6 & 7  \\
  2 & 4 & 4 & 5 &   &   &   &  & \\
};
\end{tikzpicture}
\end{document}
</code>```

Body:
I'm trying to line up the empty cells with filled cells for an array in data structure. Please help!! This is the code I have so far:

\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{matrix,backgrounds}

\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw, minimum size=8mm},
             nodes in empty cells,
             row 1/.style={nodes={draw=none}},]
{
  0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\
  2 & 4 & 4 & 5 &  &  &  & &\\
};
\end{tikzpicture}
\end{document}

It comes out look like this:The boxes did not line up1

I want to line up the boxes, how can I do that???

Body:
I first suggest that you post questions regarding LaTeX on tex.stackexchange.com.

The fix to your problem is very simple! You are missing anchor=center in the nodes={...}.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,backgrounds}

\begin{document}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
             nodes={draw, minimum size=8mm,anchor=center},
             nodes in empty cells, minimum height = 1cm,
             row 1/.style={nodes={draw=none}},]
{
  0 & 1 & 2 & 3 & 4 & 5 & 6 & 7  \\
  2 & 4 & 4 & 5 &   &   &   &  & \\
};
\end{tikzpicture}
\end{document}


问:
Why my jQuery ajax call is not successful
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:

```<code>$.ajax({
        url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
        type: 'GET',
        async: false,
        dataType: 'application/xml',
        data: {id: 43},
        success: function(data) {

            alert(data);

        },
        error: function(xhr, status, error){
            alert('error happens');
        }
     })
</code>```

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.

I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.

Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?

----------------EDIT---------------

Hi, I changed to use localhost request like:

```<code>$.ajax({
            url: 'http://localhost:8080/company-interface/the-id',
            type: 'GET',
            async: false,
            dataType: 'xml',
            data: {id: 43},
            success: function(data) {

                alert(data);

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })
</code>```

But I got the same error... more suggestions please... thank you.

答:
1302610001570 is for measuring response,

did you checked if the response create valid xml?

Body:
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:

$.ajax({
        url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
        type: 'GET',
        async: false,
        dataType: 'application/xml',
        data: {id: 43},
        success: function(data) {

            alert(data);

        },
        error: function(xhr, status, error){
            alert('error happens');
        }
     })

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.

I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.

Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?

----------------EDIT---------------

Hi, I changed to use localhost request like:

$.ajax({
            url: 'http://localhost:8080/company-interface/the-id',
            type: 'GET',
            async: false,
            dataType: 'xml',
            data: {id: 43},
            success: function(data) {

                alert(data);

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

But I got the same error... more suggestions please... thank you.


问:
SQL exception was not handled by user code
My code:

```<code>    if (Page.IsValid)
    {
        DataSet.UsersDataTable oUserDataTable =
            new DataSet.UsersDataTable();

        DataSetTableAdapters.UsersTableAdapter oUserTableAdapter =
            new DataSetTableAdapters.UsersTableAdapter();

        oUserTableAdapter.FillUserByUserName(oUserDataTable, txtUserName.Text);

        if (oUserDataTable.Count!=1)
        {
            string strErrorMessage =
                "UserName Or Password Is Not Correct ! Please Try Again . . . ";
            DisplayErrorMessage(strErrorMessage);
            return;
        }

        DataSet.UsersRow oUserRow = oUserDataTable[0];

        if (string.Compare(oUserRow.Password.Trim(),txtPassword.Text.Trim(),false)!=0)
        {
             string strErrorMessage =
                "UserName Or Password Is Not Correct ! Please Try Again . . . ";
             DisplayErrorMessage(strErrorMessage);
            return;
        }

        if (oUserRow.IsUserActive==false)
        {
            string strInformationMessage =
                string.Format("Dear {0} You Should Not Login At This Time , Please Contact Support",txtUserName.Text);
            DisplayInformationMessage(strInformationMessage);
            return;
        }
</code>```

I get an error:

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

答:
first of all check if db connection can open, if yes, then is good to go, otherwise throw exception and check if the connection string is correct. Following code can help you for DB connection checking

```<code>try
{
   using (SqlConnection conn = new SqlConnection("connection"))
   {
      conn.Open();
    }
}
catch(Exception ex)
{
   MessageBox.Show(ex.Message, "Invalid Connection String");
}
</code>```

add this code before this line DataSet.UsersDataTable oUserDataTable =
            new DataSet.UsersDataTable();

Body:
My code:

    if (Page.IsValid)
    {
        DataSet.UsersDataTable oUserDataTable =
            new DataSet.UsersDataTable();

        DataSetTableAdapters.UsersTableAdapter oUserTableAdapter =
            new DataSetTableAdapters.UsersTableAdapter();

        oUserTableAdapter.FillUserByUserName(oUserDataTable, txtUserName.Text);

        if (oUserDataTable.Count!=1)
        {
            string strErrorMessage =
                "UserName Or Password Is Not Correct ! Please Try Again . . . ";
            DisplayErrorMessage(strErrorMessage);
            return;
        }

        DataSet.UsersRow oUserRow = oUserDataTable[0];

        if (string.Compare(oUserRow.Password.Trim(),txtPassword.Text.Trim(),false)!=0)
        {
             string strErrorMessage =
                "UserName Or Password Is Not Correct ! Please Try Again . . . ";
             DisplayErrorMessage(strErrorMessage);
            return;
        }

        if (oUserRow.IsUserActive==false)
        {
            string strInformationMessage =
                string.Format("Dear {0} You Should Not Login At This Time , Please Contact Support",txtUserName.Text);
            DisplayInformationMessage(strInformationMessage);
            return;
        }

I get an error:

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Body:
first of all check if db connection can open, if yes, then is good to go, otherwise throw exception and check if the connection string is correct. Following code can help you for DB connection checking

try
{
   using (SqlConnection conn = new SqlConnection("connection"))
   {
      conn.Open();
    }
}
catch(Exception ex)
{
   MessageBox.Show(ex.Message, "Invalid Connection String");
}

add this code before this line DataSet.UsersDataTable oUserDataTable =
            new DataSet.UsersDataTable();


问:
Any type of file is been update on my rules of allowed_types
I use CodeIgniter and I want to upload an image.
Therefore I tried to limit the allowed file extensions using 'allowed_types'.

However I still accepts any file extension when I upload something.

This is a simple form.

$configImagem['upload_path']   = './files/noticias/imagens';
$configImagem['allowed_types'] = 'gif|jpg|jpeg|png';
$configImagem['file_name']     = 'noticia_'.date('y-m-d_h-i-s');

$this->upload->initialize($configImagem);
```

I expect an error when I upload a file with a extension not in allowed_types.

答:
There are some weird things happens when you use initialize() method from the upload library, that's why i stopped using this method and depended on reloading the library itself with the new configs array, i'm pretty sure this will work:

```<code>$configImagem['upload_path']   = './files/noticias/imagens';
$configImagem['allowed_types'] = 'gif|jpg|jpeg|png';
$configImagem['file_name']     = 'noticia_'.date('y-m-d_h-i-s');

$this->load->library('upload', $configImagem);
</code>```

Now these configs will override the default configs which accepts any mime type by default.

Body:
I use CodeIgniter and I want to upload an image.
Therefore I tried to limit the allowed file extensions using 'allowed_types'.

However I still accepts any file extension when I upload something.

This is a simple form.

$configImagem['upload_path']   = './files/noticias/imagens';
$configImagem['allowed_types'] = 'gif|jpg|jpeg|png';
$configImagem['file_name']     = 'noticia_'.date('y-m-d_h-i-s');

$this->upload->initialize($configImagem);

I expect an error when I upload a file with a extension not in allowed_types.

Body:
There are some weird things happens when you use initialize() method from the upload library, that's why i stopped using this method and depended on reloading the library itself with the new configs array, i'm pretty sure this will work:

$configImagem['upload_path']   = './files/noticias/imagens';
$configImagem['allowed_types'] = 'gif|jpg|jpeg|png';
$configImagem['file_name']     = 'noticia_'.date('y-m-d_h-i-s');

$this->load->library('upload', $configImagem);

Now these configs will override the default configs which accepts any mime type by default.


问:
How to specify a default value for argument list processed by click?
I have this line of code that is expected to grab all the file names passed to my Python script:

```<code>@click.argument("logs", nargs=-1, type=click.File('r'), required=1)
</code>```

When no file names are passed, I want to default to -, that is, the standard input.  So, if I try:

```<code>@click.argument("logs", nargs=-1, type=click.File('r'), required=1, default="-")
</code>```

click becomes unhappy and throws this error:

TypeError: nargs=-1 in combination with a default value is not supported.

Is there a workaround for this? I tried setting nargs=0 but that throws a different error:

IndexError: tuple index out of range

答:
Since click had explicitly stated that they disabled this particular feature needed by the question, as reported on this issue on their project, a workaround will be needed and that can be easily implemented as part of the Python function (instead of some more pile on bash code as suggested by the comment on the other answer).

The workaround is simply drop the required argument and handle the missing logs using a statement (similar to what this commit did which referenced the linked issue):

```<code>import sys
import click

@click.command()
@click.argument("logs", nargs=-1, type=click.File('r'))
def main(logs):
    if not logs:
        logs = (sys.stdin,)
    print(logs)
    # do stuff with logs

if __name__ == '__main__':
    main()

</code>```

Example execution

```<code>$ python fail.py
(<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>,)
$ python fail.py -
(<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>,)
$ python fail.py foo bar
(<_io.TextIOWrapper name='foo' mode='r' encoding='UTF-8'>, <_io.TextIOWrapper name='bar' mode='r' encoding='UTF-8'>)
</code>```

Body:
I have this line of code that is expected to grab all the file names passed to my Python script:

@click.argument("logs", nargs=-1, type=click.File('r'), required=1)

When no file names are passed, I want to default to -, that is, the standard input.  So, if I try:

@click.argument("logs", nargs=-1, type=click.File('r'), required=1, default="-")

click becomes unhappy and throws this error:

TypeError: nargs=-1 in combination with a default value is not supported.

Is there a workaround for this? I tried setting nargs=0 but that throws a different error:

IndexError: tuple index out of range

Body:
Since click had explicitly stated that they disabled this particular feature needed by the question, as reported on this issue on their project, a workaround will be needed and that can be easily implemented as part of the Python function (instead of some more pile on bash code as suggested by the comment on the other answer).

The workaround is simply drop the required argument and handle the missing logs using a statement (similar to what this commit did which referenced the linked issue):

import sys
import click

@click.command()
@click.argument("logs", nargs=-1, type=click.File('r'))
def main(logs):
    if not logs:
        logs = (sys.stdin,)
    print(logs)
    # do stuff with logs

if __name__ == '__main__':
    main()

Example execution

$ python fail.py
(<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>,)
$ python fail.py -
(<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>,)
$ python fail.py foo bar
(<_io.TextIOWrapper name='foo' mode='r' encoding='UTF-8'>, <_io.TextIOWrapper name='bar' mode='r' encoding='UTF-8'>)


问:
How do I update Anaconda?
I have Anaconda installed on my computer and I'd like to update it.  In Navigator I can see that there are several individual packages that can be updated, but also an anaconda package that sometimes has a version number and sometimes says custom.  How do I proceed?

答:
I'm using Windows 10. The following updates everything and also installs some new packages, including a Python update (for me it was 3.7.3).

At the shell, try the following (be sure to change where your Anaconda 3 Data is installed). It takes some time to update everything.

```<code>conda update --prefix X:\XXXXData\Anaconda3 anaconda
</code>```

Title: How do I update Anaconda?

Body:
I'm using Windows 10. The following updates everything and also installs some new packages, including a Python update (for me it was 3.7.3).

At the shell, try the following (be sure to change where your Anaconda 3 Data is installed). It takes some time to update everything.

conda update --prefix X:\XXXXData\Anaconda3 anaconda


问:
Submit pull request from child branch after parent branch is merged to upstream
I have a local git repo that has a remote upstream in Github. I created a branchA in my local repo for a new feature I was working on and then submitted a Pull Request for that branch. While waiting for this PR to be merged in upstream, I wanted to work on some more features that's based on branchA. So I created a new branchA1 from branchA and made some changes in that branch.

Now my PR for branchA is squash and merged to remote upstream in Github and I would like to submit a PR for my branchA1. What I did is that I first fetched the changes from remote upstream to my local master branch. Then I tried to do git rebase master in branchA1 but this command seems to be deleting all the changes I made in branchA1.

What is the best thing to do now if I would like to submit a PR from branchA1?

If I did something wrong in my workflow, what is the correct way to work on new features while waiting for a PR from parent branch to be merged?

答:
TL;DR: you probably want git rebase --onto (which needs some extra parameters).

When you—or someone else; I'll use "they" here and assume someone—did a "squash and merge" on your original pull request, they replaced your commit(s) with a single new commit that they think is better than your original commit.

You, however, still have your original commit(s).  It's now your job to use git rebase to copy only the good commits on your A1, not any of the replaced-with-better commits that were on both A1 and A and are now only on A1.

To put it in pictorial form, you had, e.g.:

```<code>...--o--o--A   <-- master, origin/master
            \
             B--C--D   <-- branch-A
                    \
                     E--F--G   <-- branch-A1
</code>```

where each uppercase letter stands in for a commit, i.e., A is the hash ID of the commit that was at the tip of your (and their) master when you started, B is the first commit you made on your branch-A, and so on.

They then said: OK, we like your B-C-D commits. But we're going to "improve" them by making a new commit H that's the result of combining B + C + D all into one big commit, which we'll put at the end of our master (your origin/master).  They may or may not have put some more commits in to their master in the meantime as well—let's draw in one round o to represent any such uninteresting commits.  As soon as you run git fetch origin, you get their new commits (you already have their old ones) into your repository, updating your origin/master:

```<code>             o--H   <-- origin/master
            /
...--o--o--A   <-- master
            \
             B--C--D   <-- branch-A
                    \
                     E--F--G   <-- branch-A1
</code>```

If you git checkout master and git merge origin/master, you'll move your own master forward to match your origin/master:

```<code>...--o--o--A--o--H   <-- master, origin/master
            \
             B--C--D   <-- branch-A
                    \
                     E--F--G   <-- branch-A1
</code>```

Your branch-A still exists, unless you specifically deleted it.  But even if you deleted it, you still have your B-C-D commits:

```<code>...--o--o--A--o--H   <-- master, origin/master
            \
             B--C--D--E--F--G   <-- branch-A1
</code>```

If you now git checkout branch-A1 and git rebase master—whether or not you still have your name branch-A pointing to your commit D that they threw away in favor of their H—your Git will now try to copy all six commits, B-C-D-E-F-G, atop H, in an attempt to produce this:

```<code>                   B'-C'-D'-E'-F'-G'   <-- branch-A1 (rebased)
                  /
...--o--o--A--o--H   <-- master, origin/master
            \
             B--C--D--E--F--G   [abandoned]
</code>```

But copying B atop H is not going to go well: it will conflict with itself, plus it needs the effect of C and D removed.  So this will look like you're trying to remove your own code, only to put it back again when you copy C to C' and later D to D'.  In any case all of that is useless.

What you'd like to tell Git, at this point, is not: Copy all of my commits on branch-A1 that aren't on master, to go after H at the tip of master, but rather: Copy only some of my commits on branch-A1 that aren't on master, to go after H at the tip of master.  The set of commits that you want to copy, in this particular example, is E-F-G.  You want to end up with:

```<code>                   E'-F'-G'   <-- branch-A1 (rebased)
                  /
...--o--o--A--o--H   <-- master, origin/master
            \
             B--C--D--E--F--G   [abandoned]
</code>```

The way to tell Git that is to use git rebase --onto, which takes two arguments instead of just one.  You want to rebase *onto master, and you want to exclude commit D and anything earlier (C, B, A, and all the boring commits to the left of A).  So, if you do still have the name branch-A identifying commit D, you can use:

```<code>git checkout branch-A1             # make sure you're on the right branch
git rebase --onto master branch-A  # tell Git: copy only commits after branch-A
</code>```

If you don't have the name branch-A, you can use a raw commit hash ID as the limiter instead of the name branch-A, or you can run git rebase -i master and delete the unwanted pick commands; or you can run git log --all --decorate --oneline --graph and count commits, or whatever you need, to find the commit.

Note that after rebasing, you have a new branch-A1 (completely unrelated by history to your earlier branch-A1, even though the three commits are copied so as to have the same effect).  You will therefore need to force-push this to whatever web service you are using to handle pull requests (apparently GitHub).  You can use --force-with-lease if you're worried that someone else might be adding commits to your branch-A1 on the GitHub server.

Body:
TL;DR: you probably want git rebase --onto (which needs some extra parameters).

When you—or someone else; I'll use "they" here and assume someone—did a "squash and merge" on your original pull request, they replaced your commit(s) with a single new commit that they think is better than your original commit.

You, however, still have your original commit(s).  It's now your job to use git rebase to copy only the good commits on your A1, not any of the replaced-with-better commits that were on both A1 and A and are now only on A1.

To put it in pictorial form, you had, e.g.:

...--o--o--A   <-- master, origin/master
            \
             B--C--D   <-- branch-A
                    \
                     E--F--G   <-- branch-A1

where each uppercase letter stands in for a commit, i.e., A is the hash ID of the commit that was at the tip of your (and their) master when you started, B is the first commit you made on your branch-A, and so on.

They then said: OK, we like your B-C-D commits. But we're going to "improve" them by making a new commit H that's the result of combining B + C + D all into one big commit, which we'll put at the end of our master (your origin/master).  They may or may not have put some more commits in to their master in the meantime as well—let's draw in one round o to represent any such uninteresting commits.  As soon as you run git fetch origin, you get their new commits (you already have their old ones) into your repository, updating your origin/master:

             o--H   <-- origin/master
            /
...--o--o--A   <-- master
            \
             B--C--D   <-- branch-A
                    \
                     E--F--G   <-- branch-A1

If you git checkout master and git merge origin/master, you'll move your own master forward to match your origin/master:

...--o--o--A--o--H   <-- master, origin/master
            \
             B--C--D   <-- branch-A
                    \
                     E--F--G   <-- branch-A1

Your branch-A still exists, unless you specifically deleted it.  But even if you deleted it, you still have your B-C-D commits:

...--o--o--A--o--H   <-- master, origin/master
            \
             B--C--D--E--F--G   <-- branch-A1

If you now git checkout branch-A1 and git rebase master—whether or not you still have your name branch-A pointing to your commit D that they threw away in favor of their H—your Git will now try to copy all six commits, B-C-D-E-F-G, atop H, in an attempt to produce this:

                   B'-C'-D'-E'-F'-G'   <-- branch-A1 (rebased)
                  /
...--o--o--A--o--H   <-- master, origin/master
            \
             B--C--D--E--F--G   [abandoned]

But copying B atop H is not going to go well: it will conflict with itself, plus it needs the effect of C and D removed.  So this will look like you're trying to remove your own code, only to put it back again when you copy C to C' and later D to D'.  In any case all of that is useless.

What you'd like to tell Git, at this point, is not: Copy all of my commits on branch-A1 that aren't on master, to go after H at the tip of master, but rather: Copy only some of my commits on branch-A1 that aren't on master, to go after H at the tip of master.  The set of commits that you want to copy, in this particular example, is E-F-G.  You want to end up with:

                   E'-F'-G'   <-- branch-A1 (rebased)
                  /
...--o--o--A--o--H   <-- master, origin/master
            \
             B--C--D--E--F--G   [abandoned]

The way to tell Git that is to use git rebase --onto, which takes two arguments instead of just one.  You want to rebase *onto master, and you want to exclude commit D and anything earlier (C, B, A, and all the boring commits to the left of A).  So, if you do still have the name branch-A identifying commit D, you can use:

git checkout branch-A1             # make sure you're on the right branch
git rebase --onto master branch-A  # tell Git: copy only commits after branch-A

If you don't have the name branch-A, you can use a raw commit hash ID as the limiter instead of the name branch-A, or you can run git rebase -i master and delete the unwanted pick commands; or you can run git log --all --decorate --oneline --graph and count commits, or whatever you need, to find the commit.

Note that after rebasing, you have a new branch-A1 (completely unrelated by history to your earlier branch-A1, even though the three commits are copied so as to have the same effect).  You will therefore need to force-push this to whatever web service you are using to handle pull requests (apparently GitHub).  You can use --force-with-lease if you're worried that someone else might be adding commits to your branch-A1 on the GitHub server.


问:
Apache redirect .js request to PHP request
I am trying to serve a JavaScript response from a JavaScript request using PHP.

Assuming that the request is embedded into the HTML source as

```<code><script type=\"text/javascript\" src=\"http://www.mydomain.com/generatejs.js\" charset=\"UTF-8\"></script>
</code>```

And i have a PHP script that is called generatejs.js.php which outputs more JavaScript code

The Apache rewrite condition/rule are

```<code>RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

But I am getting a 404 when trying to access http://www.mydomain.com/generatejs.js. Can someone please help me with the missing bit? :)

答:
Do you mean this?</p>

```<code>RewriteEngine on
RewriteRule ^generatejs.js$ generatejs.js.php
</code>```

Body:
I am trying to serve a JavaScript response from a JavaScript request using PHP.

Assuming that the request is embedded into the HTML source as

And i have a PHP script that is called generatejs.js.php which outputs more JavaScript code

The Apache rewrite condition/rule are

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]

But I am getting a 404 when trying to access http://www.mydomain.com/generatejs.js. Can someone please help me with the missing bit? :)

Body:
Do you mean this?

RewriteEngine on
RewriteRule ^generatejs.js$ generatejs.js.php


问:
Splitting the strings and store into new column in pandas dataframe
I have a data frame which as names column. Name column appear as below

```<code>Name

Tim, Brook, morgan han, wang, chen

adam, kate, ken fin, brad chun

Smith, leo

Elisa, Adam, Smith, Brad, james
</code>```

I want to split the above names and store into new columns as below

```<code>Name      Name 1       Name 2         Name 3          Name 4           Name 5

Tim       Brook        Morgan         Han             Wang             Chen
Adam      Kate         Ken fin        brad chun
Smith     Leo
Elsa      Adam          Amith         Brad            James
</code>```

I have more than 1000 rows in the column and having 20 columns. Want to split the names using function (def). Some rows has 5 names and other has 4, 3 or 2 names.

Used str.split and it's just giving the first name. But I am not sure how it split other names. Also used the function but it's not working

```<code>df[['Name']] = df.Name.str.split(', ', expand = True)

</code>```

```<code>def clean(column_name):
   name=set()
    for name_string in df[column_name]:
        name.update(name_string.split(', '))
    name=sorted(name)
    return name
</code>```

```<code>df[['Name']] = df[['Name']].apply(clean)
</code>```

If I use the above function I am getting this error

KeyError: 'Tim, Brook, morgan han, wang, chen'

Please advise. I have gone through all the posts here but not successful.

答:
```<code># to recreate example table
a = pd.DataFrame([str('Tim, Brook, morgan han, wang, chen')])
b = pd.DataFrame([str('Smith, leo')])
c = pd.DataFrame([str('Elisa, Adam, Smith, Brad, james')])
x = pd.concat([a,b,c], axis=0, ignore_index=True)
x.columns = ['Name']
</code>```

Solution

```<code>x['Name1'] = x.Name.apply(lambda x: x.split(',')[0])
x['Name2'] = x.Name.apply(lambda x: x.split(',')[1])
x['Name3'] = x.Name.apply(lambda x: x.split(',')[2] if len(x.split(',')) > 2 else '')
x['Name4'] = x.Name.apply(lambda x: x.split(',')[3] if len(x.split(',')) > 3 else '')
x['Name5'] = x.Name.apply(lambda x: x.split(',')[4] if len(x.split(',')) > 4 else '')
</code>```

Output

```<code>                                 Name  Name1   Name2        Name3  Name4  \
0  Tim, Brook, morgan han, wang, chen    Tim   Brook   morgan han   wang
1                          Smith, leo  Smith     leo
2     Elisa, Adam, Smith, Brad, james  Elisa    Adam        Smith   Brad

    Name5
0    chen
1
2   james

</code>```

You can implement a for-loop out of the solution, depending on the max number of names in each row. Hope this takes you somewhere. Cheers.

Body:
I have a data frame which as names column. Name column appear as below

Name

Tim, Brook, morgan han, wang, chen

adam, kate, ken fin, brad chun

Smith, leo

Elisa, Adam, Smith, Brad, james

I want to split the above names and store into new columns as below

Name      Name 1       Name 2         Name 3          Name 4           Name 5

Tim       Brook        Morgan         Han             Wang             Chen
Adam      Kate         Ken fin        brad chun
Smith     Leo
Elsa      Adam          Amith         Brad            James

I have more than 1000 rows in the column and having 20 columns. Want to split the names using function (def). Some rows has 5 names and other has 4, 3 or 2 names.

Used str.split and it's just giving the first name. But I am not sure how it split other names. Also used the function but it's not working

df[['Name']] = df.Name.str.split(', ', expand = True)

def clean(column_name):
   name=set()
    for name_string in df[column_name]:
        name.update(name_string.split(', '))
    name=sorted(name)
    return name

df[['Name']] = df[['Name']].apply(clean)

If I use the above function I am getting this error

KeyError: 'Tim, Brook, morgan han, wang, chen'

Please advise. I have gone through all the posts here but not successful.

Body:
# to recreate example table
a = pd.DataFrame([str('Tim, Brook, morgan han, wang, chen')])
b = pd.DataFrame([str('Smith, leo')])
c = pd.DataFrame([str('Elisa, Adam, Smith, Brad, james')])
x = pd.concat([a,b,c], axis=0, ignore_index=True)
x.columns = ['Name']

Solution

x['Name1'] = x.Name.apply(lambda x: x.split(',')[0])
x['Name2'] = x.Name.apply(lambda x: x.split(',')[1])
x['Name3'] = x.Name.apply(lambda x: x.split(',')[2] if len(x.split(',')) > 2 else '')
x['Name4'] = x.Name.apply(lambda x: x.split(',')[3] if len(x.split(',')) > 3 else '')
x['Name5'] = x.Name.apply(lambda x: x.split(',')[4] if len(x.split(',')) > 4 else '')

Output

                                 Name  Name1   Name2        Name3  Name4  \
0  Tim, Brook, morgan han, wang, chen    Tim   Brook   morgan han   wang
1                          Smith, leo  Smith     leo
2     Elisa, Adam, Smith, Brad, james  Elisa    Adam        Smith   Brad

    Name5
0    chen
1
2   james

You can implement a for-loop out of the solution, depending on the max number of names in each row. Hope this takes you somewhere. Cheers.


问:
How to localize default validation message for value-type (ushort) properties if value is out of the type boundaries?
I have some web form where user should enter the port number. Of course the best type for the port number is ushort. I use RangeAttribute to validate the port number and some error message.

[Required(ErrorMessage = "The field is required")]
[Display(Name = "Port")]
[Range(1, ushort.MaxValue, ErrorMessage = "Invalid value")]
public ushort Port { get; set; }
```

The localization works correct only if I enter values from 0 to 65535. So there is only one incorrect case - zero value. But if I try to save empty value, enter negative values or values greater than 65535, I get completely another error message (The value '-1' is not valid for Port.) and I don't know how to localize it.

Could anybody help me with this?

答:
The 'easy' way is to use short (or a greater signed type) instead ushort, the model binding process ocurs after model validation, therefore, since the value -1 is incompatible with ushort the process will stop there and your custom error will never be read.

The hard way is write your own model validator:

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#custom-attributes

Body:
I have some web form where user should enter the port number. Of course the best type for the port number is ushort. I use RangeAttribute to validate the port number and some error message.

[Required(ErrorMessage = "The field is required")]
[Display(Name = "Port")]
[Range(1, ushort.MaxValue, ErrorMessage = "Invalid value")]
public ushort Port { get; set; }

The localization works correct only if I enter values from 0 to 65535. So there is only one incorrect case - zero value. But if I try to save empty value, enter negative values or values greater than 65535, I get completely another error message (The value '-1' is not valid for Port.) and I don't know how to localize it.

Could anybody help me with this?


问:
Python Selenium: Global driver - 'driver' is not defined in the global scope
the source itself works, but I have the problem that the global driver is undefined, only in VsCode. When I run the source in pycharm, that problem does not exist. Unfortunately, I really do not know how to continue.

The Issue: 'driver' is not defined in the global scope

I used Python 3.7.2 with pytest

```<code>from selenium import webdriver
import pytest
from selenium.webdriver.common.keys import Keys

def test_setup():
        global driver
        driver = webdriver.Chrome(executable_path="e:/Webdriver/chromedriver.exe")
        driver.implicitly_wait(10)
        driver.maximize_window()

def test_login():
        driver.get("http://www.dev-crowd.com/wp-login.php")
        driver.find_element_by_id("user_login").send_keys("abc")
        driver.find_element_by_id("user_pass").send_keys("cab")
        driver.find_element_by_id("wp-submit").click()
        x = driver.title("abc")
        assert X == "abc"

def test_teardown():
        driver.close()
        driver.quit()
        print("Test completed")
</code>```

答:
The following should work, but i think it should not be necessary:</p>

```<code>from selenium import webdriver
import pytest
from selenium.webdriver.common.keys import Keys

driver = None

def test_setup():
    driver = webdriver.Chrome(executable_path="e:/Webdriver/chromedriver.exe")
    driver.implicitly_wait(10)
    driver.maximize_window()

def test_login():
    driver.get("http://www.dev-crowd.com/wp-login.php")
    driver.find_element_by_id("user_login").send_keys("abc")
    driver.find_element_by_id("user_pass").send_keys("cab")
    driver.find_element_by_id("wp-submit").click()
    x = driver.title("abc")
    assert x == "abc"

def test_teardown():
    driver.close()
    driver.quit()
    print("Test completed")
</code>```

Body:
the source itself works, but I have the problem that the global driver is undefined, only in VsCode. When I run the source in pycharm, that problem does not exist. Unfortunately, I really do not know how to continue.

The Issue: 'driver' is not defined in the global scope

I used Python 3.7.2 with pytest

from selenium import webdriver
import pytest
from selenium.webdriver.common.keys import Keys

def test_setup():
        global driver
        driver = webdriver.Chrome(executable_path="e:/Webdriver/chromedriver.exe")
        driver.implicitly_wait(10)
        driver.maximize_window()

def test_login():
        driver.get("http://www.dev-crowd.com/wp-login.php")
        driver.find_element_by_id("user_login").send_keys("abc")
        driver.find_element_by_id("user_pass").send_keys("cab")
        driver.find_element_by_id("wp-submit").click()
        x = driver.title("abc")
        assert X == "abc"

def test_teardown():
        driver.close()
        driver.quit()
        print("Test completed")

Body:
The following should work, but i think it should not be necessary:

from selenium import webdriver
import pytest
from selenium.webdriver.common.keys import Keys

driver = None

def test_setup():
    driver = webdriver.Chrome(executable_path="e:/Webdriver/chromedriver.exe")
    driver.implicitly_wait(10)
    driver.maximize_window()

def test_login():
    driver.get("http://www.dev-crowd.com/wp-login.php")
    driver.find_element_by_id("user_login").send_keys("abc")
    driver.find_element_by_id("user_pass").send_keys("cab")
    driver.find_element_by_id("wp-submit").click()
    x = driver.title("abc")
    assert x == "abc"

def test_teardown():
    driver.close()
    driver.quit()
    print("Test completed")


问:
how to access the struct?
```<code>struct result {
  int number;
  int length;
};

struct result findLongestSeq(int intarray[], int size) {
  result->number // undefined symbol
}
</code>```

how to access the struct result inside the function findLongestSeq?

thanks

答:
You have to keep in mind that by simply typing

```<code>struct result {
  int number;
  int length;
};
</code>```

you only define how a struct with name result actually looks like, i.e. of what parts it is made up. This is a general definition, but you have variable of that type yet.

To access values of this struct you have to create a variable by

```<code>struct result myResult;
</code>```

or however you want to call it. At this point you are able to access the members of this struct with  myResult.number

Title: how to access the struct?

Body:
struct result {
  int number;
  int length;
};

struct result findLongestSeq(int intarray[], int size) {
  result->number // undefined symbol
}

how to access the struct result inside the function findLongestSeq?

thanks

Body:
You have to keep in mind that by simply typing

struct result {
  int number;
  int length;
};

you only define how a struct with name result actually looks like, i.e. of what parts it is made up. This is a general definition, but you have variable of that type yet.

To access values of this struct you have to create a variable by

struct result myResult;

or however you want to call it. At this point you are able to access the members of this struct with  myResult.number


问:
Keep React Native Animated position on re-render
So I'm creating a screen on React native that has a button at the bottom end. When it's clicked it moves a searchbar from the bottom to the top of screen and everything that was on top of it is moved to the side out of screen view. Then it renders a ListView. So far so good. My problem is when a do my search that it receives data from api and populate ListView, as its re-rendering the component, everything is moved back to its initial place. I want to know if there's a way to re-render only my ListView, or keep the animated position after re-render.</p>

答: One easy way to keep the animated position after re-render, is by setting a alreadyAnimated boolean value in the state of your component. Initialize this value to false and set it to true when calling the function that triggers your animation. Then, conditionally call the animation only if this.state.alreadyAnimated is false and only set the initial animated value/position of your searchbar if alreadyAnimated is false.