问:
QuerydslPredicate with spring-boot-starter-jpa
I have a problem with autogenerating Q classess in com.querydsl. I know that there are possible mistakes with compatibility between com.query.dsl and spring-boot-jpa but i tried lots of version without any positive result. Here is my pom.xml

```<code>    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4.1212.jre7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.4</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
        <version>1.4.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>21.0</version>
    </dependency>
    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.9.3</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-jpa</artifactId>
        <version>4.0.7</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>
            <executions>
                <execution>
                    <id>process-common-model</id>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>target/generated-sources/apt</outputDirectory>
                        <processors>
                            <processor>com.query.apt.jpa.JPAAnnotationProcessor</processor>
                        </processors>
                    </configuration>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>com.querydsl</groupId>
                    <artifactId>querydsl-apt</artifactId>
                    <version>4.0.7</version>
                </dependency>
            </dependencies>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

The error

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.jpa.repository.support.QueryDslJpaRepository]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Did not find a query class com.coig.prek.webservice.modules.quiz.entiry.QQuiz for domain class com.coig.prek.webservice.modules.quiz.entiry.Quiz!
      at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.data.repository.core.support.RepositoryFactorySupport.getTargetRepositoryViaReflection(RepositoryFactorySupport.java:365) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:101) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:81) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      ... 47 common frames omitted
  Caused by: java.lang.IllegalArgumentException: Did not find a query class com.coig.prek.webservice.modules.quiz.entiry.QQuiz for domain class com.coig.prek.webservice.modules.quiz.entiry.Quiz!
      at org.springframework.data.querydsl.SimpleEntityPathResolver.createPath(SimpleEntityPathResolver.java:63) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.(QueryDslJpaRepository.java:84) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.(QueryDslJpaRepository.java:68) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_111]
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_111]
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_111]
      at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_111]
      at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      ... 56 common frames omitted
  Caused by: java.lang.ClassNotFoundException: com.coig.prek.webservice.modules.quiz.entiry.QQuiz
      at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_111]
      at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_111]
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_111]
      at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_111]
      at org.springframework.util.ClassUtils.forName(ClassUtils.java:250) ~[spring-core-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.data.querydsl.SimpleEntityPathResolver.createPath(SimpleEntityPathResolver.java:53) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      ... 63 common frames omitted

Repository:

```<code>@Repository
public interface QuizRepository extends PagingAndSortingRepository<Quiz, Long>, QueryDslPredicateExecutor<Quiz> {
}
</code>```

And Entity:

```<code>@javax.persistence.Entity
@Table(name = "QUIZ", uniqueConstraints = {
        @UniqueConstraint(columnNames = "NAME")
})
@ToString
public class Quiz extends Entity{

    @Column(name = "NAME")
    private @Setter @Getter String name;
    @Column(name = "TYPE")
    private @Setter @Getter Integer type;
    @Column(name = "TIME")
    private @Setter @Getter Long time;
    @JsonProperty(value = "branch")
    @Column(name = "BRANCH")
    private @Setter @Getter Integer branch;

    @OneToMany
    private @Setter @Getter Set<Question> questions;

    public Quiz() {}

}
</code>```

Can you tell me if I missing something, or what I am doing wrong?
Thanks for any help.

答:
Few days before, I also faced this problem!! But it was a bit different to your problem it was something like:

Failed to introspect Class org.springframework.data.jpa.repository.support.QuerydslJpaRepository] from ClassLoader [sun.misc.Launcher$AppClassLoader@764c12b6]; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.data.jpa.repository.support.QuerydslJpaRepository] from ClassLoader [sun.misc.Launcher$AppClassLoader@764c12b6]

But I believe this is worth trying:

This is was the scenario: I cloned a project which has querydsl implementation and was using STS IDE.

On downloading all the dependencies I ran the project and was successful but upon accessing any endpoint the above error started to prompt up!!

For which this is what I did:

I went into the .m2 folder and deleted the querydsl-jpa folder present inside com/querydsl directory and then manually ran mvn clean [ install for war | package for jar ] which downloaded all the dependencies and linked them properly!!

Upon re-running spring project everything was working fine.

Causes of this issue: At times while downloading the dependencies from maven or any other repository the jar file could get corrupted which is undetectable before execution so it is beneficial to delete that jar in .m2 folder and running manually as at times IDE could also corrupt downloaded jars.

Hope this resolves your issue!!

Body:
I have a problem with autogenerating Q classess in com.querydsl. I know that there are possible mistakes with compatibility between com.query.dsl and spring-boot-jpa but i tried lots of version without any positive result. Here is my pom.xml

    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4.1212.jre7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.4</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
        <version>1.4.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>21.0</version>
    </dependency>
    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.9.3</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-jpa</artifactId>
        <version>4.0.7</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>
            <executions>
                <execution>
                    <id>process-common-model</id>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>target/generated-sources/apt</outputDirectory>
                        <processors>
                            <processor>com.query.apt.jpa.JPAAnnotationProcessor</processor>
                        </processors>
                    </configuration>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>com.querydsl</groupId>
                    <artifactId>querydsl-apt</artifactId>
                    <version>4.0.7</version>
                </dependency>
            </dependencies>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

The error

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.jpa.repository.support.QueryDslJpaRepository]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Did not find a query class com.coig.prek.webservice.modules.quiz.entiry.QQuiz for domain class com.coig.prek.webservice.modules.quiz.entiry.Quiz!
      at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.data.repository.core.support.RepositoryFactorySupport.getTargetRepositoryViaReflection(RepositoryFactorySupport.java:365) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:101) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:81) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      ... 47 common frames omitted
  Caused by: java.lang.IllegalArgumentException: Did not find a query class com.coig.prek.webservice.modules.quiz.entiry.QQuiz for domain class com.coig.prek.webservice.modules.quiz.entiry.Quiz!
      at org.springframework.data.querydsl.SimpleEntityPathResolver.createPath(SimpleEntityPathResolver.java:63) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.(QueryDslJpaRepository.java:84) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.(QueryDslJpaRepository.java:68) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_111]
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_111]
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_111]
      at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_111]
      at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      ... 56 common frames omitted
  Caused by: java.lang.ClassNotFoundException: com.coig.prek.webservice.modules.quiz.entiry.QQuiz
      at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_111]
      at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_111]
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_111]
      at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_111]
      at org.springframework.util.ClassUtils.forName(ClassUtils.java:250) ~[spring-core-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.data.querydsl.SimpleEntityPathResolver.createPath(SimpleEntityPathResolver.java:53) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
      ... 63 common frames omitted

Repository:

@Repository
public interface QuizRepository extends PagingAndSortingRepository<Quiz, Long>, QueryDslPredicateExecutor<Quiz> {
}

And Entity:

@javax.persistence.Entity
@Table(name = "QUIZ", uniqueConstraints = {
        @UniqueConstraint(columnNames = "NAME")
})
@ToString
public class Quiz extends Entity{

    @Column(name = "NAME")
    private @Setter @Getter String name;
    @Column(name = "TYPE")
    private @Setter @Getter Integer type;
    @Column(name = "TIME")
    private @Setter @Getter Long time;
    @JsonProperty(value = "branch")
    @Column(name = "BRANCH")
    private @Setter @Getter Integer branch;

    @OneToMany
    private @Setter @Getter Set<Question> questions;

    public Quiz() {}

}

Can you tell me if I missing something, or what I am doing wrong?
Thanks for any help.


来源: stackexchange

问:
How do I get variables from Android Manifest in Flutter?
I want to use the API key for the Google Maps API in my package, assuming it's present in the AndroidManifest file (and the iOS equivalent). I see that if you use the google_maps_flutter package, you never have to pass the API key to the GoogleMap widget. Currently, I'm passing the API Key as an attribute to every widget I use, like this:

// The class receives the API key through a property called apiKey
SearchPlaceWidget(apiKey: YOUR_API_KEY);

And I'd like something like this:

// The class will get the API key directly from the AndroidManifest file
SeachPlaceWidget()

答:
You can't get variables from AndroidManifest.xml file. Here is what you can do, create a new file in your lib folder say strings.dart, in that file.

Write this in your newly created lib/strings.dart

```<code>final String apiKey = "your_api_key";
</code>```

And wherever you want to use the API key, simply import lib/strings.dart file, and use it like:

```<code>SearchPlaceWidget(apiKey: apiKey);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can't get variables from AndroidManifest.xml file. Here is what you can do, create a new file in your lib folder say strings.dart, in that file.

Write this in your newly created lib/strings.dart

final String apiKey = "your_api_key";

And wherever you want to use the API key, simply import lib/strings.dart file, and use it like:

SearchPlaceWidget(apiKey: apiKey);


