问:
Converting tuple inside list into a standalone tuple
I currently have a list called TrackedPoints containing tuples inside of it, I can see the values I want stored inside of it in my debugger as a tuple

TrackedPoints: [(350,350),(543,345)]

I'm currently using this code to extract the tuple i want

StartLineX = [TrackedPoints[0] for x in TrackedPoints]

This is setting StartLineX to [(350,350)]

How do i go about converting StartLineX into a tuple? I've used the tuple() function but it keeps returning the data like this, which throws an exception in my application:

((350,350),)

Any help would be much appreciated.

答:
StartLineX = [TrackedPoints[0] for x in TrackedPoints]: The part between the brackets is called a List Comprehension. This creates another list.

What you want is to take the first element from the list:
StartLineX = TrackedPoints[0].

This will fail if the TrackedPoints-list is empty.

if TrackedPoints:  # Check if list is empty.
    StartLineX = TrackedPoints[0]
else:
    pass # Handle the error in some way that works for you.
```


来源: stackexchange

问:
Quarkus getting-started application throws exception workerPoolSize must be > 0
I was following the steps written here:
https://quarkus.io/guides/getting-started#bootstrapping-the-project

Github link:
https://github.com/sujoydc/quarkus-getting-started

System Details:

Apache Maven 3.6.3

Java version: 1.8.0

OS name: "mac os x", version: "10.15.3", arch: "x86_64", family: "mac"

Local compilation result:

```<code>└─[ ✓ ] ॐ  mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.acme:getting-started >----------------------
[INFO] Building getting-started 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ getting-started ---
[INFO] Nothing to compile - all classes are up to date
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.399 s
[INFO] Finished at: 2020-02-13T22:14:23-05:00
[INFO] ------------------------------------------------------------------------
</code>```

pom.xml

```<code>    <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.acme</groupId>
  <artifactId>getting-started</artifactId>
  <version>1.0-SNAPSHOT</version>
  <properties>
    <compiler-plugin.version>3.8.1</compiler-plugin.version>
    <maven.compiler.parameters>true</maven.compiler.parameters>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <quarkus-plugin.version>1.2.0.Final</quarkus-plugin.version>
    <quarkus.platform.artifact-id>quarkus-universe-bom</quarkus.platform.artifact-id>
    <quarkus.platform.group-id>io.quarkus</quarkus.platform.group-id>
    <quarkus.platform.version>1.2.0.Final</quarkus.platform.version>
    <surefire-plugin.version>2.22.1</surefire-plugin.version>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>${quarkus.platform.group-id}</groupId>
        <artifactId>${quarkus.platform.artifact-id}</artifactId>
        <version>${quarkus.platform.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-junit5</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-maven-plugin</artifactId>
        <version>${quarkus-plugin.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>build</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${compiler-plugin.version}</version>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
          <systemProperties>
            <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
          </systemProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <profiles>
    <profile>
      <id>native</id>
      <activation>
        <property>
          <name>native</name>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>${surefire-plugin.version}</version>
            <executions>
              <execution>
                <goals>
                  <goal>integration-test</goal>
                  <goal>verify</goal>
                </goals>
                <configuration>
                  <systemProperties>
                    <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
                  </systemProperties>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
      <properties>
        <quarkus.package.type>native</quarkus.package.type>
      </properties>
    </profile>
  </profiles>
</project>
</code>```

After the following statement, I get this exception "Failed to start quarkus: java.lang.IllegalArgumentException: workerPoolSize must be > 0".
I just followed the steps and I don't know where do we set this param "workerPoolSize".

The full stack trace below:

```<code>  ./mvnw compile quarkus:dev

[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.acme:getting-started >----------------------
[INFO] Building getting-started 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ getting-started ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- quarkus-maven-plugin:1.2.0.Final:dev (default-cli) @ getting-started ---
Listening for transport dt_socket at address: 5005
06:38:08,033 INFO  [org.jbo.threads] JBoss Threads version 3.0.0.Final
06:38:08,235 ERROR [io.qua.dev.DevModeMain] Failed to start Quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor#setupProviders threw an exception: java.lang.UnsupportedOperationException
    at java.util.concurrent.CopyOnWriteArrayList$COWIterator.set(CopyOnWriteArrayList.java:1185)
    at java.util.Collections.sort(Collections.java:170)
    at org.jboss.resteasy.core.MediaTypeMap.add(MediaTypeMap.java:312)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.categorizeProviders(ResteasyCommonProcessor.java:218)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.setupProviders(ResteasyCommonProcessor.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:915)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:279)
    at io.quarkus.builder.BuildContext$$Lambda$112/468968371.run(Unknown Source)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2011)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1535)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1426)
    at java.lang.Thread.run(Thread.java:744)
    at org.jboss.threads.JBossThread.run(JBossThread.java:479)

    at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:181)
    at io.quarkus.dev.DevModeMain.doStart(DevModeMain.java:178)
    at io.quarkus.dev.DevModeMain.start(DevModeMain.java:96)
    at io.quarkus.dev.DevModeMain.main(DevModeMain.java:67)
Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor#setupProviders threw an exception: java.lang.UnsupportedOperationException
    at java.util.concurrent.CopyOnWriteArrayList$COWIterator.set(CopyOnWriteArrayList.java:1185)
    at java.util.Collections.sort(Collections.java:170)
    at org.jboss.resteasy.core.MediaTypeMap.add(MediaTypeMap.java:312)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.categorizeProviders(ResteasyCommonProcessor.java:218)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.setupProviders(ResteasyCommonProcessor.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:915)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:279)
    at io.quarkus.builder.BuildContext$$Lambda$112/468968371.run(Unknown Source)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2011)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1535)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1426)
    at java.lang.Thread.run(Thread.java:744)
    at org.jboss.threads.JBossThread.run(JBossThread.java:479)

    at io.quarkus.builder.Execution.run(Execution.java:108)
    at io.quarkus.builder.BuildExecutionBuilder.execute(BuildExecutionBuilder.java:79)
    at io.quarkus.deployment.QuarkusAugmentor.run(QuarkusAugmentor.java:128)
    at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:114)
    ... 3 more
Caused by: java.lang.UnsupportedOperationException
    at java.util.concurrent.CopyOnWriteArrayList$COWIterator.set(CopyOnWriteArrayList.java:1185)
    at java.util.Collections.sort(Collections.java:170)
    at org.jboss.resteasy.core.MediaTypeMap.add(MediaTypeMap.java:312)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.categorizeProviders(ResteasyCommonProcessor.java:218)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.setupProviders(ResteasyCommonProcessor.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:915)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:279)
    at io.quarkus.builder.BuildContext$$Lambda$112/468968371.run(Unknown Source)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2011)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1535)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1426)
    at java.lang.Thread.run(Thread.java:744)
    at org.jboss.threads.JBossThread.run(JBossThread.java:479)

06:38:08,238 INFO  [io.qua.dev.DevModeMain] Attempting to start hot replacement endpoint to recover from previous Quarkus startup failure
06:38:08,247 ERROR [io.qua.dev.DevModeMain] Failed to start quarkus: java.lang.IllegalArgumentException: workerPoolSize must be > 0
    at io.vertx.core.VertxOptions.setWorkerPoolSize(VertxOptions.java:275)
    at io.quarkus.vertx.core.runtime.VertxCoreRecorder.convertToVertxOptions(VertxCoreRecorder.java:152)
    at io.quarkus.vertx.core.runtime.VertxCoreRecorder.initializeWeb(VertxCoreRecorder.java:105)
    at io.quarkus.vertx.http.runtime.VertxHttpRecorder.startServerAfterFailedStart(VertxHttpRecorder.java:119)
    at io.quarkus.vertx.http.deployment.devmode.VertxHotReplacementSetup.handleFailedInitialStart(VertxHotReplacementSetup.java:30)
    at io.quarkus.dev.RuntimeUpdatesProcessor.startupFailed(RuntimeUpdatesProcessor.java:452)
    at io.quarkus.dev.DevModeMain.doStart(DevModeMain.java:192)
    at io.quarkus.dev.DevModeMain.start(DevModeMain.java:96)
    at io.quarkus.dev.DevModeMain.main(DevModeMain.java:67)
</code>```

答:
I've checked your code, you are having compilation error in your resources class, please replace your hello method with the below:

```<code>@GET
@Produces(MediaType.TEXT_PLAIN)
public Response hello() {
    return Response.ok().entity("hello").build();
}
</code>```

Default code generated by Quarkus was like this :

```<code>@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
    return "hello";
}
</code>```

It worked with java version "openjdk-11.0.2.jdk" and NOT with version "jdk1.8.0.jdk".

ContentLicense: CC BY-SA 4.0

Body:
I was following the steps written here:
https://quarkus.io/guides/getting-started#bootstrapping-the-project

Github link:
https://github.com/sujoydc/quarkus-getting-started

System Details:

Apache Maven 3.6.3

Java version: 1.8.0

OS name: "mac os x", version: "10.15.3", arch: "x86_64", family: "mac"

Local compilation result:

└─[ ✓ ] ॐ  mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.acme:getting-started >----------------------
[INFO] Building getting-started 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ getting-started ---
[INFO] Nothing to compile - all classes are up to date
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.399 s
[INFO] Finished at: 2020-02-13T22:14:23-05:00
[INFO] ------------------------------------------------------------------------

pom.xml

    <?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.acme</groupId>
  <artifactId>getting-started</artifactId>
  <version>1.0-SNAPSHOT</version>
  <properties>
    <compiler-plugin.version>3.8.1</compiler-plugin.version>
    <maven.compiler.parameters>true</maven.compiler.parameters>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <quarkus-plugin.version>1.2.0.Final</quarkus-plugin.version>
    <quarkus.platform.artifact-id>quarkus-universe-bom</quarkus.platform.artifact-id>
    <quarkus.platform.group-id>io.quarkus</quarkus.platform.group-id>
    <quarkus.platform.version>1.2.0.Final</quarkus.platform.version>
    <surefire-plugin.version>2.22.1</surefire-plugin.version>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>${quarkus.platform.group-id}</groupId>
        <artifactId>${quarkus.platform.artifact-id}</artifactId>
        <version>${quarkus.platform.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-junit5</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-maven-plugin</artifactId>
        <version>${quarkus-plugin.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>build</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${compiler-plugin.version}</version>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
          <systemProperties>
            <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
          </systemProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <profiles>
    <profile>
      <id>native</id>
      <activation>
        <property>
          <name>native</name>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>${surefire-plugin.version}</version>
            <executions>
              <execution>
                <goals>
                  <goal>integration-test</goal>
                  <goal>verify</goal>
                </goals>
                <configuration>
                  <systemProperties>
                    <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
                  </systemProperties>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
      <properties>
        <quarkus.package.type>native</quarkus.package.type>
      </properties>
    </profile>
  </profiles>
</project>

After the following statement, I get this exception "Failed to start quarkus: java.lang.IllegalArgumentException: workerPoolSize must be > 0".
I just followed the steps and I don't know where do we set this param "workerPoolSize".

The full stack trace below:

  ./mvnw compile quarkus:dev

[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.acme:getting-started >----------------------
[INFO] Building getting-started 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ getting-started ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- quarkus-maven-plugin:1.2.0.Final:dev (default-cli) @ getting-started ---
Listening for transport dt_socket at address: 5005
06:38:08,033 INFO  [org.jbo.threads] JBoss Threads version 3.0.0.Final
06:38:08,235 ERROR [io.qua.dev.DevModeMain] Failed to start Quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor#setupProviders threw an exception: java.lang.UnsupportedOperationException
    at java.util.concurrent.CopyOnWriteArrayList$COWIterator.set(CopyOnWriteArrayList.java:1185)
    at java.util.Collections.sort(Collections.java:170)
    at org.jboss.resteasy.core.MediaTypeMap.add(MediaTypeMap.java:312)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.categorizeProviders(ResteasyCommonProcessor.java:218)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.setupProviders(ResteasyCommonProcessor.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:915)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:279)
    at io.quarkus.builder.BuildContext$$Lambda$112/468968371.run(Unknown Source)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2011)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1535)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1426)
    at java.lang.Thread.run(Thread.java:744)
    at org.jboss.threads.JBossThread.run(JBossThread.java:479)

    at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:181)
    at io.quarkus.dev.DevModeMain.doStart(DevModeMain.java:178)
    at io.quarkus.dev.DevModeMain.start(DevModeMain.java:96)
    at io.quarkus.dev.DevModeMain.main(DevModeMain.java:67)
Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor#setupProviders threw an exception: java.lang.UnsupportedOperationException
    at java.util.concurrent.CopyOnWriteArrayList$COWIterator.set(CopyOnWriteArrayList.java:1185)
    at java.util.Collections.sort(Collections.java:170)
    at org.jboss.resteasy.core.MediaTypeMap.add(MediaTypeMap.java:312)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.categorizeProviders(ResteasyCommonProcessor.java:218)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.setupProviders(ResteasyCommonProcessor.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:915)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:279)
    at io.quarkus.builder.BuildContext$$Lambda$112/468968371.run(Unknown Source)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2011)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1535)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1426)
    at java.lang.Thread.run(Thread.java:744)
    at org.jboss.threads.JBossThread.run(JBossThread.java:479)

    at io.quarkus.builder.Execution.run(Execution.java:108)
    at io.quarkus.builder.BuildExecutionBuilder.execute(BuildExecutionBuilder.java:79)
    at io.quarkus.deployment.QuarkusAugmentor.run(QuarkusAugmentor.java:128)
    at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:114)
    ... 3 more
Caused by: java.lang.UnsupportedOperationException
    at java.util.concurrent.CopyOnWriteArrayList$COWIterator.set(CopyOnWriteArrayList.java:1185)
    at java.util.Collections.sort(Collections.java:170)
    at org.jboss.resteasy.core.MediaTypeMap.add(MediaTypeMap.java:312)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.categorizeProviders(ResteasyCommonProcessor.java:218)
    at io.quarkus.resteasy.common.deployment.ResteasyCommonProcessor.setupProviders(ResteasyCommonProcessor.java:146)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:915)
    at io.quarkus.builder.BuildContext.run(BuildContext.java:279)
    at io.quarkus.builder.BuildContext$$Lambda$112/468968371.run(Unknown Source)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2011)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1535)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1426)
    at java.lang.Thread.run(Thread.java:744)
    at org.jboss.threads.JBossThread.run(JBossThread.java:479)

06:38:08,238 INFO  [io.qua.dev.DevModeMain] Attempting to start hot replacement endpoint to recover from previous Quarkus startup failure
06:38:08,247 ERROR [io.qua.dev.DevModeMain] Failed to start quarkus: java.lang.IllegalArgumentException: workerPoolSize must be > 0
    at io.vertx.core.VertxOptions.setWorkerPoolSize(VertxOptions.java:275)
    at io.quarkus.vertx.core.runtime.VertxCoreRecorder.convertToVertxOptions(VertxCoreRecorder.java:152)
    at io.quarkus.vertx.core.runtime.VertxCoreRecorder.initializeWeb(VertxCoreRecorder.java:105)
    at io.quarkus.vertx.http.runtime.VertxHttpRecorder.startServerAfterFailedStart(VertxHttpRecorder.java:119)
    at io.quarkus.vertx.http.deployment.devmode.VertxHotReplacementSetup.handleFailedInitialStart(VertxHotReplacementSetup.java:30)
    at io.quarkus.dev.RuntimeUpdatesProcessor.startupFailed(RuntimeUpdatesProcessor.java:452)
    at io.quarkus.dev.DevModeMain.doStart(DevModeMain.java:192)
    at io.quarkus.dev.DevModeMain.start(DevModeMain.java:96)
    at io.quarkus.dev.DevModeMain.main(DevModeMain.java:67)

Body:
I've checked your code, you are having compilation error in your resources class, please replace your hello method with the below:

@GET
@Produces(MediaType.TEXT_PLAIN)
public Response hello() {
    return Response.ok().entity("hello").build();
}

Default code generated by Quarkus was like this :

@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
    return "hello";
}

It worked with java version "openjdk-11.0.2.jdk" and NOT with version "jdk1.8.0.jdk".


问:
Why is a reference needed in operator overloading?
In what situations would a reference be needed when overloading, as the code still works without it? I am aware it has something to with chaining, but I do not understand exactly why the reference is needed.

Example:

```<code>Object& operator++();
</code>```

答:
Let's look at your example - we may want to increase the same object twice, therefore, we may wish to do the following:

```<code>#include <iostream>

class MyObject
{
    public:

    MyObject()
    {
        cnt = 0;
    }

    MyObject& operator++()
    {
        ++cnt;
        return *this;
    }

    int cnt;
};

int main()
{
  MyObject obj{};
  std::cout << "The value at start " << obj.cnt << std::endl;
  ++obj;
  std::cout << "The value after increment " << obj.cnt << std::endl;

  ++(++obj); // Legal ONLY when returning a reference!
  std::cout << "The value after two increments in the same time: " << obj.cnt << std::endl;
}
</code>```

In this case, we increase the the counter twice using chaining, and as we expected, we get the following result:

```<code>The value at start 0
The value after increment 1
The value after two increments in the same time: 3
</code>```

If we should return an object and not a reference to this, then, we operate on a l-value reference (since this object doesn't have a name!), therefore, this chaining would do nothing to the original object, as can seen in the following example:

```<code>#include <iostream>

class MyObject
{
    public:

    MyObject()
    {
        cnt = 0;
    }