问:
onListItemClick, what statement do I need to get the value?
i can add to a db and list as a listview.
When I click a list item using onListItemClick, what statement do I
need to get the value?

Thanks in advance.

```<code>public class Main extends ListActivity {
private static String[] FROM = { _ID, DESCRIPTION, UN };
private static String ORDER_BY = DESCRIPTION + " ASC";
private static int[] TO = {R.id.itemrowid, R.id.itemdescription, R.id.itemun };
private EventsData events;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    events = new EventsData(this);
    try {
        Cursor cursor = getEvents();
        showEvents(cursor);
     } finally {
        events.close();
     }

**public void onListItemClick(ListView parent, View v, int position, long id) {
    // What statement to put here to get the value of _ID,DESCRIPTION, UN
    // selected**?
}

private Cursor getEvents() {
    // Perform a managed query. The Activity will handle closing
    // and re-querying the cursor when needed.
    SQLiteDatabase db = events.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
            null, ORDER_BY);
    startManagingCursor(cursor);
    return cursor;
}

private void showEvents(Cursor cursor) {
    // Set up data binding
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.item, cursor, FROM, TO);
    setListAdapter(adapter);
}
</code>```

答:
Adding to sergey answer you can also directly see what View was clicked and use findViewById() to find the components, therefore, the values you want.

This is just an alternative being the method Sergey much less 'patchy'

ContentLicense: CC BY-SA 3.0

Body:
i can add to a db and list as a listview.
When I click a list item using onListItemClick, what statement do I
need to get the value?

Thanks in advance.

public class Main extends ListActivity {
private static String[] FROM = { _ID, DESCRIPTION, UN };
private static String ORDER_BY = DESCRIPTION + " ASC";
private static int[] TO = {R.id.itemrowid, R.id.itemdescription, R.id.itemun };
private EventsData events;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    events = new EventsData(this);
    try {
        Cursor cursor = getEvents();
        showEvents(cursor);
     } finally {
        events.close();
     }

**public void onListItemClick(ListView parent, View v, int position, long id) {
    // What statement to put here to get the value of _ID,DESCRIPTION, UN
    // selected**?
}

private Cursor getEvents() {
    // Perform a managed query. The Activity will handle closing
    // and re-querying the cursor when needed.
    SQLiteDatabase db = events.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
            null, ORDER_BY);
    startManagingCursor(cursor);
    return cursor;
}

private void showEvents(Cursor cursor) {
    // Set up data binding
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.item, cursor, FROM, TO);
    setListAdapter(adapter);
}


问:
Can I alter the constraints of one table by using the constraints of another table?
I had to drop a table and remake it using an archive. In the process, I lost the table's constraints--things like the primary key--triggers, indices, and more. I have, however, the same table on a different DB, which has all the appropriate constraints.

I have tried adding the constraints, triggers, and indices manually, but there are just too many.

I was wondering if I could do something like:

```<code>alter table t73
  modify col_n....col_n+1
  using (select constraints from t73@otherdb)
</code>```

答:
No, that won't work.

What you could do is to use some GUI (like TOAD or SQL Developer), find table t73, have a look at its Script which contains all commands (CREATE TABLE, CREATE INDEX, CREATE CONSTRAINT, ...) and copy/paste the ones you need and execute them in your current database.

That would be quick.

If you want to do it right (you know, pretending you know what you're doing, just like I do), then see DBMS_METADATA.GET_DDL and extract those commands from the database.

The final result should be the same.

Body:
I had to drop a table and remake it using an archive. In the process, I lost the table's constraints--things like the primary key--triggers, indices, and more. I have, however, the same table on a different DB, which has all the appropriate constraints.

I have tried adding the constraints, triggers, and indices manually, but there are just too many.

I was wondering if I could do something like:

alter table t73
  modify col_n....col_n+1
  using (select constraints from t73@otherdb)


问:
How do I pass static_cast<T> as a function?
I have a type A that's designed to be implicitly casted to type B.  Here's an example case I'd like to use it in:

```<code>// Current implementation:
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
               [](const A& a) -> B { return a; });  // Thanks, Kerrek SB.

// Ideal implementation - Won't compile, expected '(' after 'static_cast'.
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
               static_cast<B>);
</code>```

What can I do to make the latter option compile?

答:
Build a functor enclosing static_cast:

```<code>template <typename T>
struct StaticCast
{
    template <typename U>
    T operator()(const U& rhs)
    {
        return static_cast<T>(rhs);
    }
};
</code>```

With this, you can call std::transform:

```<code>std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b), StaticCast<b>());
</code>```

It can be used in the case the output vector is already defined in place of the lambda shown in comments. If not, prefer the constructor mentioned in another answer**.

This functor version is compliant with C++98 if needed -- even if OP is tagged C++11, it may be worthy to note this point.

** Note that with this particular constructor, a warning C4244 is raised with VS compiler (tested with VS2017).

Body:
I have a type A that's designed to be implicitly casted to type B.  Here's an example case I'd like to use it in:

// Current implementation:
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
               [](const A& a) -> B { return a; });  // Thanks, Kerrek SB.

// Ideal implementation - Won't compile, expected '(' after 'static_cast'.
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
               static_cast);

What can I do to make the latter option compile?

Body:
Build a functor enclosing static_cast:

template <typename T>
struct StaticCast
{
    template <typename U>
    T operator()(const U& rhs)
    {
        return static_cast<T>(rhs);
    }
};

With this, you can call std::transform:

std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b), StaticCast<b>());

It can be used in the case the output vector is already defined in place of the lambda shown in comments. If not, prefer the constructor mentioned in another answer**.

This functor version is compliant with C++98 if needed -- even if OP is tagged C++11, it may be worthy to note this point.

** Note that with this particular constructor, a warning C4244 is raised with VS compiler (tested with VS2017).


问:
How can I draw dotted line using chartjs?
I would like to draw dotted line using chartjs. I did not see any options in creating dotted lines. I feel we need to extend the chartjs to support this. Can some one help me in this?</p>

答:
For dotted lines use borderDash and borderCapStyle. The following example creates a dotted line (3px diameter):

```<code>data: {
  datasets: [
    {
        data           : data,
        borderWidth    : 3, // set diameter of dots here
        borderColor    : '#ccc',
        fill           : false,
        pointRadius    : 0,
        borderDash     : [0,6], // set 'length' of dash/dots to zero and
                                // space between dots (center to center)
                                // recommendation: 2x the borderWidth
        borderCapStyle : 'round' // this is where the magic happens
    }
  ]
}
</code>```

Output

Output (better contrast for demonstration)

Body:
For dotted lines use borderDash and borderCapStyle. The following example creates a dotted line (3px diameter):

data: {
  datasets: [
    {
        data           : data,
        borderWidth    : 3, // set diameter of dots here
        borderColor    : '#ccc',
        fill           : false,
        pointRadius    : 0,
        borderDash     : [0,6], // set 'length' of dash/dots to zero and
                                // space between dots (center to center)
                                // recommendation: 2x the borderWidth
        borderCapStyle : 'round' // this is where the magic happens
    }
  ]
}

Output

Output (better contrast for demonstration)


问:
One Hot Encoding a single column
I am trying to use one hot encoder on the target column('Species') in the Iris dataset.

But I am getting the following errors:

ValueError: Expected 2D array, got 1D array instead:

Reshape your data either using array.reshape(-1, 1) if your data has a
  single feature or array.reshape(1, -1) if it contains a single sample.

```<code>Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm    Species
0   1   5.1 3.5 1.4         0.2     Iris-setosa
1   2   4.9 3.0 1.4         0.2     Iris-setosa
2   3   4.7 3.2 1.3         0.2     Iris-setosa
3   4   4.6 3.1 1.5         0.2     Iris-setosa
4   5   5.0 3.6 1.4         0.2     Iris-setosa
</code>```

I did google the issue and i found that most of the scikit learn estimators need a 2D array rather than a 1D array.

At the same time, I also found that we can try passing the dataframe with its index to encode single columns, but it didn't work

```<code>onehotencoder = OneHotEncoder(categorical_features=[df.columns.tolist().index('pattern_id')
X = dataset.iloc[:,1:5].values
y = dataset.iloc[:, 5].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder= LabelEncoder()
y = labelencoder.fit_transform(y)

onehotencoder = OneHotEncoder(categorical_features=[0])
y = onehotencoder.fit_transform(y)
</code>```

I am trying to encode a single categorical column and split into multiple columns (the way the encoding usually works)

答:
For your case, since it looks like you are using the kaggle dataset, I would just use

```<code>import pandas as pd
pd.get_dummies(df.Species).head()

Out[158]:
   Iris-setosa  Iris-versicolor  Iris-virginica
0            1                0               0
1            1                0               0
2            1                0               0
3            1                0               0
4            1                0               0
</code>```