    MyObject(const MyObject& other)
    {
        this->cnt = other.cnt;
    }

    MyObject operator++()
    {
        MyObject tmp(*this);

        ++cnt;

        return tmp;
    }

    int cnt;
};

int main()
{
  MyObject obj{};
  std::cout << "The value at start " << obj.cnt << std::endl;
  ++obj;
  std::cout << "The value after increment " << obj.cnt << std::endl;

  ++(++obj); // Legal ONLY when returning a reference!
  std::cout << "The value after two increments in the same time: " << obj.cnt << std::endl;
}
</code>```

output:

```<code>The value at start 0
The value after increment 1
The value after two increments in the same time: 2
</code>```

Body:
In what situations would a reference be needed when overloading, as the code still works without it? I am aware it has something to with chaining, but I do not understand exactly why the reference is needed.

Example:

Object& operator++();

Body:
Let's look at your example - we may want to increase the same object twice, therefore, we may wish to do the following:

#include <iostream>

class MyObject
{
    public:

    MyObject()
    {
        cnt = 0;
    }

    MyObject& operator++()
    {
        ++cnt;
        return *this;
    }

    int cnt;
};

int main()
{
  MyObject obj{};
  std::cout << "The value at start " << obj.cnt << std::endl;
  ++obj;
  std::cout << "The value after increment " << obj.cnt << std::endl;

  ++(++obj); // Legal ONLY when returning a reference!
  std::cout << "The value after two increments in the same time: " << obj.cnt << std::endl;
}

In this case, we increase the the counter twice using chaining, and as we expected, we get the following result:

The value at start 0
The value after increment 1
The value after two increments in the same time: 3

If we should return an object and not a reference to this, then, we operate on a l-value reference (since this object doesn't have a name!), therefore, this chaining would do nothing to the original object, as can seen in the following example:

#include <iostream>

class MyObject
{
    public:

    MyObject()
    {
        cnt = 0;
    }

    MyObject(const MyObject& other)
    {
        this->cnt = other.cnt;
    }

    MyObject operator++()
    {
        MyObject tmp(*this);

        ++cnt;

        return tmp;
    }

    int cnt;
};

int main()
{
  MyObject obj{};
  std::cout << "The value at start " << obj.cnt << std::endl;
  ++obj;
  std::cout << "The value after increment " << obj.cnt << std::endl;

  ++(++obj); // Legal ONLY when returning a reference!
  std::cout << "The value after two increments in the same time: " << obj.cnt << std::endl;
}

output:

The value at start 0
The value after increment 1
The value after two increments in the same time: 2


问:
python tuples: unpacking into a list using *args
Hello and thanks for your time;

I am using *args to take various arguments, which creates a tuple. How do I 'unpack' a tuple into a list? The following code appends the list with a tuple.

```<code>grades = []

def add_grades(*args):
    grades.append(args):
    return grades

print(add_grades(99,88,77))
</code>```

I can do this using a for loop and iterating through the tuple, but looking to see if I can unpack directly.

答:
You can use the list.extend method instead:

```<code>def add_grades(*args):
    grades.extend(args):
    return grades
</code>```

Body:
Hello and thanks for your time;

I am using *args to take various arguments, which creates a tuple. How do I 'unpack' a tuple into a list? The following code appends the list with a tuple.

grades = []

def add_grades(*args):
    grades.append(args):
    return grades

print(add_grades(99,88,77))

I can do this using a for loop and iterating through the tuple, but looking to see if I can unpack directly.

Body:
You can use the list.extend method instead:

def add_grades(*args):
    grades.extend(args):
    return grades


问:
Apply Function to MultiIndex DataFrame by Groupby
I want to groupby('Ticker') this multiIndex Dataframe and then Apply a function that returns a Series for each ticker and add the result to a new column on the df.

```<code>def Indicator(dataf):

    df = dataf.copy()
    df['TR1'] = df.High.sub(df.Low)
    df['TR2'] = abs(df.High.sub(df.Close.shift(1)))
    df['TR3'] = abs(df.Low.sub(df.Close.shift(1)))
    df['TR'] = df[['TR1', 'TR2', 'TR3']].max(axis=1)
    df['TR_mean'] = df['TR'].resample('M').mean().shift(1).resample('D').fillna('bfill')
    df['Vol_mean'] = df['Volume'].resample('M').mean().shift(1).resample('D').fillna('bfill')
    indicator = (df.TR.div(df.TR_mean)).div(df.Volume.div(df.Vol_mean))

    return indicator
</code>```

I try something Like this:

```<code>tickers.groupby('Ticker').apply(Indicator)
</code>```

But I get this error:
Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'

Dataframe:

```<code>                        Close           High         Low               Open         Volume
Date        Ticker
2010-01-04  AAPL        6048.299805    6048.299805  5974.430176 5975.520020 1.043444e+08
            GOOG        1132.989990    1133.869995  1116.560059 1116.560059 3.991400e+09
            TSM         10654.79003    10694.49023  10608.13948 10609.33984 1.044000e+05
2010-01-05  AAPL        6031.859863    6058.020020  6015.669922 6043.939941 1.175721e+08
            GOOG        1132.989990    1133.869995  1116.560059 1116.560059 3.991400e+09
            TSM         10654.79003    10694.49023  10608.13948 10609.33984 1.044000e+05
</code>```

答:
In order to fix that error, you just need to add the following line in the Indicator function, after the copy operation:

```<code>df.index = df.index.get_level_values(0)
</code>```

The problem indeed is due to the fact you pass a MultiIndex instead of a DateTime index to the resample method in the function (which is a function to work with time series). What the extra line is doing is basically replacing the MultiIndex by just the DateTime part of the index. This results in the following:

```<code>>>> df_orig
                          Close          High           Low          Open        Volume
Date       Ticker
2010-01-04 AAPL     6048.299805   6048.299805   5974.430176   5975.520020  1.043444e+08
           GOOGL    1132.989990   1133.869995   1116.560059   1116.560059  3.991400e+09
           TSM     10654.790030  10694.490230  10608.139480  10609.339840  1.044000e+05
2010-01-05 AAPL     6031.859863   6058.020020   6015.669922   6043.939941  1.175721e+08
           GOOGL    1132.989990   1133.869995   1116.560059   1116.560059  3.991400e+09
           TSM     10654.790030  10694.490230  10608.139480  10609.339840  1.044000e+05

>>> df_orig.info()
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 6 entries, (2010-01-04 00:00:00, AAPL) to (2010-01-05 00:00:00, TSM)
Data columns (total 5 columns):
Close     6 non-null float64
High      6 non-null float64
Low       6 non-null float64
Open      6 non-null float64
Volume    6 non-null float64
dtypes: float64(5)
memory usage: 410.0+ bytes

>>> df_orig.groupby("Ticker").apply(Indicator)
Date    2010-01-04  2010-01-05
Ticker
AAPL           NaN         NaN
GOOGL          NaN         NaN
TSM            NaN         NaN
</code>```

Of course you can also remove the Ticker column prior to the groupby-apply part like this:

```<code>ticker_idx = df_orig.index.get_level_values(1)
df_orig.reset_index(1, drop=True).groupby(ticker_idx).apply(Indicator)
</code>```

This way you don't need to add that extra line in the function.

Also, I'm getting a bunch of NaN as result of the groupby-apply operation, but by looking at your function's code, I assume that's due to the fact the function was expecting more data then 2 days. Let me know if this is correct.

Body:
I want to groupby('Ticker') this multiIndex Dataframe and then Apply a function that returns a Series for each ticker and add the result to a new column on the df.

def Indicator(dataf):

    df = dataf.copy()
    df['TR1'] = df.High.sub(df.Low)
    df['TR2'] = abs(df.High.sub(df.Close.shift(1)))
    df['TR3'] = abs(df.Low.sub(df.Close.shift(1)))
    df['TR'] = df[['TR1', 'TR2', 'TR3']].max(axis=1)
    df['TR_mean'] = df['TR'].resample('M').mean().shift(1).resample('D').fillna('bfill')
    df['Vol_mean'] = df['Volume'].resample('M').mean().shift(1).resample('D').fillna('bfill')
    indicator = (df.TR.div(df.TR_mean)).div(df.Volume.div(df.Vol_mean))

    return indicator

I try something Like this:

tickers.groupby('Ticker').apply(Indicator)

But I get this error:
Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'

Dataframe:

                        Close           High         Low               Open         Volume
Date        Ticker
2010-01-04  AAPL        6048.299805    6048.299805  5974.430176 5975.520020 1.043444e+08
            GOOG        1132.989990    1133.869995  1116.560059 1116.560059 3.991400e+09
            TSM         10654.79003    10694.49023  10608.13948 10609.33984 1.044000e+05
2010-01-05  AAPL        6031.859863    6058.020020  6015.669922 6043.939941 1.175721e+08
            GOOG        1132.989990    1133.869995  1116.560059 1116.560059 3.991400e+09
            TSM         10654.79003    10694.49023  10608.13948 10609.33984 1.044000e+05

Body:
In order to fix that error, you just need to add the following line in the Indicator function, after the copy operation:

df.index = df.index.get_level_values(0)

The problem indeed is due to the fact you pass a MultiIndex instead of a DateTime index to the resample method in the function (which is a function to work with time series). What the extra line is doing is basically replacing the MultiIndex by just the DateTime part of the index. This results in the following:

>>> df_orig
                          Close          High           Low          Open        Volume
Date       Ticker
2010-01-04 AAPL     6048.299805   6048.299805   5974.430176   5975.520020  1.043444e+08
           GOOGL    1132.989990   1133.869995   1116.560059   1116.560059  3.991400e+09
           TSM     10654.790030  10694.490230  10608.139480  10609.339840  1.044000e+05
2010-01-05 AAPL     6031.859863   6058.020020   6015.669922   6043.939941  1.175721e+08
           GOOGL    1132.989990   1133.869995   1116.560059   1116.560059  3.991400e+09
           TSM     10654.790030  10694.490230  10608.139480  10609.339840  1.044000e+05

>>> df_orig.info()
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 6 entries, (2010-01-04 00:00:00, AAPL) to (2010-01-05 00:00:00, TSM)
Data columns (total 5 columns):
Close     6 non-null float64
High      6 non-null float64
Low       6 non-null float64
Open      6 non-null float64
Volume    6 non-null float64
dtypes: float64(5)
memory usage: 410.0+ bytes

>>> df_orig.groupby("Ticker").apply(Indicator)
Date    2010-01-04  2010-01-05
Ticker
AAPL           NaN         NaN
GOOGL          NaN         NaN
TSM            NaN         NaN

Of course you can also remove the Ticker column prior to the groupby-apply part like this:

ticker_idx = df_orig.index.get_level_values(1)
df_orig.reset_index(1, drop=True).groupby(ticker_idx).apply(Indicator)

This way you don't need to add that extra line in the function.

Also, I'm getting a bunch of NaN as result of the groupby-apply operation, but by looking at your function's code, I assume that's due to the fact the function was expecting more data then 2 days. Let me know if this is correct.


问:
Vaadin - GWT dependency always needed?
Is the GWT mandatory in a deployment with Vaadin framework.

I mean is the Vaadin framework builded over the GWT and then not using GWT is not possible.
I ask because some manager asked me but I was not able to answer if it can be used separately or not.

I know the GWT does not need Vaadin but what about the inverse?

答: You can use Vaadin without GWT. Vaadin 7 and 8 client side code is precompiled with GWT. Thus you need GWT only for adding new widgets to Vaadin 7 or 8.</p>

ContentLicense: CC BY-SA 3.0

Title: Vaadin - GWT dependency always needed?


问:
Sorting the columns based on value of a column. Pandas
df1

```<code>ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        A           30000
23661      BIKE          BLUE        B           43563
23661      BIKE          BLUE        C           45124
23661      BIKE          BLUE        D           28000
48684      CAR           RED         B           45145
48684      CAR           RED         D           35613
48684      CAR           RED         A           82312
48684      CAR           RED         C           24536
48684      CAR           RED         E           45613
54519      BIKE          BLACK       A           21345
54519      BIKE          BLACK       B           62623
54519      BIKE          BLACK       C           14613
54519      BIKE          BLACK       E           14365
54519      BIKE          BLACK       D           67353
</code>```

Expecting outcome is the location that has the highest price for the vehicle.

```<code>ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        C           45124
48684      CAR           RED         A           82312
54519      BIKE          BLACK       D           67353
</code>```

df.sort_values(df['PRICE'],  ascending=False, kind='quicksort') Using this code we can manually do one by one. How to do this for the whole df.

答: U can do groupby on color column & then apply sort function on price: Something like this  df.groupby(["COLOR"]).apply(lambda x: x.sort_values(["PRICE"], ascending = False))</p>

Body:
df1

ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        A           30000
23661      BIKE          BLUE        B           43563
23661      BIKE          BLUE        C           45124
23661      BIKE          BLUE        D           28000
48684      CAR           RED         B           45145
48684      CAR           RED         D           35613
48684      CAR           RED         A           82312
48684      CAR           RED         C           24536
48684      CAR           RED         E           45613
54519      BIKE          BLACK       A           21345
54519      BIKE          BLACK       B           62623
54519      BIKE          BLACK       C           14613
54519      BIKE          BLACK       E           14365
54519      BIKE          BLACK       D           67353

Expecting outcome is the location that has the highest price for the vehicle.

ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        C           45124
48684      CAR           RED         A           82312
54519      BIKE          BLACK       D           67353

df.sort_values(df['PRICE'],  ascending=False, kind='quicksort') Using this code we can manually do one by one. How to do this for the whole df.


问:
How to use custom variable in JavaScript
I just want to know to how to use custom varible with javascript.suppose we have 5 id with name zawsz,baws2,tawsx,paws4,vawsa and we want to execute single DOM command to all these element whose id is define here.

```<code>document.getElementById("-aws-").onclick=function(){}
</code>```

Here -aws- define all the id define above.(-) can be replace with any char/int value;

答:
You could use the following code:
(The following code will select all elements of which the id includes aws.
I have tested this code and it works: https://jsfiddle.net/5042woqz/)

```<code>document.querySelectorAll('*[id*="aws"]').forEach(function(item) {
    item.onclick=function() {
        console.log('click!');
    };
});
</code>```

Items will now be an array containing all your aws- items.
If you have further questions, just let me know.

P.S.: You could achieve the same thing really easily with jquery.

Body:
I just want to know to how to use custom varible with javascript.suppose we have 5 id with name zawsz,baws2,tawsx,paws4,vawsa and we want to execute single DOM command to all these element whose id is define here.

document.getElementById("-aws-").onclick=function(){}

Here -aws- define all the id define above.(-) can be replace with any char/int value;

Body:
You could use the following code:
(The following code will select all elements of which the id includes aws.
I have tested this code and it works: https://jsfiddle.net/5042woqz/)

document.querySelectorAll('*[id*="aws"]').forEach(function(item) {
    item.onclick=function() {
        console.log('click!');
    };
});

Items will now be an array containing all your aws- items.
If you have further questions, just let me know.

P.S.: You could achieve the same thing really easily with jquery.


问:
Getting documents with ID from firstore collection React
I don't know how to get a generited by Firestsore document (shop) ID in array of shops which firebase give me back....

```<code>    componentDidMount() {
    let response = fire.firestore().collection('shops').
    get().
    then(snapshot => {
        const data = snapshot.docs.map(doc => doc.data());
        this.setState({
            ...this.state,
            shopsArray: data
        })
    })
}
</code>```

答:
To get the ID of the document, use the DocumentSnapshot.id property. So something like:

```<code>componentDidMount() {
    let response = fire.firestore().collection('shops').
    get().
    then(snapshot => {
        snapshot.docs.forEach((doc) => { console.log(doc.id); });
        ...
</code>```

Body:
I don't know how to get a generited by Firestsore document (shop) ID in array of shops which firebase give me back....

    componentDidMount() {
    let response = fire.firestore().collection('shops').
    get().
    then(snapshot => {
        const data = snapshot.docs.map(doc => doc.data());
        this.setState({
            ...this.state,
            shopsArray: data
        })
    })
}

Body:
To get the ID of the document, use the DocumentSnapshot.id property. So something like:

componentDidMount() {
    let response = fire.firestore().collection('shops').
    get().
    then(snapshot => {
        snapshot.docs.forEach((doc) => { console.log(doc.id); });
        ...


问:
React datepicker set min and max date
I am using react-datepicker in my project.

I need to display only days for a specific month (lets say February 2020). I was under the impression that I could pass iso dates as minDate and maxDate but this does not seem to work.

My code:

```<code>   const DatePickerMod = () => {
    const [startDate, setStartDate] = useState(null);
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      minDate={'02-01-2020'}
      maxDate={'02-29-2020}
      placeholderText="Select a date in February 2020"
    />
  );
  };
</code>```

答:
pass your date (with that format) as string to a new Date() instance like so:

 <DatePicker
    selected={startDate}
    onChange={date => setStartDate(date)}
    minDate={new Date("02-01-2020")}
    maxDate={new Date("02-29-2020")}
    placeholderText="Select a date in February 2020"
/>```

Title: React datepicker set min and max date

Body:
I am using react-datepicker in my project.

I need to display only days for a specific month (lets say February 2020). I was under the impression that I could pass iso dates as minDate and maxDate but this does not seem to work.

My code:

   const DatePickerMod = () => {
    const [startDate, setStartDate] = useState(null);
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      minDate={'02-01-2020'}
      maxDate={'02-29-2020}
      placeholderText="Select a date in February 2020"
    />
  );
  };


问:
Heroku not updating css for rails app
I'm having trouble updating my rails app on heroku.  I've gotten my app up but I tried to change my application.css file in /public/stylesheets/ but whenever I try to push to heroku, the CSS never changes.  I tested these changes locally and they work just fine, I just can't figure out how to push them to heroku.  I've tried pushing with    git push heroku, heroku db:push, and heroku rake db:migrate but nothing works.  Thanks for your help.</p>

答:
Remember that you have to commit the changes locally before you can push them.

If you do a git status, it should be clean.

If it's not (my prediction):

```<code>git commit -am "Your commit message"
git push heroku master
</code>```

Title: Heroku not updating css for rails app

Body:
Remember that you have to commit the changes locally before you can push them.

If you do a git status, it should be clean.

If it's not (my prediction):

git commit -am "Your commit message"
git push heroku master


问:
Flutter: Listview in AlterDialog not scrollable
I need an AlertDialog with minHeight of 50. It contains a ListView. If the ListView exceeds the screen it should become scrollable. But I can't scroll for some reason. Can anyone explain to me why it's not working :)

```<code> AlertDialog(
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
  title: ... ,
  content: ConstrainedBox(
    constraints: new BoxConstraints(
      minHeight: 50,
    ),
    child: Column(
      children: <Widget>[
        Row(...),
        Container(
          child:  ListView.builder(
            shrinkWrap: true,
            itemCount: list.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: () => _onTap(list[index]),
                child: Row(
                  children: <Widget>[
                    Flexible(
                      flex: 1,
                      child: Checkbox(...),
                    ),
                    Flexible(
                      flex: 3,
                      child: Text(list[index]),)
                  ],
                )
              );
            },
          )
        )
      ],
    ),
   ),
  actions: <Widget>[
    MaterialButton(
      minWidth:100,
      child: Text('Cancel'),
      onPressed: (){
        Navigator.of(context).pop();
      }
    ),
    MaterialButton(
      minWidth:100,
      elevation: 5.0,
      color: Theme.of(context).accentColor,
      child: Text('Save', style: TextStyle(color: Color(0xFFF6F5F5))),
      onPressed: (){

      }
    )
  ],
);
</code>```

答: Add mainAxisSize: MainAxisSize.min to your Column. Without it, your Column is at infinite height and contains all Listview items. That's why it does not scroll.</p>

Body:
I need an AlertDialog with minHeight of 50. It contains a ListView. If the ListView exceeds the screen it should become scrollable. But I can't scroll for some reason. Can anyone explain to me why it's not working :)

 AlertDialog(
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
  title: ... ,
  content: ConstrainedBox(
    constraints: new BoxConstraints(
      minHeight: 50,
    ),
    child: Column(
      children: <Widget>[
        Row(...),
        Container(
          child:  ListView.builder(
            shrinkWrap: true,
            itemCount: list.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: () => _onTap(list[index]),
                child: Row(
                  children: <Widget>[
                    Flexible(
                      flex: 1,
                      child: Checkbox(...),
                    ),
                    Flexible(
                      flex: 3,
                      child: Text(list[index]),)
                  ],
                )
              );
            },
          )
        )
      ],
    ),
   ),
  actions: <Widget>[
    MaterialButton(
      minWidth:100,
      child: Text('Cancel'),
      onPressed: (){
        Navigator.of(context).pop();
      }
    ),
    MaterialButton(
      minWidth:100,
      elevation: 5.0,
      color: Theme.of(context).accentColor,
      child: Text('Save', style: TextStyle(color: Color(0xFFF6F5F5))),
      onPressed: (){

      }
    )
  ],
);