Note that the default here encodes all the classes (3 species), where it is common to use just two and compare differences in the means to the baseline group, (eg. the default in R or typically when doing regression/ANOVA which can be accomplished using the drop_first argument).

Title: One Hot Encoding a single column

Body:
I am trying to use one hot encoder on the target column('Species') in the Iris dataset.

But I am getting the following errors:

ValueError: Expected 2D array, got 1D array instead:

Reshape your data either using array.reshape(-1, 1) if your data has a
  single feature or array.reshape(1, -1) if it contains a single sample.

Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm    Species
0   1   5.1 3.5 1.4         0.2     Iris-setosa
1   2   4.9 3.0 1.4         0.2     Iris-setosa
2   3   4.7 3.2 1.3         0.2     Iris-setosa
3   4   4.6 3.1 1.5         0.2     Iris-setosa
4   5   5.0 3.6 1.4         0.2     Iris-setosa

I did google the issue and i found that most of the scikit learn estimators need a 2D array rather than a 1D array.

At the same time, I also found that we can try passing the dataframe with its index to encode single columns, but it didn't work

onehotencoder = OneHotEncoder(categorical_features=[df.columns.tolist().index('pattern_id')
X = dataset.iloc[:,1:5].values
y = dataset.iloc[:, 5].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder= LabelEncoder()
y = labelencoder.fit_transform(y)

onehotencoder = OneHotEncoder(categorical_features=[0])
y = onehotencoder.fit_transform(y)

I am trying to encode a single categorical column and split into multiple columns (the way the encoding usually works)

Body:
For your case, since it looks like you are using the kaggle dataset, I would just use

import pandas as pd
pd.get_dummies(df.Species).head()

Out[158]:
   Iris-setosa  Iris-versicolor  Iris-virginica
0            1                0               0
1            1                0               0
2            1                0               0
3            1                0               0
4            1                0               0

Note that the default here encodes all the classes (3 species), where it is common to use just two and compare differences in the means to the baseline group, (eg. the default in R or typically when doing regression/ANOVA which can be accomplished using the drop_first argument).


问:
Conditionally insert a line in JSON array like file with awk
I want to push items with awk to a myArray.json file like so

```<code>[
 item1,
 item2
]
</code>```

To add item1 I tried

```<code>echo -e "[\n]" > myArray.json # Create an empty JSON array with "\n"
awk -v var="item1" '/\]/ {print var} 1' myArray.json >> myArray-tmp.json
mv myArray-tmp.json myArray.json
</code>```

If I now comment out echo -e "[\n]" > myArray.json line (or conditionally skip it), set var="item2" and run the script, item2 is added to the array. I want to add a comma after first line, but not second.

答:
also, one easy alternative - a walk-path based unix utility jtc to manipulate json.

In jtc there's an option to apply changes right into the source file - -f (without it, the result will only be printed to the console):

```<code>bash $ jtc myArray.json
[
   "item1"
]
bash $
bash $ jtc -f -i'"item2"' myArray.json
bash $
bash $ jtc myArray.json
[
   "item1",
   "item2"
]
bash $
</code>```

Note: inserted element must be a valid JSON - hence double quotes (”item2” - that makes a valid JSON string) and to preserve them (escape shell interpolation) - there are outer single quotes around the argument

PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations

Body:
I want to push items with awk to a myArray.json file like so

[
 item1,
 item2
]

To add item1 I tried

echo -e "[\n]" > myArray.json # Create an empty JSON array with "\n"
awk -v var="item1" '/\]/ {print var} 1' myArray.json >> myArray-tmp.json
mv myArray-tmp.json myArray.json

If I now comment out echo -e "[\n]" > myArray.json line (or conditionally skip it), set var="item2" and run the script, item2 is added to the array. I want to add a comma after first line, but not second.

Body:
also, one easy alternative - a walk-path based unix utility jtc to manipulate json.

In jtc there's an option to apply changes right into the source file - -f (without it, the result will only be printed to the console):

bash $ jtc myArray.json
[
   "item1"
]
bash $
bash $ jtc -f -i'"item2"' myArray.json
bash $
bash $ jtc myArray.json
[
   "item1",
   "item2"
]
bash $

Note: inserted element must be a valid JSON - hence double quotes (”item2” - that makes a valid JSON string) and to preserve them (escape shell interpolation) - there are outer single quotes around the argument

PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations


问:
C# Volley how to get OnResponse?
Please let me know where do I need to write "OnResponse" in C# using Volley.    </p>

<p>I converted the code from Android studio to c# which uses Volley library. Then I opened the code in Xamarin to send request and receive the response.I added the Volley Nuget package (Xamarin.Bindings.Volley).
Following is the code snippet of converted C#. However, The code do not recognize "OnResponse" function. I need an example of Successful "OnResponse" implementation in c# using Volley. </p>

```<code>    public void GetAndPostReqquest(string url, int requestedCode, JSONObject @object, IServerResponse jsonResponse)
    {
        int method = Request.equestMethodConsts.Get;
        switch (requestedCode)
        {
            case POST:
                method = Request.equestMethodConsts.Post;
                break;
            case PUT:
                method = Request.equestMethodConsts.Put;
                break;

        }

        if (!IsInternetAvailable())
        {
            jsonResponse.RequestFinishedWithError(MContext.GetString(App8.Droid.Resource.String.internet_connection_is_not_available));
            return;
        }

        jsonResponse.RequestStarted();

        JsonObjectRequest request = new JsonObjectRequest(method, url, @object, Llistener, EerrorListener) {

        private void OnResponse(JSONObject response)
        {
            IDictionary<string, string> headers = new Dictionary<string, string>();
            string credentials = UNAME + ":" + PWD;
            string auth = "Basic " + Convert.ToBase64String(credentials.ToCharArray(0, credentials.Length));
            headers["Authorization"] = auth;
            headers["Content-Type"] = "application/json; charset=utf-8";
            //return headers;
        }

    }
</code>```

答:
To use Volley on your code you will need to do a couple of small changes.

First, I would suggest you change the Nugget package you are using from Xamarin.Bindings.Volley to the Xamarin.Android.Volley. The one you are currently using is outdated (2017) and the one I am suggesting not only is up-to-date but also is maintained by Xamarin, so chances are that it will be always updated.

In the Activity where your code is being executed, you will need to make it implement two interfaces that are part of Volley namespace, these are: Response.IListener and Response.IErrorListener

It should look like this:

```<code>public class MainActivity : Activity, Response.IListener, Response.IErrorListener
</code>```

This will require you to complete the implementation of these interfaces by adding two methods: public void OnErrorResponse(VolleyError p0) and public void OnResponse(Object p0) to the Activity class

In the OnResponse method is where you are gonna add your logic.

You will need to cast the Object received in the OnResponse to a JSONObject object before using it.

The Activity definition should later look like this:

```<code>public class MainActivity : Activity, Response.IListener, Response.IErrorListener
{
    public void OnErrorResponse(VolleyError p0)
    {
    }

    public void OnResponse(Object p0)
    {
        if(p0 is JSONObject response)
        {
            // Do your logic here with response
        }
    }

   /......

}
</code>```

Your request will be updated like this:

```<code>JsonObjectRequest request = new JsonObjectRequest(method, url, @object, this, this);
</code>```

Hope this helps.-

Title: C# Volley how to get OnResponse?

Body:
Please let me know where do I need to write "OnResponse" in C# using Volley.

I converted the code from Android studio to c# which uses Volley library. Then I opened the code in Xamarin to send request and receive the response.I added the Volley Nuget package (Xamarin.Bindings.Volley).
Following is the code snippet of converted C#. However, The code do not recognize "OnResponse" function. I need an example of Successful "OnResponse" implementation in c# using Volley.

    public void GetAndPostReqquest(string url, int requestedCode, JSONObject @object, IServerResponse jsonResponse)
    {
        int method = Request.equestMethodConsts.Get;
        switch (requestedCode)
        {
            case POST:
                method = Request.equestMethodConsts.Post;
                break;
            case PUT:
                method = Request.equestMethodConsts.Put;
                break;

        }

        if (!IsInternetAvailable())
        {
            jsonResponse.RequestFinishedWithError(MContext.GetString(App8.Droid.Resource.String.internet_connection_is_not_available));
            return;
        }

        jsonResponse.RequestStarted();

        JsonObjectRequest request = new JsonObjectRequest(method, url, @object, Llistener, EerrorListener) {

        private void OnResponse(JSONObject response)
        {
            IDictionary<string, string> headers = new Dictionary<string, string>();
            string credentials = UNAME + ":" + PWD;
            string auth = "Basic " + Convert.ToBase64String(credentials.ToCharArray(0, credentials.Length));
            headers["Authorization"] = auth;
            headers["Content-Type"] = "application/json; charset=utf-8";
            //return headers;
        }

    }

Body:
To use Volley on your code you will need to do a couple of small changes.

First, I would suggest you change the Nugget package you are using from Xamarin.Bindings.Volley to the Xamarin.Android.Volley. The one you are currently using is outdated (2017) and the one I am suggesting not only is up-to-date but also is maintained by Xamarin, so chances are that it will be always updated.

In the Activity where your code is being executed, you will need to make it implement two interfaces that are part of Volley namespace, these are: Response.IListener and Response.IErrorListener

It should look like this:

public class MainActivity : Activity, Response.IListener, Response.IErrorListener

This will require you to complete the implementation of these interfaces by adding two methods: public void OnErrorResponse(VolleyError p0) and public void OnResponse(Object p0) to the Activity class

In the OnResponse method is where you are gonna add your logic.

You will need to cast the Object received in the OnResponse to a JSONObject object before using it.

The Activity definition should later look like this:

public class MainActivity : Activity, Response.IListener, Response.IErrorListener
{
    public void OnErrorResponse(VolleyError p0)
    {
    }

    public void OnResponse(Object p0)
    {
        if(p0 is JSONObject response)
        {
            // Do your logic here with response
        }
    }

   /......

}

Your request will be updated like this:

JsonObjectRequest request = new JsonObjectRequest(method, url, @object, this, this);

Hope this helps.-


问:
Android Studio : Error running 'app' Default activity not found
I'm new to android studio and doing my first project.  I made changes to my layout xml file after which getting the above mentioned error. i didn't add any new activity and also the android manifest.xml file has default activity mentioned.

I have tried to invalidate the cache and restart the Android studio but still the error exists and I'm not able to execute my program.

答:
In this scenario You have missed by telling the manifest about Which activity to run, Like I have Removed these Lines From Menifest

```<code>        <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</code>```

This error will accour, Just add the above Lines in menifest and Your error will Gone.

Like I have tested By removing the above line for Yourself from Menifest I face the Error just Like You..

Here the main Activity will be the One You want to start First After Installation Of Apk

Body:
In this scenario You have missed by telling the manifest about Which activity to run, Like I have Removed these Lines From Menifest

        <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

This error will accour, Just add the above Lines in menifest and Your error will Gone.

Like I have tested By removing the above line for Yourself from Menifest I face the Error just Like You..

Here the main Activity will be the One You want to start First After Installation Of Apk


问:
How to replace has_key in python3?
I try to install Auto-SelfControl and got stuck when executing this command:

```<code>sudo /usr/bin/python auto-selfcontrol.py
</code>```

It shows the error:

AttributeError: 'dict' object has no attribute 'has_key'

I'm searching for solutions and end up with replacing has_key for in operator but as I only know the basics of python, the code is quite complex for me.

There're 3 places where has_key have been used, can you help me change it so I can run with python3?

1.

```<code>def check_if_running(username):
""" checks if self-control is already running. """
defaults = get_selfcontrol_settings(username)
return defaults.has_key("BlockStartedDate") and not NSDate.distantFuture().isEqualToDate_(defaults["BlockStartedDate"])
</code>```

2-4.

```<code>def check_config(config):
""" checks whether the config file is correct """
if not config.has_key("username"):
    exit_with_error("No username specified in config.")
if config["username"] not in get_osx_usernames():
    exit_with_error(
            "Username '{username}' unknown.\nPlease use your OSX username instead.\n" \
            "If you have trouble finding it, just enter the command 'whoami'\n" \
            "in your terminal.".format(
                    username=config["username"]))
if not config.has_key("selfcontrol-path"):
    exit_with_error("The setting 'selfcontrol-path' is required and must point to the location of SelfControl.")
if not os.path.exists(config["selfcontrol-path"]):
    exit_with_error(
            "The setting 'selfcontrol-path' does not point to the correct location of SelfControl. " \
            "Please make sure to use an absolute path and include the '.app' extension, " \
            "e.g. /Applications/SelfControl.app")
if not config.has_key("block-schedules"):
    exit_with_error("The setting 'block-schedules' is required.")
if len(config["block-schedules"]) == 0:
    exit_with_error("You need at least one schedule in 'block-schedules'.")
if config.get("host-blacklist", None) is None:
    print("WARNING:")
    msg = "It is not recommended to directly use SelfControl's blacklist. Please use the 'host-blacklist' " \
          "setting instead."
    print(msg)
    syslog.syslog(syslog.LOG_WARNING, msg)
</code>```

答:
Tested in python3.7.</p>

```<code>   tmp = {'a':1, 'b':2, 'c':3}
   print(tmp.__contains__('a')) #True
</code>```

Title: How to replace has_key in python3?

Body:
I try to install Auto-SelfControl and got stuck when executing this command:

sudo /usr/bin/python auto-selfcontrol.py

It shows the error:

AttributeError: 'dict' object has no attribute 'has_key'

I'm searching for solutions and end up with replacing has_key for in operator but as I only know the basics of python, the code is quite complex for me.

There're 3 places where has_key have been used, can you help me change it so I can run with python3?

1.

def check_if_running(username):
""" checks if self-control is already running. """
defaults = get_selfcontrol_settings(username)
return defaults.has_key("BlockStartedDate") and not NSDate.distantFuture().isEqualToDate_(defaults["BlockStartedDate"])

2-4.

def check_config(config):
""" checks whether the config file is correct """
if not config.has_key("username"):
    exit_with_error("No username specified in config.")
if config["username"] not in get_osx_usernames():
    exit_with_error(
            "Username '{username}' unknown.\nPlease use your OSX username instead.\n" \
            "If you have trouble finding it, just enter the command 'whoami'\n" \
            "in your terminal.".format(
                    username=config["username"]))
if not config.has_key("selfcontrol-path"):
    exit_with_error("The setting 'selfcontrol-path' is required and must point to the location of SelfControl.")
if not os.path.exists(config["selfcontrol-path"]):
    exit_with_error(
            "The setting 'selfcontrol-path' does not point to the correct location of SelfControl. " \
            "Please make sure to use an absolute path and include the '.app' extension, " \
            "e.g. /Applications/SelfControl.app")
if not config.has_key("block-schedules"):
    exit_with_error("The setting 'block-schedules' is required.")
if len(config["block-schedules"]) == 0:
    exit_with_error("You need at least one schedule in 'block-schedules'.")
if config.get("host-blacklist", None) is None:
    print("WARNING:")
    msg = "It is not recommended to directly use SelfControl's blacklist. Please use the 'host-blacklist' " \
          "setting instead."
    print(msg)
    syslog.syslog(syslog.LOG_WARNING, msg)

Body:
Tested in python3.7.

   tmp = {'a':1, 'b':2, 'c':3}
   print(tmp.__contains__('a')) #True


问:
dbplyr character columns to database as TEXT instead of VARCHAR
Suppose I'm using the starwars dataset, and tried to create table in Mysql database (using copy_to)

```<code>    library(tidyverse)
    data <- starwars %>%
      select(name, skin_color)

    data

    # A tibble: 87 x 2
   name               skin_color
   <chr>              <chr>
 1 Luke Skywalker     fair
 2 C-3PO              gold
 3 R2-D2              white, blue
 4 Darth Vader        white
 5 Leia Organa        light
 6 Owen Lars          light
 7 Beru Whitesun lars light
 8 R5-D4              white, red
 9 Biggs Darklighter  light
10 Obi-Wan Kenobi     fair
# … with 77 more rows

conn <- DBI::dbConnect(RMariaDB::MariaDB(),
                            host = "myhost",
                            user = "myuser",
                            password = "mypass",
                            db = "mydb")

copy_to(conn, data, temporary = FALSE, overwrite = TRUE)
</code>```

The issue is the character columns are created as TEXT columns but the proper definition should be VARCHAR.

```<code>DESC table data

`data` (
    `name` TEXT NULL,
    `skin_color` TEXT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
</code>```

How to force varchar instead of text?

答:
This may not be your ideal solution, but you could always try first creating the target table in MariaDB before you run the R script.  Then, call copy_to with overwrite set to false:

From MariaDB:

```<code>CREATE TABLE data (
    name varchar(255),
    skin_color varchar(255)
);
</code>```

From R:

```<code>copy_to(conn, data, temporary=FALSE, overwrite=FALSE)
</code>```

Body:
Suppose I'm using the starwars dataset, and tried to create table in Mysql database (using copy_to)

    library(tidyverse)
    data <- starwars %>%
      select(name, skin_color)

    data

    # A tibble: 87 x 2
   name               skin_color
   <chr>              <chr>
 1 Luke Skywalker     fair
 2 C-3PO              gold
 3 R2-D2              white, blue
 4 Darth Vader        white
 5 Leia Organa        light
 6 Owen Lars          light
 7 Beru Whitesun lars light
 8 R5-D4              white, red
 9 Biggs Darklighter  light
10 Obi-Wan Kenobi     fair
# … with 77 more rows

conn <- DBI::dbConnect(RMariaDB::MariaDB(),
                            host = "myhost",
                            user = "myuser",
                            password = "mypass",
                            db = "mydb")

copy_to(conn, data, temporary = FALSE, overwrite = TRUE)

The issue is the character columns are created as TEXT columns but the proper definition should be VARCHAR.

DESC table data

`data` (
    `name` TEXT NULL,
    `skin_color` TEXT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;

How to force varchar instead of text?

Body:
This may not be your ideal solution, but you could always try first creating the target table in MariaDB before you run the R script.  Then, call copy_to with overwrite set to false:

From MariaDB:

CREATE TABLE data (
    name varchar(255),
    skin_color varchar(255)
);

From R:

copy_to(conn, data, temporary=FALSE, overwrite=FALSE)


问:
How to set a default value using Select?
How to set a default value using the select event? Currently in EDIT mode I just hardcoded selectedKey="USD", thus when the user clicks on another value (eg: CAD) it does not update the value to CAD in the VIEW mode.

```<code><Select id="idCurrency" items="{/VH_CurrencySet}" selectedKey="USD">
    <items>
        <core:Item text="{Text}" key="{Code}" />
    </items>
    <layoutData>
        <l:GridData span="XL2 L3 M3 S5" />
    </layoutData>
</Select>
</code>```

In VIEW Mode, the currency should appear as CAD.

答:
Personnaly, I prefer to leverage binding as much as possible.

If you add an entry in your model '/CurrencySelected', the selected value will be reflected in your model permanently.

controller.js

```<code>// somewhere on model init
// If you want to keep USD as default value, otherwise first one will be affected automatically
model.setProperty('/CurrencySelected', 'USD')

// To consume the currency
const currentCurrency = model.getProperty('/CurrencySelected')
</code>```

view.xml

```<code><Select
  id="idCurrency"
  items="{/VH_CurrencySet}"
  selectedKey="{/CurrencySelected}">
  <items>
    <core:Item
      text="{Text}"
      key="{Code}"/>
  </items>
  <layoutData>
    <l:GridData span="XL2 L3 M3 S5"/>
  </layoutData>
</Select>
</code>```

Body:
How to set a default value using the select event? Currently in EDIT mode I just hardcoded selectedKey="USD", thus when the user clicks on another value (eg: CAD) it does not update the value to CAD in the VIEW mode.

<Select id="idCurrency" items="{/VH_CurrencySet}" selectedKey="USD">
    <items>
        <core:Item text="{Text}" key="{Code}" />
    </items>
    <layoutData>
        <l:GridData span="XL2 L3 M3 S5" />
    </layoutData>
</Select>

In VIEW Mode, the currency should appear as CAD.

Body:
Personnaly, I prefer to leverage binding as much as possible.

If you add an entry in your model '/CurrencySelected', the selected value will be reflected in your model permanently.

controller.js

// somewhere on model init
// If you want to keep USD as default value, otherwise first one will be affected automatically
model.setProperty('/CurrencySelected', 'USD')

// To consume the currency
const currentCurrency = model.getProperty('/CurrencySelected')

view.xml

<Select
  id="idCurrency"
  items="{/VH_CurrencySet}"
  selectedKey="{/CurrencySelected}">
  <items>
    <core:Item
      text="{Text}"
      key="{Code}"/>
  </items>
  <layoutData>
    <l:GridData span="XL2 L3 M3 S5"/>
  </layoutData>
</Select>


问:
How to handle long relative paths using the '\\?\' prefix?
So we all know that Windows programs by default are limited to dealing
 with a maximum path length of 260 characters. However, this limit can easily be overcome by prefixing the path by the \\?\ character sequence.

For some reason, however, this isn't possible with relative paths, as MSDN says:

Because you cannot use the \\?\ prefix with a relative path,
  relative paths are always limited to a total of MAX_PATH characters.

(source)

I don't really understand the reason why Microsoft decided to forbid relative paths to be prefixed with \\?\ so if there is some sort of rationale behind this decision, I'd be really glad to hear about it because it doesn't really make sense to me that \\?\ is only allowed for full paths.

My real question, though, is how to deal with this limitation: Should I simply call GetFullPathName() on relative paths to extend them to full paths, then add the \\?\ prefix, and then pass that path to fopen() etc., or what is the recommended way of dealing with this limitation?

答:
You cannot use the \\?\ prefix with a relative path.

When relative path is passed to the system, it is parsed as absolute paths and then passed to the system. And as it is mentioned in the source:

The prefixes \\:\ are not used as part of the path itself. They
  indicate that the path should be passed to the system with minimal
  modification, which means that you cannot use forward slashes to
  represent path separators, or a period to represent the current
  directory, or double dots to represent the parent directory.


问:
Python list creation with multiple loops
lets say I have one list ['A','B','C']

and the second [1,2]

I want to create a new list [(A,1), (A,2), (B,1)...]

Obviously it can be trivially done using a for loop like this:

```<code>a = ['A','B','C']
b = [1,2]
c = []
for x in a:
    for y in b:
        c.append((x,y))

c
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]
</code>```

but how can I do it using the [x for x in...] syntax ?

答:
In your case the list comprehensions version could be:

```<code>>>> [(x, y) for x in "ABC" for y in [1,2]]
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]
</code>```

Note that the order matters, that is for a fixed x='A' the possible values of y are iterated first.

Body:
lets say I have one list ['A','B','C']

and the second [1,2]

I want to create a new list [(A,1), (A,2), (B,1)...]

Obviously it can be trivially done using a for loop like this:

a = ['A','B','C']
b = [1,2]
c = []
for x in a:
    for y in b:
        c.append((x,y))

c
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

but how can I do it using the [x for x in...] syntax ?

Body:
In your case the list comprehensions version could be:

>>> [(x, y) for x in "ABC" for y in [1,2]]
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

Note that the order matters, that is for a fixed x='A' the possible values of y are iterated first.


问:
My controller returns ModelAndView but it doesn't load jsp
I'm studying the restful API. In this project, I wanna log-in using restful API. So, I made two projects. The one is spring MVC. It just shows the web page. Another is the restful API. And It worked well but when I call the web page, it doesn't work.

I found several solutions, but those not for me.
The one checks import org.springframework.web.servlet.ModelAndView. I already used it.
Another used String as the return type in the controller instead of ModelAndView.

This is my Controller.

```<code>@Controller
public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView displayLogin(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView model = new ModelAndView("login");
        return model;
    }

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String displayWelcom(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView model = new ModelAndView("welcome");
        System.out.println("Welcome model");
        return "welcome";
    }
}

</code>```

And This is my javascript for going to another page(welcome).

```<code>function validateForm() {
        var xmlhttp = new XMLHttpRequest();
        var url = "http://localhost:8080/users/www.t3q.com";
        //      + window.location.hostname;
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200) {
                alert('1');
                var json = JSON.parse(xmlhttp.responseText);
//              if(json.isSuccess == 'true')
//              {
                    var xmlhttp2 = new XMLHttpRequest();
                    xmlhttp2.open("GET", "http://localhost:8081/SpringMVCloginExample/welcome", true);
                    xmlhttp2.send();
//              } else {
//                  alert(json.reason);
//              }
                console.log(xmlhttp.responseText);
            }
        };

        xmlhttp.open("POST", url, true);

        xmlhttp.setRequestHeader("Content-Type",
                "application/json;charset=UTF-8");

        var userData = JSON.stringify($("#loginForm").serializeObject());

        console.log(userData);
        xmlhttp.send(userData);
    }
</code>```

And This is my spring web setting XML.

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.t3q" />

<!--    <mvc:annotation-driven /> -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

</beans>
</code>```

And this is web.xml.

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>SpringMVCloginExample</display-name>

    <servlet>
        <servlet-name>springLoginApplication</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath://resource//springWeb.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springLoginApplication</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

Actually, I already used <mvc:annotation-driven />.
How can I solve this problem?
Help me, please.

Additional 1.
This is my project explorer.

Answer (modified)

```<code>var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"localhost:8080/welcome");
$(document.body).append(f);
f.submit();
</code>```

Body:
I'm studying the restful API. In this project, I wanna log-in using restful API. So, I made two projects. The one is spring MVC. It just shows the web page. Another is the restful API. And It worked well but when I call the web page, it doesn't work.

I found several solutions, but those not for me.
The one checks import org.springframework.web.servlet.ModelAndView. I already used it.
Another used String as the return type in the controller instead of ModelAndView.

This is my Controller.

@Controller
public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView displayLogin(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView model = new ModelAndView("login");
        return model;
    }

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String displayWelcom(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView model = new ModelAndView("welcome");
        System.out.println("Welcome model");
        return "welcome";
    }
}

And This is my javascript for going to another page(welcome).

function validateForm() {
        var xmlhttp = new XMLHttpRequest();
        var url = "http://localhost:8080/users/www.t3q.com";
        //      + window.location.hostname;
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200) {
                alert('1');
                var json = JSON.parse(xmlhttp.responseText);
//              if(json.isSuccess == 'true')
//              {
                    var xmlhttp2 = new XMLHttpRequest();
                    xmlhttp2.open("GET", "http://localhost:8081/SpringMVCloginExample/welcome", true);
                    xmlhttp2.send();
//              } else {
//                  alert(json.reason);
//              }
                console.log(xmlhttp.responseText);
            }
        };

        xmlhttp.open("POST", url, true);

        xmlhttp.setRequestHeader("Content-Type",
                "application/json;charset=UTF-8");

        var userData = JSON.stringify($("#loginForm").serializeObject());

        console.log(userData);
        xmlhttp.send(userData);
    }

And This is my spring web setting XML.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.t3q" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

</beans>

And this is web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>SpringMVCloginExample</display-name>

    <servlet>
        <servlet-name>springLoginApplication</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath://resource//springWeb.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springLoginApplication</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Actually, I already used <mvc:annotation-driven />.
How can I solve this problem?
Help me, please.

Additional 1.
This is my project explorer.

Answer (modified)

var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"localhost:8080/welcome");
$(document.body).append(f);
f.submit();


问:
Datetime format in flask marshmallow schema
I want to apply a custom DateTime format for the data retrieved from model using the Schema in flask marshmallow.

Currently using the schema like:

```<code>class ScheduleListSchema(ma.Schema):
    class Meta:
        fields = ('id', 'start_time', 'end_time')
</code>```

In this start_time in format of 2018-12-05T03:00:00+00:00

So I want to create a custom format for the start_time value in schema.

答:
If end_time is the same format as start_time , datetimeformat is another solution:

```<code>class ScheduleListSchema(ma.Schema):
    class Meta:
        fields = ('id', 'start_time', 'end_time')
        datetimeformat = '%Y-%m-%dT%H:%M:%S%z'
</code>```

Body:
I want to apply a custom DateTime format for the data retrieved from model using the Schema in flask marshmallow.

Currently using the schema like:

class ScheduleListSchema(ma.Schema):
    class Meta:
        fields = ('id', 'start_time', 'end_time')

In this start_time in format of 2018-12-05T03:00:00+00:00

So I want to create a custom format for the start_time value in schema.

Body:
If end_time is the same format as start_time , datetimeformat is another solution:

class ScheduleListSchema(ma.Schema):
    class Meta:
        fields = ('id', 'start_time', 'end_time')
        datetimeformat = '%Y-%m-%dT%H:%M:%S%z'


Title: Python list creation with multiple loops

Body:
Take a look at itertools.product:

>>> from itertools import product
>>> a = [ 'A', 'B', 'C' ]
>>> b = [ 1, 2]
>>> [ x for x in product(a, b) ]
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]


答:
You are right - you shouldn't hard code the Selected Key.
You should set the Selected Key in code once the data has been loaded (e.g. by attaching a function to the attachRequestCompleted event off the model you are loading)
This means that USD would be the initial default value only.

After that, the Select control would display the Currency you select.
Trust this makes sense?

```<code><Select id="idCurrency" items="{/VH_CurrencySet}">
    <items>
         <core:Item text="{Text}" key="{Code}"/>
    </items>
</Select>
</code>```

If you need access to the currency code you could bind a variable to the selectedKey.

Title: How to set a default value using Select?

Body:
You are right - you shouldn't hard code the Selected Key.
You should set the Selected Key in code once the data has been loaded (e.g. by attaching a function to the attachRequestCompleted event off the model you are loading)
This means that USD would be the initial default value only.

After that, the Select control would display the Currency you select.
Trust this makes sense?

<Select id="idCurrency" items="{/VH_CurrencySet}">
    <items>
         <core:Item text="{Text}" key="{Code}"/>
    </items>
</Select>

If you need access to the currency code you could bind a variable to the selectedKey.


问:
Extract Pattern Matches / Remove Everything From Line Except Pattern
I'm currently using grep to try to extract specific text from each line of a file. It's successfully extracting the matches, however, I would like it to retain any lines that don't have matches (leave them as a blank line).

This is what I've tried so far (to get the name of the city on each line):

```<code>grep -o -P '(?<="city":").*?(?=")' input.txt
</code>```

Example input:

```<code>email":"addictedtotlick7@gmail.com","last_name":"THOMPSON","first_name":"ERIN",,"__v":0,,,,"state":"NY","city":"north tonawanda"}
first_name":"chris","last_name":"caul",,"email":"dawgzn@mail.com",,,,"__v":0}
email":"lesliebo993@hotmail.com",,"first_name":"LESLIE","last_name":"RAMBO",,"city":"DOTHAN","state":"AL",,,"__v":0,
email":"malala@yahoo.com",,,"state":"GA","city":"NORCROSS",,"last_name":"KEO","first_name":"CATHY",,"__v":0,
email":"kdela@gmail.com",,"state":"FL","city":"HOLLYWOOD",,"last_name":"DE LA CRUZ","first_name":"KIDA",,"__v":0,
</code>```

Desired output:

```<code>north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD
</code>```

Happy to try something in SED too if it's easier, but would prefer to avoid AWK as I have to work with big files, not sure I have enough RAM.

答:
You may do that with GNU awk:

```<code>gawk '{print index($0, "\"city\":\"") == 0 ? "" : gensub(/.*\"city\":\"([^\"]*).*/, "\\1", 1);}' file > newfile
</code>```

This means: if the line has "city":" in it (index($0, "\"city\":\"") == 0) then (?) print a blank line ("") or (:) print the result of the gensub(/.*\"city\":\"([^\"]*).*/, "\\1", 1) regex replacement:

.* - any 0+ chars

\"city\":\" - a "city":" substring

([^\"]*) - Capturing group 1 (\1): any 0+ chars other than "

.* - any 0+ chars.

The result of this is the value of Group 1. We need gensub and hence GNU awk as we need access to the capturing group value.

Body:
I'm currently using grep to try to extract specific text from each line of a file. It's successfully extracting the matches, however, I would like it to retain any lines that don't have matches (leave them as a blank line).

This is what I've tried so far (to get the name of the city on each line):

grep -o -P '(?<="city":").*?(?=")' input.txt

Example input:

email":"addictedtotlick7@gmail.com","last_name":"THOMPSON","first_name":"ERIN",,"__v":0,,,,"state":"NY","city":"north tonawanda"}
first_name":"chris","last_name":"caul",,"email":"dawgzn@mail.com",,,,"__v":0}
email":"lesliebo993@hotmail.com",,"first_name":"LESLIE","last_name":"RAMBO",,"city":"DOTHAN","state":"AL",,,"__v":0,
email":"malala@yahoo.com",,,"state":"GA","city":"NORCROSS",,"last_name":"KEO","first_name":"CATHY",,"__v":0,
email":"kdela@gmail.com",,"state":"FL","city":"HOLLYWOOD",,"last_name":"DE LA CRUZ","first_name":"KIDA",,"__v":0,

Desired output:

north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD

Happy to try something in SED too if it's easier, but would prefer to avoid AWK as I have to work with big files, not sure I have enough RAM.

Body:
You may do that with GNU awk:

gawk '{print index($0, "\"city\":\"") == 0 ? "" : gensub(/.*\"city\":\"([^\"]*).*/, "\\1", 1);}' file > newfile

This means: if the line has "city":" in it (index($0, "\"city\":\"") == 0) then (?) print a blank line ("") or (:) print the result of the gensub(/.*\"city\":\"([^\"]*).*/, "\\1", 1) regex replacement:

.* - any 0+ chars

\"city\":\" - a "city":" substring

([^\"]*) - Capturing group 1 (\1): any 0+ chars other than "

.* - any 0+ chars.

The result of this is the value of Group 1. We need gensub and hence GNU awk as we need access to the capturing group value.


问:
Python compare list of dictionaries with another dictionary in loop
I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

```<code>a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for d in a:

    for i,j in valueDict.items():

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j
            break
    else:

        print('no value')

print(a)
</code>```

Below is the output When I tried to execute above code

```<code>Enter main color: red

Enter secondary color :black

Enter another main color: yellow

Enter another secondary color: white

{'red': 'black', 'yellow': 'white'}

matched

matched

no value

[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]
</code>```

Issue here is 'no value' is getting printed.
In my use case no value shouldn't be printed at all.

I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries.
Please help.

答:
for allow to use else command to use after it iteration complete. you are getting no value beacuse of that.

what you need to do is maintain a flag to capture if an macheded happened or not

example

```<code>for d in a:
    flag = False
    for i,j in valueDict.items():
        if d['main_color'] == i:
            print('matched')
            d['second_color'] = j
            flag = True
            # enter code here
            break
    if flag is False:
            print('no value')
</code>```

Body:
I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for d in a:

    for i,j in valueDict.items():

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j
            break
    else:

        print('no value')

print(a)

Below is the output When I tried to execute above code

Enter main color: red

Enter secondary color :black

Enter another main color: yellow

Enter another secondary color: white

{'red': 'black', 'yellow': 'white'}

matched

matched

no value

[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]

Issue here is 'no value' is getting printed.
In my use case no value shouldn't be printed at all.

I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries.
Please help.

Body:
for allow to use else command to use after it iteration complete. you are getting no value beacuse of that.

what you need to do is maintain a flag to capture if an macheded happened or not

example

for d in a:
    flag = False
    for i,j in valueDict.items():
        if d['main_color'] == i:
            print('matched')
            d['second_color'] = j
            flag = True
            # enter code here
            break
    if flag is False:
            print('no value')


问:
Saving ggplot plot in R with deeper color depth than PNG-8 format
In R, the default settings to save a PNG file (e.g. ggplot/ggsave) is always the PNG-8 format, which allows up to 256 (2^8) colors. How can I save a image with deep color depth, such as 16/24-bit color? So I can get a "True color' image.</p>

```<code>  ggplot(mtcars)+ geom_point(aes(x=gear,y=mpg))
  ggsave('car.png')
</code>```

答:
You could use cairographics for that. This should default to a larger format.</p>

```<code>install.packages("Cairo")
library(Cairo)

ggsave("car.png", type = "cairo-png")
</code>```

Body:
In R, the default settings to save a PNG file (e.g. ggplot/ggsave) is always the PNG-8 format, which allows up to 256 (2^8) colors. How can I save a image with deep color depth, such as 16/24-bit color? So I can get a "True color' image.

  ggplot(mtcars)+ geom_point(aes(x=gear,y=mpg))
  ggsave('car.png')

Body:
You could use cairographics for that. This should default to a larger format.

install.packages("Cairo")
library(Cairo)

ggsave("car.png", type = "cairo-png")


问:
Do we need additional web server like Apache to handle multiple API requests from Dart server?
I am starting with server-side Dart to have a "microservice" like architecture to provide REST API interface to IOT nodes.

As I have good experience with Flutter I want to use Dart for server-side application as well.

But I have a few queries regarding implementation as follows :

A. Do we need any additional web server like Apache to handle multiple simultaneous REST API requests from IoT devices/clients? Does Dart Server capable to handle large traffic independently?

B. Is there any document/case study of comparing client request handling capability of Dart server side Vs Node Js / Python Flask

Thanks,
Gaurav

答:
A. Dart has its own HTTP server implementations, you don't need Apache, refer to aqueduct, shelf or angel for starters.

B. I don't know of any specific studies however you can find articles like this if you google, in general the Dart VM performs well in this respect. Note that if you use Google cloud you can now also use Dart in the Cloud Run product if all you want to do is serve HTTP requests, see here


问:
C++ : const reference to local object
```<code>const std::string s1 = "abc";
const std::string & s2 = "abc";
</code>```

Is the definition of s2 legal? If so, what is the difference between between s1 and s2?

Thanks.

答:
Yes, s2 is legal. s2 is bound to a temporary std::string - extending the temporaries lifetime. s1 isn't a temporary, it's a named variable.

See 12.2/5:

The second context is when a reference
  is bound to a temporary. The temporary
  to which the reference is bound or the
  temporary that is the complete object
  to a subobject of which the temporary
  is bound persists for the lifetime of
  the reference except as specified
  below.

Title: C++ : const reference to local object

Body:
const std::string s1 = "abc";
const std::string & s2 = "abc";

Is the definition of s2 legal? If so, what is the difference between between s1 and s2?

Thanks.


问:
Short way to replace values in a Series based on values in another Series?
I the below code, I am replacing all NaN values from column b with blank string if the corresponding value in column a is 1.

The code works, but I have to type df.loc[df.a == 1, 'b'] twice.

Is there a shorter/better way to do it?

```<code>    import pandas as pd

    df = pd.DataFrame({
        'a': [1, None, 3],
        'b': [None, 5, 6],
    })

    filtered = df.loc[df.a == 1, 'b']
    filtered.fillna('', inplace=True)
    df.loc[df.a == 1, 'b'] = filtered
    print(df)
</code>```

答:
Use Series.fillna only for matched values by condition:

```<code>df.loc[df.a == 1, 'b'] = df['b'].fillna('')
</code>```

Body:
I the below code, I am replacing all NaN values from column b with blank string if the corresponding value in column a is 1.

The code works, but I have to type df.loc[df.a == 1, 'b'] twice.

Is there a shorter/better way to do it?

    import pandas as pd

    df = pd.DataFrame({
        'a': [1, None, 3],
        'b': [None, 5, 6],
    })

    filtered = df.loc[df.a == 1, 'b']
    filtered.fillna('', inplace=True)
    df.loc[df.a == 1, 'b'] = filtered
    print(df)

Body:
Use Series.fillna only for matched values by condition:

df.loc[df.a == 1, 'b'] = df['b'].fillna('')


答:
Using python lists:

```<code>[(i, j) for i in a for j in b]
</code>```

Using a module:

```<code>from itertools import product

list(product(a, b))
</code>```

Body:
Using python lists:

[(i, j) for i in a for j in b]

Using a module:

from itertools import product

list(product(a, b))


问:
Javascript function call with Thymeleaf
I need to call a javascript function on thymeleaf template, something like this:

Case 1:

```<code><select th:onclick="${'function1('a')'}">
</code>```

But in this case the thymeleaf not work.. some researchs ago (including stackoverflow) I get the followings "solutions":

Case 2:

```<code><select th:onclick="${'function1(''a'')'}">
</code>```

Case 3:

```<code><select th:onclick="${'function1(\'a\')'}">
</code>```

Case 4:

```<code><select th:onclick="${'function1(\''+'a'+'\')'}">
</code>```

But in all cases I get the same error: "...Exception evaluating SpringEL expression..."

My problem is about javascript callings, I need put some parameters ${var} for call in js function. How I can fix that ?

Thanks

答:
As far as I know, you have two possibilities how to do it:

Using double brackets

```<code><body th:onload="showToast([[${toast}]])">
...
</body>
</code>```

And then JS function like this

```<code>function showToast(toast) {
    M.toast({html: toast});
}
</code>```

Using data- attribute

```<code><body th:data-toast="${toast}" th:onload="showToast()">
...
</body>
</code>```

And appropriate JS function

```<code>function showToast() {
    var toast = document.querySelectorAll('body')[0].getAttribute('data-toast');
    M.toast({html: toast});
}
</code>```

Title: Javascript function call with Thymeleaf

Body:
I need to call a javascript function on thymeleaf template, something like this:

Case 1:

<select th:onclick="${'function1('a')'}">

But in this case the thymeleaf not work.. some researchs ago (including stackoverflow) I get the followings "solutions":

Case 2:

<select th:onclick="${'function1(''a'')'}">

Case 3:

<select th:onclick="${'function1(\'a\')'}">

Case 4:

<select th:onclick="${'function1(\''+'a'+'\')'}">

But in all cases I get the same error: "...Exception evaluating SpringEL expression..."

My problem is about javascript callings, I need put some parameters ${var} for call in js function. How I can fix that ?

Thanks

Body:
As far as I know, you have two possibilities how to do it:

Using double brackets

<body th:onload="showToast([[${toast}]])">
...
</body>

And then JS function like this

function showToast(toast) {
    M.toast({html: toast});
}

Using data- attribute

<body th:data-toast="${toast}" th:onload="showToast()">
...
</body>

And appropriate JS function

function showToast() {
    var toast = document.querySelectorAll('body')[0].getAttribute('data-toast');
    M.toast({html: toast});
}


问:
Finding the sum of minimum distance from the points in one list to points in other list?
I have two lists containing x and y number of n-dimensional points respectively. I had to calculate the sum of minimum distances of each point in list one (containing x points) from each point in second list (containing y points). The distance I am calculating is Euclidean distance. The optimized solution is needed.

I have already implemented its naive solution in Python. But its time complexity is too much to be used anywhere. There will be optimization possible. Can this problems time complexity be reduced than what I have implemented?

I was reading thispaper which I was trying to implement. In this they were having the similar problem to which they stated that it's special condition of Earth Mover Distance. As there was no code given, hence unable to know how it got implemented. Thus my naive implementation, the above code was too slow to work on data set of 11k documents. I used Google Colab for executing my code.

# Calculating Euclidean distance between two points
def euclidean_dist(x,y):
  dd = 0.0
  #len(x) is number of dimensions. Basically x and y is a
  #list which contains coordinates of a point
  for i in range(len(x)):
    dd = dd+(x[i]-y[i])**2
  return dd**(1/2)

# Calculating the desired solution to our problem
def dist(l1,l2):
  min_dd = 0.0
  dd = euclidean_dist(l1[0],l2[0])
  for j in range(len(l1)):
    for k in range(len(l2)):
      temp = euclidean_dist(l1[j],l2[k])
      if dd > temp:
        dd = temp
    min_dd = min_dd+dd
    dd = euclidean_dist(l1[j],l2[0])
  return min_dd
```

答:
Small arrays

For two numpy arrays x and y of shape (n,) and (m,) respectively, you can vectorize the distance calculations and then get the minimum distance:

```<code>import numpy as np

n = 10
m = 20

x = np.random.random(n)
y = np.random.random(m)

# Using squared distance matrix and taking the
# square root at the minimum value
distance_matrix = (x[:,None]-y[None,:])**2
minimum_distance_sum = np.sum(np.sqrt(np.min(distance_matrix, axis=1)))
</code>```

For arrays of shape (n,l) and (m,l), you just need to calculate the distance_matrix as:

```<code>distance_matrix = np.sum((x[:,None]-y[None,:])**2, axis=2)
</code>```

Alternatively, you could use np.linalg.norm, scipy.spatial.distance.cdist, np.einsum etc., but in many cases they are not faster.

Large arrays

If l, n and m above are too large for you to keep the distance_matrix in memory, you can use the mathematical lower and upper bound of the euclidean distance to increase the speed (see this paper. Since this relies on for loops, it will be very slow, but one can wrap the functions with numba to counter this:

```<code>import numpy as np
import numba

@numba.jit(nopython=True, fastmath=True)
def get_squared_distance(a,b):
    return np.sum((a-b)**2)

def get_minimum_distance_sum(x,y):
    n = x.shape[0]
    m = y.shape[0]
    l = x.shape[1]

    # Calculate mean and standard deviation of both arrays
    mx = np.mean(x, axis=1)
    my = np.mean(y, axis=1)
    sx = np.std(x, axis=1)
    sy = np.std(y, axis=1)
    return _get_minimum_distance_sum(x,y,n,m,l,mx,my,sx,sy)

@numba.jit(nopython=True, fastmath=True)
def _get_minimum_distance_sum(x,y,n,m,l,mx,my,sx,sy):
    min_distance_sum = 0
    for i in range(n):
        min_distance = get_squared_distance(x[i], y[0])
        for j in range(1,m):
            if i == 0 and j == 0:
                continue
            lower_bound = l * ((mx[i] - my[j])**2 + (sx[i] - sy[j])**2)
            if lower_bound >= min_distance:
                continue
            distance = get_squared_distance(x[i], y[j])
            if distance < min_distance:
                min_distance = distance
        min_distance_sum += np.sqrt(min_distance)

    return min_distance_sum

def test_minimum_distance_sum():
    # Will likely be much larger for this to be faster than the other method
    n = 10
    m = 20
    l = 100

    x = np.random.random((n,l))
    y = np.random.random((m,l))

    return get_minimum_distance_sum(x,y)
</code>```

This approach should be faster than the former approach with increased array size. The algorithm can be improved slightly as described in the paper, but any speedup would depend heavily on the shape of the arrays.

Timings

On my laptop, on two arrays of shape (1000,100), your approach takes ~1 min, the "small arrays" approach takes 690 ms and the "large arrays" approach takes 288 ms. For two arrays of shape (100, 3), your approach takes 28 ms, the "small arrays" approach takes 429 μs and the "large arrays" approach takes 578 μs.

Body:
Small arrays

For two numpy arrays x and y of shape (n,) and (m,) respectively, you can vectorize the distance calculations and then get the minimum distance:

import numpy as np

n = 10
m = 20

x = np.random.random(n)
y = np.random.random(m)

# Using squared distance matrix and taking the
# square root at the minimum value
distance_matrix = (x[:,None]-y[None,:])**2
minimum_distance_sum = np.sum(np.sqrt(np.min(distance_matrix, axis=1)))

For arrays of shape (n,l) and (m,l), you just need to calculate the distance_matrix as:

distance_matrix = np.sum((x[:,None]-y[None,:])**2, axis=2)

Alternatively, you could use np.linalg.norm, scipy.spatial.distance.cdist, np.einsum etc., but in many cases they are not faster.

Large arrays

If l, n and m above are too large for you to keep the distance_matrix in memory, you can use the mathematical lower and upper bound of the euclidean distance to increase the speed (see this paper. Since this relies on for loops, it will be very slow, but one can wrap the functions with numba to counter this:

import numpy as np
import numba

@numba.jit(nopython=True, fastmath=True)
def get_squared_distance(a,b):
    return np.sum((a-b)**2)

def get_minimum_distance_sum(x,y):
    n = x.shape[0]
    m = y.shape[0]
    l = x.shape[1]

    # Calculate mean and standard deviation of both arrays
    mx = np.mean(x, axis=1)
    my = np.mean(y, axis=1)
    sx = np.std(x, axis=1)
    sy = np.std(y, axis=1)
    return _get_minimum_distance_sum(x,y,n,m,l,mx,my,sx,sy)

@numba.jit(nopython=True, fastmath=True)
def _get_minimum_distance_sum(x,y,n,m,l,mx,my,sx,sy):
    min_distance_sum = 0
    for i in range(n):
        min_distance = get_squared_distance(x[i], y[0])
        for j in range(1,m):
            if i == 0 and j == 0:
                continue
            lower_bound = l * ((mx[i] - my[j])**2 + (sx[i] - sy[j])**2)
            if lower_bound >= min_distance:
                continue
            distance = get_squared_distance(x[i], y[j])
            if distance < min_distance:
                min_distance = distance
        min_distance_sum += np.sqrt(min_distance)

    return min_distance_sum

def test_minimum_distance_sum():
    # Will likely be much larger for this to be faster than the other method
    n = 10
    m = 20
    l = 100

    x = np.random.random((n,l))
    y = np.random.random((m,l))

    return get_minimum_distance_sum(x,y)

This approach should be faster than the former approach with increased array size. The algorithm can be improved slightly as described in the paper, but any speedup would depend heavily on the shape of the arrays.

Timings

On my laptop, on two arrays of shape (1000,100), your approach takes ~1 min, the "small arrays" approach takes 690 ms and the "large arrays" approach takes 288 ms. For two arrays of shape (100, 3), your approach takes 28 ms, the "small arrays" approach takes 429 μs and the "large arrays" approach takes 578 μs.


答:
[x for x in...] syntax has name and it called list comprehension, you can write your loops between [ and ] and put inner most before your loops.

```<code>[(x, y) for x in a for y in b]
</code>```

Body:
lets say I have one list ['A','B','C']

and the second [1,2]

I want to create a new list [(A,1), (A,2), (B,1)...]

Obviously it can be trivially done using a for loop like this:

a = ['A','B','C']
b = [1,2]
c = []
for x in a:
    for y in b:
        c.append((x,y))

c
[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

but how can I do it using the [x for x in...] syntax ?

Body:
[x for x in...] syntax has name and it called list comprehension, you can write your loops between [ and ] and put inner most before your loops.

[(x, y) for x in a for y in b]


问:
How do I add versions to “Visual Studio Version Selector”, my list is empty
I have VS 2008, 2010, and 2012 installed.

Initially, VS2013 Team Explorer was installed (Shell only).  I uninstalled that.

Now, the Visual Studio Version Selector shows an empty list when executing a .sln file.  Nothing shows.

How can I repopulate this list?  Where is it stored?  Registry?  I tried to find entries, but since it doesn't actually have any items in the list, I couldn't search for a specific string.

答:
Just ran into this situation for VS2017 then I realized I have unfinished updates for Visual Studio when checking Visual Studio Installer.

The installer displayed a hint that I should restart my computer to complete the update and after doing so, the version selector works again.