问:
Best way to find lowest number in a list of objects using math.min?
Heres my code, which works but i feel like there is a more simple way doing this. The bold part is where i want to change.</p>

```<code>interface properties {
    age: number;
    salary: number;
    name: string;
}
let minSalary: any;
let maxSalary: any;

let list: properties[] = [
    {name: "P", age: 12, salary: 100},
    {name: "S", age: 80, salary: 12000},
    {name: "Q", age: 25, salary: 80000},
    {name: "W", age: 55, salary: 45000},
    {name: "E", age: 32, salary: 25000},
    {name: "V", age: 5, salary: 0}
];

**minSalary =  Math.min.apply(Math, list.map( salaries => {
    return salaries.salary;** // This is the code i want to make easier
}
));

console.log(minSalary);
</code>```

答:
Instead of properties as a interface, make it a class, and have a method called toString and return this.salary (though it is a number type), and then in do Math.min(...list) directly. You can have a method called valueOf instead of toString as well as an alternate, that will work too.

class properties {
  constructor(name, age, salary) {
    this.name = name;
    this.age = age;
    this.salary = salary;
  }
  toString() { return this.salary; }
}

let list = [
    new properties("P", 12, 100),
    new properties("S", 80, 12000),
    new properties("Q", 25, 80000),
    new properties("W", 55, 45000),
    new properties("E", 32, 25000),
    new properties("V", 5, 0)
];

console.log("Min: ", Math.min(...list));```

As you are compiling it from a Typescript to JavaScript you can write this code in a more cleaner way.

Now, this will work (without overhead) incase you are constructing the data from your side. Incase you are receiving this data, then each object will not contain this toString method. however you can convert each of them to property class instance, but then this will not give you any additional benifit as still you have to use a map, and then min

Body:
Heres my code, which works but i feel like there is a more simple way doing this. The bold part is where i want to change.

interface properties {
    age: number;
    salary: number;
    name: string;
}
let minSalary: any;
let maxSalary: any;

let list: properties[] = [
    {name: "P", age: 12, salary: 100},
    {name: "S", age: 80, salary: 12000},
    {name: "Q", age: 25, salary: 80000},
    {name: "W", age: 55, salary: 45000},
    {name: "E", age: 32, salary: 25000},
    {name: "V", age: 5, salary: 0}
];

**minSalary =  Math.min.apply(Math, list.map( salaries => {
    return salaries.salary;** // This is the code i want to make easier
}
));

console.log(minSalary);

Body:
Instead of properties as a interface, make it a class, and have a method called toString and return this.salary (though it is a number type), and then in do Math.min(...list) directly. You can have a method called valueOf instead of toString as well as an alternate, that will work too.

class properties {
  constructor(name, age, salary) {
    this.name = name;
    this.age = age;
    this.salary = salary;
  }
  toString() { return this.salary; }
}

let list = [
    new properties("P", 12, 100),
    new properties("S", 80, 12000),
    new properties("Q", 25, 80000),
    new properties("W", 55, 45000),
    new properties("E", 32, 25000),
    new properties("V", 5, 0)
];

console.log("Min: ", Math.min(...list));

As you are compiling it from a Typescript to JavaScript you can write this code in a more cleaner way.

Now, this will work (without overhead) incase you are constructing the data from your side. Incase you are receiving this data, then each object will not contain this toString method. however you can convert each of them to property class instance, but then this will not give you any additional benifit as still you have to use a map, and then min


问:
How to get background color of div?
I have a div I want when user clicks on this div the background color of div should be display in alert box using jquery only ?

答:
Try this</p>

```<code><script type="text/javascript">
$(document).ready(function(){
  $("div").click(function(){
    var $c=$(this).css("background-color");
    alert($c);
  });
});
</script>
</code>```

Title: How to get background color of div?

Body:
Try this

<script type="text/javascript">
$(document).ready(function(){
  $("div").click(function(){
    var $c=$(this).css("background-color");
    alert($c);
  });
});
</script>


问:
How i can remove here System.out.println()
Hello guys I would like to know how to remove in my code the system.out.println, because I am passing an object in a method. Thank you

The code is about the sum of two fractions, and I have to pass all the arguments in the two object and then use it in the class to make the sum and the subtraction of the two fraction, I really need help guys thank you so much.

Class

package denominatore;

public class Frazione {
    private int numeratore;
    private int denominatore;

    public Frazione (int num, int den){
        numeratore = num;
        denominatore = den;
    }
    public void somma(Frazione frazioneForadori2){
        System.out.println("La somma è: ");
        System.out.println((numeratore * frazioneForadori2.getDenominatore())+(denominatore * frazioneForadori2.getNumeratore())+"\n--");
        System.out.println(denominatore * frazioneForadori2.getDenominatore());
    }
    public void sottrazione(Frazione frazioneForadori2){
        System.out.println("La sottrazione è: ");
        System.out.println((numeratore * frazioneForadori2.getDenominatore())-(denominatore * frazioneForadori2.getNumeratore())+"\n--");
        System.out.println(denominatore * frazioneForadori2.getDenominatore());
    }
    public int getNumeratore(){
        return numeratore;
    }
    public int getDenominatore(){
        return denominatore;
    }
}
```

答:
Instead of printing the result from each method, return it as a new Frazione (fraction) object. Just fill the calculated numerator and denominator into the new object. For example the somma (sum) method becomes:

```<code>public Frazione somma(Frazione frazioneForadori2){
    return new Frazione((numeratore * frazioneForadori2.getDenominatore())+(denominatore * frazioneForadori2.getNumeratore()),
            denominatore * frazioneForadori2.getDenominatore());
}
</code>```

The sottrazione (subtraction/difference)  method is similar, I am leaving that to you.

In order to print out the result outside the method it’s probably practical to define a toString method for the Frazione class:

```<code>@Override
public String toString() {
    return "" + numeratore + "\n--\n" + denominatore;
}
</code>```

With this method in your class we can try out the revised somma method like this:

```<code>    System.out.println(new Frazione(5, 3).somma(new Frazione(7, 2)));
</code>```

The output is:

```<code>31
--
6
</code>```

I believe it’s the same output that you got before.

Body:
Instead of printing the result from each method, return it as a new Frazione (fraction) object. Just fill the calculated numerator and denominator into the new object. For example the somma (sum) method becomes:

public Frazione somma(Frazione frazioneForadori2){
    return new Frazione((numeratore * frazioneForadori2.getDenominatore())+(denominatore * frazioneForadori2.getNumeratore()),
            denominatore * frazioneForadori2.getDenominatore());
}

The sottrazione (subtraction/difference)  method is similar, I am leaving that to you.

In order to print out the result outside the method it’s probably practical to define a toString method for the Frazione class:

@Override
public String toString() {
    return "" + numeratore + "\n--\n" + denominatore;
}

With this method in your class we can try out the revised somma method like this:

    System.out.println(new Frazione(5, 3).somma(new Frazione(7, 2)));

The output is:

31
--
6

I believe it’s the same output that you got before.


问:
Creating New Roles and Permissions to urls Dynamically in Spring
Spring security -how to add roles dynamically and depending on role there url access permission must change and when creating role we have to set url permissions dynamically<br>
ex: for admin he can access all urls
and when i am creating another role like support i can set which urls he can access dynamically  </p>

答:
This is specifically what Spring authorization handles.

You can use Spring expressions like -

```<code>@PreAuthorize("hasAuthority('PERM_ADD')")
@RequestMapping("/add")
public String add() {
  ...
}
</code>```

Here is the documentation -

https://docs.spring.io/spring-security/site/docs/current/reference/html/authorization.html

You may want to implement something like this example - https://stackoverflow.com/a/60251931/1308685

Where the user roles are mapped to more granular permissions.

Body:
Spring security -how to add roles dynamically and depending on role there url access permission must change and when creating role we have to set url permissions dynamically

ex: for admin he can access all urls
and when i am creating another role like support i can set which urls he can access dynamically

Body:
This is specifically what Spring authorization handles.

You can use Spring expressions like -

@PreAuthorize("hasAuthority('PERM_ADD')")
@RequestMapping("/add")
public String add() {
  ...
}

Here is the documentation -

https://docs.spring.io/spring-security/site/docs/current/reference/html/authorization.html

You may want to implement something like this example - https://stackoverflow.com/a/60251931/1308685

Where the user roles are mapped to more granular permissions.


问:
Cant figure out what is wrong with this spider
So im strugging to determine what im doing wrong here.. Looking to scrape this site and extract some details for each item - category - title - price - url. But cant figure out why the spider will not give me the results im after.

If i remove the parse_details function in this spider, the spider will crawl the urls i want, yet when i call parse_details to grab some data, its breaking the crawl and not getting the full scope im looking for. (newb so please be gentle!)

without my yield request

```<code># -*- coding: utf-8 -*-
from scrapy import Spider
from scrapy.http import Request

# Define spider settings
class WickesSpider(Spider):
    name = 'wickes'
    allowed_domains = ['wickes.co.uk']
    start_urls = ['https://www.wickes.co.uk/Products/Building-Materials/c/1000173']

    def parse(self, response):
        # this will call self.parse by default for all your categories
        for url in response.xpath('//ul[@class="aside-nav2__list"]/li/a/@href').extract():
            yield Request(response.urljoin(url))

    def parse_details(self, response):

        pass
</code>```

log

```<code>2020-02-16 14:52:21 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-16 14:52:21 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 113681,
 'downloader/request_count': 178,
 'downloader/request_method_count/GET': 178,
 'downloader/response_bytes': 9932059,
 'downloader/response_count': 178,
 'downloader/response_status_count/200': 178,
 'dupefilter/filtered': 212,
 'elapsed_time_seconds': 17.984344,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 16, 14, 52, 21, 844590),
 'log_count/DEBUG': 179,
 'log_count/INFO': 10,
 'memusage/max': 53600256,
 'memusage/startup': 53600256,
 'request_depth_max': 4,
 'response_received_count': 178,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/200': 1,
 'scheduler/dequeued': 177,
 'scheduler/dequeued/memory': 177,
 'scheduler/enqueued': 177,
 'scheduler/enqueued/memory': 177,
 'start_time': datetime.datetime(2020, 2, 16, 14, 52, 3, 860246)}
2020-02-16 14:52:21 [scrapy.core.engine] INFO: Spider closed (finished)
</code>```

with yield request

```<code># -*- coding: utf-8 -*-
from scrapy import Spider
from scrapy.http import Request

# Define spider settings
class WickesSpider(Spider):
    name = 'wickes'
    allowed_domains = ['wickes.co.uk']
    start_urls = ['https://www.wickes.co.uk/Products/Building-Materials/c/1000173']

    def parse(self, response):
        # this will call self.parse by default for all your categories
        for url in response.xpath('//ul[@class="aside-nav2__list"]/li/a/@href').extract():
            yield Request(response.urljoin(url),
                         callback=self.parse_details)

    def parse_details(self, response):
        items = response.xpath('.//div[@class="products-list products-list-v2"]').extract()

        for item in items:
            category = response.xpath('.//h1/text()').extract_first()
            title = response.xpath('.//*[@class="product-card__title product-card__title-v2"]/text()').extract_first()
            price = response.xpath('.//*[@class="product-card__price-value "]/text()').extract_first()
            url = response.xpath('.//*[@class="product-card__title product-card__title-v2"]/@href').extract_first()

            yield {
                'category': category,
                'title': title,
                'price': price,
                'url': url
            }
</code>```

log

```<code>2020-02-16 14:55:14 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-16 14:55:14 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 10801,
 'downloader/request_count': 19,
 'downloader/request_method_count/GET': 19,
 'downloader/response_bytes': 902364,
 'downloader/response_count': 19,
 'downloader/response_status_count/200': 19,
 'dupefilter/filtered': 17,
 'elapsed_time_seconds': 2.775066,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 16, 14, 55, 14, 607396),
 'item_scraped_count': 2,
 'log_count/DEBUG': 22,
 'log_count/INFO': 10,
 'memusage/max': 53420032,
 'memusage/startup': 53420032,
 'request_depth_max': 1,
 'response_received_count': 19,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/200': 1,
 'scheduler/dequeued': 18,
 'scheduler/dequeued/memory': 18,
 'scheduler/enqueued': 18,
 'scheduler/enqueued/memory': 18,
 'start_time': datetime.datetime(2020, 2, 16, 14, 55, 11, 832330)}
2020-02-16 14:55:14 [scrapy.core.engine] INFO: Spider closed (finished)
</code>```

答:
Alright, so i started over..  this time i tried something different and it worked (so far anyway, still need to check for defects). But at least im getting results

```<code>import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from wickes_spider.items import WickesSpiderItem
from scrapy.http import Response

class WickesSpider(CrawlSpider):
    name = "wickes"
    start_urls = [
              "https://www.wickes.co.uk/Products/Building-Materials/c/1000173",
    ]

    rules = (
        Rule(LinkExtractor(allow=('Building-Materials')),callback='parse_links',follow=True),
        )
    def parse_links(self, response):
        items = items = response.xpath('.//*[@class="content"]')
        for item in items:
            item = WickesSpiderItem()
            item['category'] = response.xpath('.//h1/text()').extract_first()
            item['title'] = response.xpath('.//*[@class="product-card__title product-card__title-v2"]/text()').extract_first()
            item['price'] = response.xpath('.//*[@class="product-card__price-value "]/text()').extract_first()
            item['url'] = response.xpath('.//*[@class="product-card__title product-card__title-v2"]/@href').extract_first()

            yield item
</code>```

Using LinkExtractor seems to of solved my issues. Thanks for all the help anyway.

Body:
So im strugging to determine what im doing wrong here.. Looking to scrape this site and extract some details for each item - category - title - price - url. But cant figure out why the spider will not give me the results im after.

If i remove the parse_details function in this spider, the spider will crawl the urls i want, yet when i call parse_details to grab some data, its breaking the crawl and not getting the full scope im looking for. (newb so please be gentle!)

without my yield request

# -*- coding: utf-8 -*-
from scrapy import Spider
from scrapy.http import Request

# Define spider settings
class WickesSpider(Spider):
    name = 'wickes'
    allowed_domains = ['wickes.co.uk']
    start_urls = ['https://www.wickes.co.uk/Products/Building-Materials/c/1000173']

    def parse(self, response):
        # this will call self.parse by default for all your categories
        for url in response.xpath('//ul[@class="aside-nav2__list"]/li/a/@href').extract():
            yield Request(response.urljoin(url))

    def parse_details(self, response):

        pass

log

2020-02-16 14:52:21 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-16 14:52:21 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 113681,
 'downloader/request_count': 178,
 'downloader/request_method_count/GET': 178,
 'downloader/response_bytes': 9932059,
 'downloader/response_count': 178,
 'downloader/response_status_count/200': 178,
 'dupefilter/filtered': 212,
 'elapsed_time_seconds': 17.984344,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 16, 14, 52, 21, 844590),
 'log_count/DEBUG': 179,
 'log_count/INFO': 10,
 'memusage/max': 53600256,
 'memusage/startup': 53600256,
 'request_depth_max': 4,
 'response_received_count': 178,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/200': 1,
 'scheduler/dequeued': 177,
 'scheduler/dequeued/memory': 177,
 'scheduler/enqueued': 177,
 'scheduler/enqueued/memory': 177,
 'start_time': datetime.datetime(2020, 2, 16, 14, 52, 3, 860246)}
2020-02-16 14:52:21 [scrapy.core.engine] INFO: Spider closed (finished)

with yield request

# -*- coding: utf-8 -*-
from scrapy import Spider
from scrapy.http import Request

# Define spider settings
class WickesSpider(Spider):
    name = 'wickes'
    allowed_domains = ['wickes.co.uk']
    start_urls = ['https://www.wickes.co.uk/Products/Building-Materials/c/1000173']

    def parse(self, response):
        # this will call self.parse by default for all your categories
        for url in response.xpath('//ul[@class="aside-nav2__list"]/li/a/@href').extract():
            yield Request(response.urljoin(url),
                         callback=self.parse_details)

    def parse_details(self, response):
        items = response.xpath('.//div[@class="products-list products-list-v2"]').extract()

        for item in items:
            category = response.xpath('.//h1/text()').extract_first()
            title = response.xpath('.//*[@class="product-card__title product-card__title-v2"]/text()').extract_first()
            price = response.xpath('.//*[@class="product-card__price-value "]/text()').extract_first()
            url = response.xpath('.//*[@class="product-card__title product-card__title-v2"]/@href').extract_first()

            yield {
                'category': category,
                'title': title,
                'price': price,
                'url': url
            }

log

2020-02-16 14:55:14 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-16 14:55:14 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 10801,
 'downloader/request_count': 19,
 'downloader/request_method_count/GET': 19,
 'downloader/response_bytes': 902364,
 'downloader/response_count': 19,
 'downloader/response_status_count/200': 19,
 'dupefilter/filtered': 17,
 'elapsed_time_seconds': 2.775066,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 16, 14, 55, 14, 607396),
 'item_scraped_count': 2,
 'log_count/DEBUG': 22,
 'log_count/INFO': 10,
 'memusage/max': 53420032,
 'memusage/startup': 53420032,
 'request_depth_max': 1,
 'response_received_count': 19,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/200': 1,
 'scheduler/dequeued': 18,
 'scheduler/dequeued/memory': 18,
 'scheduler/enqueued': 18,
 'scheduler/enqueued/memory': 18,
 'start_time': datetime.datetime(2020, 2, 16, 14, 55, 11, 832330)}
2020-02-16 14:55:14 [scrapy.core.engine] INFO: Spider closed (finished)

Body:
Alright, so i started over..  this time i tried something different and it worked (so far anyway, still need to check for defects). But at least im getting results

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from wickes_spider.items import WickesSpiderItem
from scrapy.http import Response

class WickesSpider(CrawlSpider):
    name = "wickes"
    start_urls = [
              "https://www.wickes.co.uk/Products/Building-Materials/c/1000173",
    ]

    rules = (
        Rule(LinkExtractor(allow=('Building-Materials')),callback='parse_links',follow=True),
        )
    def parse_links(self, response):
        items = items = response.xpath('.//*[@class="content"]')
        for item in items:
            item = WickesSpiderItem()
            item['category'] = response.xpath('.//h1/text()').extract_first()
            item['title'] = response.xpath('.//*[@class="product-card__title product-card__title-v2"]/text()').extract_first()
            item['price'] = response.xpath('.//*[@class="product-card__price-value "]/text()').extract_first()
            item['url'] = response.xpath('.//*[@class="product-card__title product-card__title-v2"]/@href').extract_first()

            yield item

Using LinkExtractor seems to of solved my issues. Thanks for all the help anyway.


问:
How can I use regex to find data between quotation marks?
I need to extract data which is between the single quotes.

```<code>"request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>"
</code>```

I did try:
^"request="'*' but doesn;t work

答:
Regex '(.*)' should do the work:

text = "\"request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>\""
console.log(text.match(/'(.*)'/)[1])
```

Also you can use regex testers to see what your regex will find. I use regex101.

Body:
I need to extract data which is between the single quotes.

"request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>"

I did try:
^"request="'*' but doesn;t work

Body:
Regex '(.*)' should do the work:

text = "\"request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>\""
console.log(text.match(/'(.*)'/)[1])

Also you can use regex testers to see what your regex will find. I use regex101.


问:
How do I print colored text to the terminal?
How do I output colored text to the terminal in Python?</p>

答:
Here is a simple function I use to print a text message in color without having to remember ANSI codes but rather using standard RGB tuples to define the foreground and background colors.</p>
```<code>def print_in_color(txt_msg, fore_tuple, back_tuple, ):
    # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
    # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
    rf,bf,gf = fore_tuple
    rb,gb,bb = back_tuple
    msg = '{0}' + txt_msg
    mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
    print(msg .format(mat))
    print('\33[0m') # Returns default print color to back to black

# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))
</code>```

OwnerDisplayName: rmyeid

Body:
Here is a simple function I use to print a text message in color without having to remember ANSI codes but rather using standard RGB tuples to define the foreground and background colors.

def print_in_color(txt_msg, fore_tuple, back_tuple, ):
    # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
    # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
    rf,bf,gf = fore_tuple
    rb,gb,bb = back_tuple
    msg = '{0}' + txt_msg
    mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
    print(msg .format(mat))
    print('\33[0m') # Returns default print color to back to black

# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))


问:
Division with if condition
I just start learning ruby with an online course and in my very first exercise, I can't complete the challenge. I have to create functions to sum, subtract, multiply and divide that meet the specs conditions.

For the division, I need to check if it will divide per 0 or not, give the result or a warning. My code is

```<code>def divisao(primeiro_numero, segundo_numero)
    if segundo_numero > 0
        primeiro_numero / segundo_numero
    else
        puts 'Opa! Zero como divisor'
end
</code>```

But when I run the specs, I get the following warning

```<code>0 examples, 0 failures, 1 error occurred outside of examples
</code>```

I have changed all the functions, but this one doesn't seem to work.
I added the complete functions and specs file here:https://gist.github.com/isafloriano/86c170400b2f5fc63dc5e8edd8913525

Can anyone give me a clue why this doesn't work?

答:
Here's a compact way to write your four methods.

```<code>def add(n1, n2)
  f(n1, n2, :+)
end

def subtract(n1, n2)
  f(n1, n2, :-)
end

def multiply(n1, n2)
  f(n1, n2, :*)
end

def divide(n1, n2)
  if n2.zero?
    puts "Zero-divide error"
    return nil
  end
  f(n1, n2, :/)
end
</code>```

```<code>def f(n1, n2, op)
   n1.public_send(op, n2)
end
</code>```

```<code>add(3, 7)         #=> 10
add(5, 7.2)       #=> 12.2

subtract(4, 8)    #=> -4
subtract(6.1, 3)  #=> 3.0999999999999996

multiply(2, 6)    #=> 12
multiply(1.0, 6)  #=> 6.0

divide(4, 0)      #=> nil
Zero-divide error
divide(4, 0.0)    #=> nil
Zero-divide error
divide(4, 2)      #=> 2
divide(5, 2)      #=> 2
divide(5, 2.0)    #=> 2.5
</code>```

See Object#public_send.

Title: Division with if condition

Body:
I just start learning ruby with an online course and in my very first exercise, I can't complete the challenge. I have to create functions to sum, subtract, multiply and divide that meet the specs conditions.

For the division, I need to check if it will divide per 0 or not, give the result or a warning. My code is

def divisao(primeiro_numero, segundo_numero)
    if segundo_numero > 0
        primeiro_numero / segundo_numero
    else
        puts 'Opa! Zero como divisor'
end

But when I run the specs, I get the following warning

0 examples, 0 failures, 1 error occurred outside of examples

I have changed all the functions, but this one doesn't seem to work.
I added the complete functions and specs file here:https://gist.github.com/isafloriano/86c170400b2f5fc63dc5e8edd8913525

Can anyone give me a clue why this doesn't work?

Body:
Here's a compact way to write your four methods.

def add(n1, n2)
  f(n1, n2, :+)
end

def subtract(n1, n2)
  f(n1, n2, :-)
end

def multiply(n1, n2)
  f(n1, n2, :*)
end

def divide(n1, n2)
  if n2.zero?
    puts "Zero-divide error"
    return nil
  end
  f(n1, n2, :/)
end

def f(n1, n2, op)
   n1.public_send(op, n2)
end

add(3, 7)         #=> 10
add(5, 7.2)       #=> 12.2

subtract(4, 8)    #=> -4
subtract(6.1, 3)  #=> 3.0999999999999996

multiply(2, 6)    #=> 12
multiply(1.0, 6)  #=> 6.0

divide(4, 0)      #=> nil
Zero-divide error
divide(4, 0.0)    #=> nil
Zero-divide error
divide(4, 2)      #=> 2
divide(5, 2)      #=> 2
divide(5, 2.0)    #=> 2.5

See Object#public_send.


问:
How to abbreviate "number of <items>" in source code?
I'm new to learning Java and I'm bad at English but I try my best to write good, understandable source code.

I want to make variables to save the "number of cars" or "number of items". How do I abbreviate "number of ..." without using symbols like # that don't work in a source code?

Thanks

答:
I try my best to write good, understandable source code

Then my best advice would be not to abbreviate variable names.

Just go with numberOfCars.

Why?
I know you've probably seen a lot of programs where people use one-letter variables or stuff like numCars.

Abbreviating your variables make your code less clear for others (including you in 6 months).

We all have great text editors with auto-completion on variables, use that.


问:
sencha touch list-component
I have a listpanel that seems to work correctly, but when the details card is shown I get the word 'undefined' instead of my template.

This is part of the code:

```<code>Ext.regModel('Complementarias', {
fields: ['MiniAct', 'Actividad', 'Fecha', 'Mes']
});

var store = new Ext.data.JsonStore({
model  : 'Complementarias',
sorters: 'MiniAct',
getGroupString : function(record) {
    return record.get('MiniAct')[0];
},
data: [
    {MiniAct: '1', Actividad: '2', Mes: '3', Fecha: '4' }
]
});

baApp.detailPanel = new Ext.Panel({
        id: 'detailpanel',
        itemTpl: 'testa',
        html: '',
        dockedItems: [
            {
                xtype: 'toolbar',
                title: "Extensión",
                ui: "light",
                items: [{
                    text: 'atrás',
                    ui: 'back',
                    handler: function() {
                        Extension.setActiveItem('indexlist', {type:'slide',     direction:'right'});
                    }
                }]
            }
        ]
    });

baApp.listPanel = new Ext.List({
id: 'indexlist',
itemTpl : '<div id="extension"><h1>{MiniAct}</h2><br><h2>{Fecha}</h2></div>',
grouped : true,
store: store,
onItemDisclosure: true,
listeners:{
            itemtap: function(view, index, item, e){
            baApp.detailPanel.update(view.data);
            Extension.setActiveItem('detailpanel', {type:'slide', direction:'left'});
        }
    }
});

Extension = new Ext.Panel({
layout: 'card',
iconCls: 'chat3',
title:"Extensión",
defaults: {
    scroll: 'vertical'
},
items: [baApp.listPanel, baApp.detailPanel]
});

baApp.views.Viewport = Ext.extend(Ext.TabPanel, {
fullscreen: true,
style: "background-color: white;",
tabBar: {
    dock: 'bottom',
    sortable: true,
    layout: {
    pack: 'center'
    }
},
items: [
{xtype: 'inicio'},
{xtype: 'planes'},
Extension,
{xtype: 'plano'},
{xtype: 'directorio'}
]

});
</code>```

Does anyone have an idea where the undefined comes from?

Thanks

答:
To my knowledge Ext.List - what you are calling 'view' in your itemtap listener - does not have a 'data' property. You may be thinking of the record, which you can get using the index being passed from the same event:</p>

```<code>listeners: {
    itemtap: function( view, index, item, e ) {
        var rec = view.getStore().getAt(index);
        baApp.detailPanel.update(rec.data);
        Extension.setActiveItem('detailpanel', {type:'slide', direction:'left'});
    }
}
</code>```

Title: sencha touch list-component

Body:
I have a listpanel that seems to work correctly, but when the details card is shown I get the word 'undefined' instead of my template.

This is part of the code:

Ext.regModel('Complementarias', {
fields: ['MiniAct', 'Actividad', 'Fecha', 'Mes']
});

var store = new Ext.data.JsonStore({
model  : 'Complementarias',
sorters: 'MiniAct',
getGroupString : function(record) {
    return record.get('MiniAct')[0];
},
data: [
    {MiniAct: '1', Actividad: '2', Mes: '3', Fecha: '4' }
]
});

baApp.detailPanel = new Ext.Panel({
        id: 'detailpanel',
        itemTpl: 'testa',
        html: '',
        dockedItems: [
            {
                xtype: 'toolbar',
                title: "Extensión",
                ui: "light",
                items: [{
                    text: 'atrás',
                    ui: 'back',
                    handler: function() {
                        Extension.setActiveItem('indexlist', {type:'slide',     direction:'right'});
                    }
                }]
            }
        ]
    });

baApp.listPanel = new Ext.List({
id: 'indexlist',
itemTpl : '

{MiniAct}

{Fecha}

',
grouped : true,
store: store,
onItemDisclosure: true,
listeners:{
            itemtap: function(view, index, item, e){
            baApp.detailPanel.update(view.data);
            Extension.setActiveItem('detailpanel', {type:'slide', direction:'left'});
        }
    }
});

Extension = new Ext.Panel({
layout: 'card',
iconCls: 'chat3',
title:"Extensión",
defaults: {
    scroll: 'vertical'
},
items: [baApp.listPanel, baApp.detailPanel]
});

baApp.views.Viewport = Ext.extend(Ext.TabPanel, {
fullscreen: true,
style: "background-color: white;",
tabBar: {
    dock: 'bottom',
    sortable: true,
    layout: {
    pack: 'center'
    }
},
items: [
{xtype: 'inicio'},
{xtype: 'planes'},
Extension,
{xtype: 'plano'},
{xtype: 'directorio'}
]

});

Does anyone have an idea where the undefined comes from?

Thanks

Body:
To my knowledge Ext.List - what you are calling 'view' in your itemtap listener - does not have a 'data' property. You may be thinking of the record, which you can get using the index being passed from the same event:

listeners: {
    itemtap: function( view, index, item, e ) {
        var rec = view.getStore().getAt(index);
        baApp.detailPanel.update(rec.data);
        Extension.setActiveItem('detailpanel', {type:'slide', direction:'left'});
    }
}


问:
python tuples: unpacking into a list using *args
Hello and thanks for your time;

I am using *args to take various arguments, which creates a tuple. How do I 'unpack' a tuple into a list? The following code appends the list with a tuple.

```<code>grades = []

def add_grades(*args):
    grades.append(args):
    return grades

print(add_grades(99,88,77))
</code>```

I can do this using a for loop and iterating through the tuple, but looking to see if I can unpack directly.

答:
To convert the tuple to list you can return *args as list and extend the existing list

```<code>grades = []

def add_grades(*args):
    return [*args]

grades.extend(add_grades(99,88,77))
</code>```

Note that you can extend the list with tuple as well

```<code>def add_grades(*args):
    return args

grades.extend(add_grades(99,88,77))
</code>```

If you don't do anything else in add_grades you can also do it without any function

```<code>grades.extend([99,88,77])
</code>```

Body:
Hello and thanks for your time;

I am using *args to take various arguments, which creates a tuple. How do I 'unpack' a tuple into a list? The following code appends the list with a tuple.

grades = []

def add_grades(*args):
    grades.append(args):
    return grades

print(add_grades(99,88,77))

I can do this using a for loop and iterating through the tuple, but looking to see if I can unpack directly.

Body:
To convert the tuple to list you can return *args as list and extend the existing list

grades = []

def add_grades(*args):
    return [*args]

grades.extend(add_grades(99,88,77))

Note that you can extend the list with tuple as well

def add_grades(*args):
    return args

grades.extend(add_grades(99,88,77))

If you don't do anything else in add_grades you can also do it without any function

grades.extend([99,88,77])