问:
problems configuring Spring + JPA/Hibernate: java.lang.ClassNotFoundException: org.Hibernate.ejb.HibernatePersistence
I want to use Spring 3.2.8 + JPA/Hibernate on Oracle DB (first time for me).

I think I can not configure correctly something (persistence unit, spring config files) so i have always an error when deploying in Tomcat.

```<code>   Caused by: java.lang.ClassNotFoundException: org.Hibernate.ejb.HibernatePersistence
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:255)
    at org.springframework.util.ClassUtils.resolveClassName(ClassUtils.java:288)
    ... 38 more

Aug 08, 2014 1:37:16 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Aug 08, 2014 1:37:16 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/ftc-wo-webapp] startup failed due to previous errors
Aug 08, 2014 1:37:16 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Aug 08, 2014 1:37:16 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
</code>```

The hibernate jars (including entity manager jar) are contained in the final war (under WEB-INF/lib) So I don't understand why still the class is not founded.
The following configuration is present:

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
      xmlns="http://java.sun.com/xml/ns/persistence"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
      http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="woBPFlowInfo">
    <provider>org.Hibernate.ejb.HibernatePersistence</provider>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
      <property name="hibernate.max_fetch_depth" value="3"/>
      <property name="hibernate.hbm2ddl.auto" value="update" />
      <property name="hibernate.show_sql" value="true" />
    </properties>
  </persistence-unit>
</persistence>
</code>```

main spring config file: app_config.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      ...
    <context:component-scan base-package="com.ftc.webapp" />

    <mvc:annotation-driven/>

<!-- Database added -->

    <!-- Loads BPFlowInfo from the JPA system -->
    <bean id="woBPFlowRepository" class="com.ftc.webapp.data.JpaWoBPFlowRepository"/>

    <!-- Instructs the container to look for beans with @Transactional and decorate them -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Enables annotation-config, needed for @PersistenceContext annotations -->
    <context:annotation-config />

     <import resource="db_config.xml"/>
</beans>
</code>```

db_config.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<!-- // NAME: rewards-db-config.xml // // MODULE: rewardsdb // // PURPOSE:
    Database and transaction configuration for testing the rewards // application. -->
<beans xmlns="...">

    <context:annotation-config />

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource"
          class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="testOnBorrow" value="true" />
        <property name="initialSize" value="2" />
        <property name="maxActive" value="50" />
        <property name="removeAbandoned" value="true"/>
        <property name="removeAbandonedTimeout" value="300"/>
        <property name="validationQuery" value="select 1 from dual" />
    </bean>

    <!-- Translates ORM exceptions to Spring Data Access Exceptions -->
    <bean
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <!-- Data access using 100% JPA -->
        <!-- A transaction manager for working with JPA Entity Managers -->
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>

        <!-- FactoryBean that creates the EntityManagerFactory -->
        <bean id="entityManagerFactory"  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="persistenceUnitName" value="woBPFlowInfo" />
        </bean>
</beans>
</code>```

and pom.xml contains  following dependencies:

pom.xml

```<code>  <properties>
      <smp.version>5.2.2.6</smp.version>
      <spring.version>3.2.8.RELEASE</spring.version>
      <hibernate.version>3.4.0.GA</hibernate.version>
      <javaxServlet.version>2.5</javaxServlet.version>
      <jackson.version>1.9.5</jackson.version>
  </properties>
  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>jsr250-api</artifactId>
        <version>1.0</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${javaxServlet.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <!-- Persistency & Object Relational mapping -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.5.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>ojdbc</groupId>
        <artifactId>ojdbc</artifactId>
        <version>14</version>
    </dependency>

   <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
  </dependencies>
</code>```

答:
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> is the right persistence provider as per JPA standards.

<provider>org.hibernate.ejb.HibernatePersistence</provider> is deprecated.

Body:
I want to use Spring 3.2.8 + JPA/Hibernate on Oracle DB (first time for me).

I think I can not configure correctly something (persistence unit, spring config files) so i have always an error when deploying in Tomcat.

   Caused by: java.lang.ClassNotFoundException: org.Hibernate.ejb.HibernatePersistence
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:255)
    at org.springframework.util.ClassUtils.resolveClassName(ClassUtils.java:288)
    ... 38 more

Aug 08, 2014 1:37:16 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Aug 08, 2014 1:37:16 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/ftc-wo-webapp] startup failed due to previous errors
Aug 08, 2014 1:37:16 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Aug 08, 2014 1:37:16 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]

The hibernate jars (including entity manager jar) are contained in the final war (under WEB-INF/lib) So I don't understand why still the class is not founded.
The following configuration is present:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
      xmlns="http://java.sun.com/xml/ns/persistence"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
      http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="woBPFlowInfo">
    <provider>org.Hibernate.ejb.HibernatePersistence</provider>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
      <property name="hibernate.max_fetch_depth" value="3"/>
      <property name="hibernate.hbm2ddl.auto" value="update" />
      <property name="hibernate.show_sql" value="true" />
    </properties>
  </persistence-unit>
</persistence>

main spring config file: app_config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      ...
    <context:component-scan base-package="com.ftc.webapp" />

    <mvc:annotation-driven/>

    <bean id="woBPFlowRepository" class="com.ftc.webapp.data.JpaWoBPFlowRepository"/>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <context:annotation-config />

     <import resource="db_config.xml"/>
</beans>

db_config.xml file

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="...">

    <context:annotation-config />

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource"
          class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="testOnBorrow" value="true" />
        <property name="initialSize" value="2" />
        <property name="maxActive" value="50" />
        <property name="removeAbandoned" value="true"/>
        <property name="removeAbandonedTimeout" value="300"/>
        <property name="validationQuery" value="select 1 from dual" />
    </bean>

    <bean
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>

        <bean id="entityManagerFactory"  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="persistenceUnitName" value="woBPFlowInfo" />
        </bean>
</beans>

and pom.xml contains  following dependencies:

pom.xml

  <properties>
      <smp.version>5.2.2.6</smp.version>
      <spring.version>3.2.8.RELEASE</spring.version>
      <hibernate.version>3.4.0.GA</hibernate.version>
      <javaxServlet.version>2.5</javaxServlet.version>
      <jackson.version>1.9.5</jackson.version>
  </properties>
  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>jsr250-api</artifactId>
        <version>1.0</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${javaxServlet.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.5.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>ojdbc</groupId>
        <artifactId>ojdbc</artifactId>
        <version>14</version>
    </dependency>

   <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
  </dependencies>


来源: stackexchange

问:
How Cassandra Handle a select query?
I'm working on designing Cassandra column family.

I met with a situation of higher GC while SELECTing, after loading a higher density of data. That is, amount of data in a partition increased. Also for low density data, it works fine.

I want to know how Cassandra does the SELECT query (with both partition and cluster key specified)?

Is the whole set of data in a partition is loaded into memory while we execute SELECT?

Will large number of partition keys affect performance?

答:
Cassandra does not load the entire partition into memory, but it does load IndexInfo objects which help Cassandra find the relevant CQL rows within the partition. These are short lived java objects which can create quite a bit of heap pressure (GC pauses) - this is a design issue that will be addressed in CASSANDRA-9754 (known as Birch, a b-tree implementation of the index data structure).

Until cassandra-4.0 is released, you should target 100MB for your max partition size, and break larger partitions into smaller pieces.

ContentLicense: CC BY-SA 3.0

Title: How Cassandra Handle a select query?


问:
Merge and broadcast, building a (simple) Akka graph
The Akka documentation is vast and there are a lot of tutorials. But either they are outdated or they only cover the basics (or, maybe I simply can't find the right ones).

What I want to create is a websocket application with multiple clients and multiple sources on the server side. As I don't want to get over my head from the start, I want to make baby steps and incrementally increase the complexity of the software I am building.

After toying around with some simple flows I wanted to start with a more sophisticated graph now.

What I want is:

Two sources, one that pushes "keepAlive" messages from the server to the client (currently only one) and a second one that actually pushes useful data.

Now for the first one I have this:

```<code>val tickingSource: Source[Array[Byte], Cancellable] =
  Source.tick(initialDelay = 1 second, interval = 10 seconds, tick = NotUsed)
        .zipWithIndex
        .map{ case (_, counter) => SomeMessage().toByteArray}
</code>```

Where SomeMessage is a protobuf type.

Because I can't find an up-to-date way to add an actor as a source, I tried the following for my second source:

```<code>val secondSource = Source(1 to 1000)
val secondSourceConverter = Flow[Int].map(x => BigInteger.valueOf(x).toByteArray)
</code>```

My attempt at the graph:

```<code>val g: RunnableGraph[NotUsed] = RunnableGraph.fromGraph(GraphDSL.create()
{
  implicit builder =>
  import GraphDSL.Implicits._

  val sourceMerge = builder.add(Merge[Array[Byte]](2).named("sourceMerge"))

  val x = Source(1 to 1000)

  val y = Flow[Int].map(x => BigInteger.valueOf(x).toByteArray)

  val out = Sink.ignore
  tickingSource ~> sourceMerge ~> out
  x ~> y ~> sourceMerge

  ClosedShape
})
</code>```

Now g is of type RunnableGraph[NotUsed] while it should be RunnableGraph[Array[Byte]] for my websocket. And I wonder here: am I already doing something completely wrong?

答:
I'm not sure how you would like to process incoming messages but here is a simple example. Hope that it'll help you.</p>

```<code>path("ws") {
   extractUpgradeToWebSocket { upgrade =>
    complete {
      import scala.concurrent.duration._
      val tickSource = Source.tick(1.second, 1.second, TextMessage("ping"))
      val messagesSource = Source.queue(10, OverflowStrategy.backpressure)
      messagesSource.mapMaterializedValue { queue =>
        //do something with out queue
        //like myHandler ! RegisterOutQueue(queue)
      }
      val sink = Sink.ignore
      val source = tickSource.merge(messagesSource)
      upgrade.handleMessagesWithSinkSource(
        inSink = sink,
        outSource = source
      )
   }
}
</code>```

Body:
The Akka documentation is vast and there are a lot of tutorials. But either they are outdated or they only cover the basics (or, maybe I simply can't find the right ones).

What I want to create is a websocket application with multiple clients and multiple sources on the server side. As I don't want to get over my head from the start, I want to make baby steps and incrementally increase the complexity of the software I am building.

After toying around with some simple flows I wanted to start with a more sophisticated graph now.

What I want is:

Two sources, one that pushes "keepAlive" messages from the server to the client (currently only one) and a second one that actually pushes useful data.

Now for the first one I have this:

val tickingSource: Source[Array[Byte], Cancellable] =
  Source.tick(initialDelay = 1 second, interval = 10 seconds, tick = NotUsed)
        .zipWithIndex
        .map{ case (_, counter) => SomeMessage().toByteArray}

Where SomeMessage is a protobuf type.

Because I can't find an up-to-date way to add an actor as a source, I tried the following for my second source:

val secondSource = Source(1 to 1000)
val secondSourceConverter = Flow[Int].map(x => BigInteger.valueOf(x).toByteArray)

My attempt at the graph:

val g: RunnableGraph[NotUsed] = RunnableGraph.fromGraph(GraphDSL.create()
{
  implicit builder =>
  import GraphDSL.Implicits._

  val sourceMerge = builder.add(Merge[Array[Byte]](2).named("sourceMerge"))

  val x = Source(1 to 1000)

  val y = Flow[Int].map(x => BigInteger.valueOf(x).toByteArray)

  val out = Sink.ignore
  tickingSource ~> sourceMerge ~> out
  x ~> y ~> sourceMerge

  ClosedShape
})

Now g is of type RunnableGraph[NotUsed] while it should be RunnableGraph[Array[Byte]] for my websocket. And I wonder here: am I already doing something completely wrong?

Body:
I'm not sure how you would like to process incoming messages but here is a simple example. Hope that it'll help you.

path("ws") {
   extractUpgradeToWebSocket { upgrade =>
    complete {
      import scala.concurrent.duration._
      val tickSource = Source.tick(1.second, 1.second, TextMessage("ping"))
      val messagesSource = Source.queue(10, OverflowStrategy.backpressure)
      messagesSource.mapMaterializedValue { queue =>
        //do something with out queue
        //like myHandler ! RegisterOutQueue(queue)
      }
      val sink = Sink.ignore
      val source = tickSource.merge(messagesSource)
      upgrade.handleMessagesWithSinkSource(
        inSink = sink,
        outSource = source
      )
   }
}


问:
Regex to obfuscate substring of a repeating substring
Given a string like:

```<code>abc_1234 xyz def_123aa4a56
</code>```

I want to replace parts of it so the output is:

```<code>abc_*******z def_*******56
</code>```

The rules are:

abc_ and def_ are kind of delimiters, so anything between the two are part of the previous delimiter string.

The string between the abc_ and def_, and the next delimited string should be replaced by *, except for the last 2 characters of that substring. In the above example, abc_1234 xyz  (note trailing space), got turned into abc_*******z

Body:
Given a string like:

abc_1234 xyz def_123aa4a56

I want to replace parts of it so the output is:

abc_*******z def_*******56

The rules are:

abc_ and def_ are kind of delimiters, so anything between the two are part of the previous delimiter string.

The string between the abc_ and def_, and the next delimited string should be replaced by *, except for the last 2 characters of that substring. In the above example, abc_1234 xyz  (note trailing space), got turned into abc_*******z

Body:
Given:

> s
=> "abc_1234 xyz def_123aa4a56"

You can do:

> s.gsub(/(?<=abc_|def_)(.*?)(..)(?=(?:abc_|def_|$))/) { |m| "*" * $1.length<<$2  }
=> "abc_*******z def_*******56"


问:
MongoDB: Server has startup warnings
I firstly installed MongoDB 3.2.5 today. But when I start it and use MongoDB shell, it gave me these warnings below:

```<code>C:\Windows\system32>mongo
MongoDB shell version: 3.2.5
connecting to: test
Server has startup warnings:
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten]
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten] ** WARNING: Insecure configuration, access control is not enabled and no --bind_ip has been specified.
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted,
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten] **          and the server listens on all available network interfaces.
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten]
>
</code>```

my OS is Microsoft Windows [version 10.0.10586].

答:
Select the target DB (Exp : use admin)

Create user in the selected DB

Select the required DB (exp use admin)

```<code>db.createUser(
   {
     user: "root",
     pwd: "root",
     roles: [ "readWrite", "dbAdmin" ]
   }
)
</code>```

The above command will create the root user with roles readWrite and dbAdmin in the admin DB. more info about roles

Now, run the server in authentication mode using mongod --auth

Run client and provide username and password to login using db.auth("root","root")

ContentLicense: CC BY-SA 4.0

Title: MongoDB: Server has startup warnings

Body:
I firstly installed MongoDB 3.2.5 today. But when I start it and use MongoDB shell, it gave me these warnings below:

C:\Windows\system32>mongo
MongoDB shell version: 3.2.5
connecting to: test
Server has startup warnings:
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten]
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten] ** WARNING: Insecure configuration, access control is not enabled and no --bind_ip has been specified.
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted,
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten] **          and the server listens on all available network interfaces.
2016-04-16T11:06:17.943+0800 I CONTROL  [initandlisten]
>

my OS is Microsoft Windows [version 10.0.10586].

Body:
Select the target DB (Exp : use admin)

Create user in the selected DB

Select the required DB (exp use admin)

db.createUser(
   {
     user: "root",
     pwd: "root",
     roles: [ "readWrite", "dbAdmin" ]
   }
)

The above command will create the root user with roles readWrite and dbAdmin in the admin DB. more info about roles

Now, run the server in authentication mode using mongod --auth

Run client and provide username and password to login using db.auth("root","root")


问:
Robot Framework How to get different timezone and locale for different country?
In robot framework, the current supported keyword to get timezone is:

```<code>${month}  Get Current Date  result_format=%B%Y
</code>```

which will return: July 2017

The question is how to get current date from other country and locale?
as example in Vietnam should return: Tháng Bảy 2017
and Thailand should return : กรกฎาคม พ.ศ. 2560

答:
In the Robot Framework Datetime library the concept of changing the TimeZone is not present. The Robot Framework Custom Timestamp functions rely on the underlying Python datatime.strptime function. This function uses the python Locale for it's formatting.

As this has now become a more general Python problem, I've searched SO and found this particular SO answer to fulfill the criteria to create a custom Python Keyword for Robot Framework that would allow changing the Locale and thus determine the output.

Body:
In robot framework, the current supported keyword to get timezone is:

${month}  Get Current Date  result_format=%B%Y

which will return: July 2017

The question is how to get current date from other country and locale?
as example in Vietnam should return: Tháng Bảy 2017
and Thailand should return : กรกฎาคม พ.ศ. 2560


问:
Nightwatch - button click using button text name
Is there any way to click the button using button text?

Button 1
Button 2
Button 3
Button 4

I currently use :nth-of-type to locate them but I'm looking for something more readable. (Xpath also not very readable).

The other option I'm thinking about, to use page objects and move not readable selector there.

答:
CSS selectors do not currently support matching text, and probably never will. You can use xpath to locate the button by its text.

/* This will match any button that contains the string 'Button 1'. If there were say, a Button 12, Nightwatch will complain about multiple elements matching that selector, but it will generally work. */

```<code>.useXpath().click("//*[contains(text(),'Button 1')]")
</code>```

/*
 This will match only a button that exactly matches the string 'Button 1'*/

.useXpath().click("//*[.='Button 1']")
// Note that spaces matter, so if there is a leading or trailing space in the html, or anything else, it won't work.

/* Finally, let's say your buttons aren't numbered, like this html:*/

```<code><button class="astext"><span>Foo</span></button>
<button class="astext"><span>Foo</span></button>
<button class="astext"><span>Foo</span></button>
<button class="astext"><span>Foo</span></button>
</code>```

/* you still have options here. by indexing into the item you want. Let's assume you want to click the second button with the text "Foo". To do that, wrap your xpath expression in parenthesis, and then note your index in brackets like this:*/

```<code>.useXpath().click("(//*[contains(text(),'Foo')])[2]")
</code>```

xpath selectors are worth knowing. There are times when it's just far simpler to write an xpath selector and with practice, it's reasonably easy to do. Here is an excellent source document on xpath selectors

Body:
CSS selectors do not currently support matching text, and probably never will. You can use xpath to locate the button by its text.

/* This will match any button that contains the string 'Button 1'. If there were say, a Button 12, Nightwatch will complain about multiple elements matching that selector, but it will generally work. */

.useXpath().click("//*[contains(text(),'Button 1')]")

/*
 This will match only a button that exactly matches the string 'Button 1'*/

.useXpath().click("//*[.='Button 1']")
// Note that spaces matter, so if there is a leading or trailing space in the html, or anything else, it won't work.

/* Finally, let's say your buttons aren't numbered, like this html:*/

<button class="astext"><span>Foo</span></button>
<button class="astext"><span>Foo</span></button>
<button class="astext"><span>Foo</span></button>
<button class="astext"><span>Foo</span></button>

/* you still have options here. by indexing into the item you want. Let's assume you want to click the second button with the text "Foo". To do that, wrap your xpath expression in parenthesis, and then note your index in brackets like this:*/

.useXpath().click("(//*[contains(text(),'Foo')])[2]")

xpath selectors are worth knowing. There are times when it's just far simpler to write an xpath selector and with practice, it's reasonably easy to do. Here is an excellent source document on xpath selectors


问:
Laravel chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted
After I updated the following packages I got an error that the oauth-public.key file couldn't be found.

Package operations: 1 install, 2 updates, 0 removals

Updating laravel/framework (v5.4.27 => v5.4.28): Downloading (100%)

    Installing defuse/php-encryption (v2.1.0): Downloading (100%)

    Updating league/oauth2-server (5.1.3 => 5.1.4): Downloading (100%)

Firstly I deleted the two oauth- files in project/storage and then executed this command: php artisan passport:install to generate new oauth- files.

Now I get the following error when trying to access an api route.

(1/1) ErrorException
  chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted

Stack trace

in CryptKey.php (line 51)

at HandleExceptions->handleError(2, 'chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted', '/var/dev/project/vendor/league/oauth2-server/src/CryptKey.php', 51, array('keyPath' => 'file:///var/dev/project/storage/oauth-public.key', 'passPhrase' => null, 'keyPathPerms' => '644'))

at chmod('file:///var/dev/project/storage/oauth-public.key', 384)
  in CryptKey.php (line 51)

at CryptKey->__construct('file:///var/dev/project/storage/oauth-public.key')
  in ResourceServer.php (line 50)

File permissions

```<code>-rw-r--r-- user:user oauth-private.key
-rw-r--r-- user:user oauth-public.key
</code>```

Update 1

I found out that oauth Libaray introduced a security fix. Oauth V5 Security Improvements

Version 5.1.4 is a backwards compatbile with other 5.1.x releases.

You will notice in your server logs a message like this:

You must set the encryption key going forward to improve the security of this library - see this page for more information https://oauth2.thephpleague.com/v5-security-improvements/

To supress this notice once you have instantiated an instance of \League\OAuth2\Server\AuthorizationServer you should call the setEncryptionKey() method passing in at least 32 bytes of random data.

You can generate this using base64_encode(random_bytes(32)). Alternatively if you’re using a framework such as Laravel which has a encryption key already generated you can pass in that (in the case of Laravel use env('APP_KEY')).

Problem is that the maintainer of Laravel Passport has to fix this.

Update 2

After I removed the vendor folder and executed composer install again I get still the same error.

答:
It would not be safe to change the owner of oauth-private.key to www-data:www-data. Only the oauth-public.key should be owned by www-data:www-data.

This should be sufficient:

```<code>sudo chown www-data:www-data oauth-public.key
sudo chmod 600 oauth-public.key
</code>```

Once done, check your permissions by running this in the storage folder:

```<code>ls -la
</code>```

Owner of oauth-private.key should NOT be www-data:www-data.

Owner of oauth-public.key should be www-data:www-data

Body:
After I updated the following packages I got an error that the oauth-public.key file couldn't be found.

Package operations: 1 install, 2 updates, 0 removals

Updating laravel/framework (v5.4.27 => v5.4.28): Downloading (100%)

    Installing defuse/php-encryption (v2.1.0): Downloading (100%)

    Updating league/oauth2-server (5.1.3 => 5.1.4): Downloading (100%)

Firstly I deleted the two oauth- files in project/storage and then executed this command: php artisan passport:install to generate new oauth- files.

Now I get the following error when trying to access an api route.

(1/1) ErrorException
  chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted

Stack trace

in CryptKey.php (line 51)

at HandleExceptions->handleError(2, 'chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted', '/var/dev/project/vendor/league/oauth2-server/src/CryptKey.php', 51, array('keyPath' => 'file:///var/dev/project/storage/oauth-public.key', 'passPhrase' => null, 'keyPathPerms' => '644'))

at chmod('file:///var/dev/project/storage/oauth-public.key', 384)
  in CryptKey.php (line 51)

at CryptKey->__construct('file:///var/dev/project/storage/oauth-public.key')
  in ResourceServer.php (line 50)

File permissions

-rw-r--r-- user:user oauth-private.key
-rw-r--r-- user:user oauth-public.key

Update 1

I found out that oauth Libaray introduced a security fix. Oauth V5 Security Improvements

Version 5.1.4 is a backwards compatbile with other 5.1.x releases.

You will notice in your server logs a message like this:

You must set the encryption key going forward to improve the security of this library - see this page for more information https://oauth2.thephpleague.com/v5-security-improvements/

To supress this notice once you have instantiated an instance of \League\OAuth2\Server\AuthorizationServer you should call the setEncryptionKey() method passing in at least 32 bytes of random data.

You can generate this using base64_encode(random_bytes(32)). Alternatively if you’re using a framework such as Laravel which has a encryption key already generated you can pass in that (in the case of Laravel use env('APP_KEY')).

Problem is that the maintainer of Laravel Passport has to fix this.

Update 2

After I removed the vendor folder and executed composer install again I get still the same error.

Body:
It would not be safe to change the owner of oauth-private.key to www-data:www-data. Only the oauth-public.key should be owned by www-data:www-data.

This should be sufficient:

sudo chown www-data:www-data oauth-public.key
sudo chmod 600 oauth-public.key

Once done, check your permissions by running this in the storage folder:

ls -la

Owner of oauth-private.key should NOT be www-data:www-data.

Owner of oauth-public.key should be www-data:www-data


问:
C# equivalent of C++ std::vector<int>.end()
I was trying to rewrite some C++ code I found on the internet in C# for my hexagon sphere project, but I ran into the following code:

```<code>if((((*ti)->m_hexA) != tileNdx) && (find(nbrs. begin(), nbrs.end(), ((*ti)->m_hexA)) == nbrs.end()))
{
    nbrs.push_back(((*ti)->m_hexA));
}
</code>```

I have it mostly converted to C#. I even built my own Find<T>(List<T> list, T value) method that achieves the same basic functionality as std::find.

I am still unsure about the docs for std::vector<T>::end() however. The docs say it returns an iterator pointing to a "place holder" slot at the end of the iterator, and that attempting to access it will result in "undefined behaviour". Does this:

1.) Mean that in my C#, when dealing with regular objects performing comparisons with an end() element, I should just compare the object to null?

2.) With integers and other primitives, should I just compare against a sentinel value such as -1?

In the above c++ source code, nbrs is a std::vector, m_hexA is an int, and ti is a struct.

答:
The whole construction:

```<code>(find(nbrs. begin(), nbrs.end(), ((*ti)->m_hexA)) == nbrs.end())
</code>```

could be written in C# using LinQ:

```<code>nbrs.FirstOrDefault(i => i == ti.m_hexA) == null
</code>```

or

```<code>!nbrs.Any(i => i == ti.m_hexA)
</code>```

where ((*ti)->m_hexA) is equivalent of ti.m_hexA.

Body:
I was trying to rewrite some C++ code I found on the internet in C# for my hexagon sphere project, but I ran into the following code:

if((((*ti)->m_hexA) != tileNdx) && (find(nbrs. begin(), nbrs.end(), ((*ti)->m_hexA)) == nbrs.end()))
{
    nbrs.push_back(((*ti)->m_hexA));
}

I have it mostly converted to C#. I even built my own Find<T>(List<T> list, T value) method that achieves the same basic functionality as std::find.

I am still unsure about the docs for std::vector<T>::end() however. The docs say it returns an iterator pointing to a "place holder" slot at the end of the iterator, and that attempting to access it will result in "undefined behaviour". Does this:

1.) Mean that in my C#, when dealing with regular objects performing comparisons with an end() element, I should just compare the object to null?

2.) With integers and other primitives, should I just compare against a sentinel value such as -1?

In the above c++ source code, nbrs is a std::vector, m_hexA is an int, and ti is a struct.

Body:
The whole construction:

(find(nbrs. begin(), nbrs.end(), ((*ti)->m_hexA)) == nbrs.end())

could be written in C# using LinQ:

nbrs.FirstOrDefault(i => i == ti.m_hexA) == null

or

!nbrs.Any(i => i == ti.m_hexA)

where ((*ti)->m_hexA) is equivalent of ti.m_hexA.


问:
Routing not working in reactjs application
I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.

following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';

ReactDOM.render((
     <Router history={hashHistory}>
        <div>
            <Route path="/" component={App}/>
            <Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>
        </div>
    </Router>

), document.getElementById('app'))
</code>```

答:
You need to configure the route to match the root path exactly. Try this...</p>

```<code><Route exact path="/" component={App}/>
</code>```

Body:
I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.

following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';

ReactDOM.render((
     <Router history={hashHistory}>

            <Route path="/" component={App}/>
            <Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>

    </Router>

), document.getElementById('app'))

Body:
You need to configure the route to match the root path exactly. Try this...

<Route exact path="/" component={App}/>


问:
react-native-router-flux: How can I retain parent navbar when switching tabs?
I currently have the following in my router:

```<code><Scene key="results" title="Query Results"
    tabs={true} tabBarStyle={style.tabBarStyle}>
    <Scene
      key="listResultsTab"
      title="List"
      icon={TabIcon}
    >
      <Scene key="listResults" component={ListResultsScene} title="Results List" />
    </Scene>

    <Scene
      key="mapResultsTab"
      title="Map"
      icon={TabIcon}
    >
      <Scene key="mapResults" component={MapResultsScene} title="Results Map" />
    </Scene>
</Scene>
</code>```

So far, it creates a tab bar with two tabs that alternate between the ListResults and MapResults components, which is what I want. However, the tabs each maintain their own navbar. This isn't necessarily an issue except that it overrides the parent navbar so I lose access to anything that came before query results.

My ideal setup would be something like:

```<code>launchScreen --> queryResults----->listResults -> ... ->
                   |
                   -->mapResults-> ... ->
</code>```

Is there any way to keep queryResults's navbar while switching between the tabs?

The docs say

Every tab has its own navigation bar. However, if you do not set its parent  with hideNavBar={true}, the tabs' navigation bar will be overrided by their parent.

However this does not seem to be the case. I am not using hideNavBar and the parent's navigation bar is still being overridden by the tab's. I thought perhaps I could use hideNavBar on the tab's, but that only just removes the navBar entirely.

Edit: Updating with more detailed information.

This is my full Scenes list.

```<code>import React from 'react';
import {StyleSheet, Text } from 'react-native';
import { Actions, Scene, ActionConst } from 'react-native-router-flux';
import LaunchScene from '../scenes/LaunchScene';
import LoginScene from '../scenes/LoginScene';
import WorkspaceSelectionScene from '../scenes/WorkspaceSelectionScene';
import QuerySelectionScene from '../scenes/QuerySelectionScene';
import EditQueryScene from '../scenes/EditQueryScene';
import ListResultsScene from '../scenes/ListResultsScene';
import MapResultsScene from '../scenes/MapResultsScene';

const style = StyleSheet.create({
        tabBarStyle: {
            borderTopWidth : .5,
            borderColor    : '#b7b7b7',
            backgroundColor: 'white',
            opacity: 1
        },
        padForNavBar: {
          paddingTop: 64
        }
});

const TabIcon = ({ selected, title }) => {
  return (
    <Text style={{color: selected ? 'red' :'black'}}>{title}</Text>
  );
}

const scenes = Actions.create(
  <Scene key="root">
    <Scene key="login" component={LoginScene} title="Login" sceneStyle={style.padForNavBar} />
    <Scene key="workspaceSelection" component={WorkspaceSelectionScene}
      title="Workspace Selection" sceneStyle={style.padForNavBar} />
    <Scene key="querySelection" component={QuerySelectionScene}
      title="Query Selection" sceneStyle={style.padForNavBar} />
    <Scene key="launch" component={LaunchScene} title="Launch" sceneStyle={style.padForNavBar} />
    <Scene key="editQuery" component={EditQueryScene} title="Edit Query" sceneStyle={style.padForNavBar} />
    <Scene key="results" title="Query Results"
        tabs={true} tabBarStyle={style.tabBarStyle}>
        <Scene
          key="listResultsTab"
          title="List"
          icon={TabIcon}
        >
          <Scene key="listResults" component={ListResultsScene} title="Results List" sceneStyle={style.padForNavBar} />
        </Scene>

        <Scene
          key="mapResultsTab"
          title="Map"
          icon={TabIcon}
        >
          <Scene key="mapResults" component={MapResultsScene} title="Results Map" sceneStyle={style.padForNavBar} />
        </Scene>
    </Scene>
  </Scene>
);

export default scenes
</code>```

This is what my tabs look like when I hit the listResults tab nested inside the results scene. Note that I can still return to the previous pages.

But when I switch tabs to the mapResults tab, still within the results scene, the navbar is reset. I no longer have access to the back button. Switching back to listResults will not restore it.

答: As an update, this turned out to be an issue with the library. An issue was opened and it was corrected in a subsequent commit.</p>

Body:
I currently have the following in my router:

<Scene key="results" title="Query Results"
    tabs={true} tabBarStyle={style.tabBarStyle}>
    <Scene
      key="listResultsTab"
      title="List"
      icon={TabIcon}
    >
      <Scene key="listResults" component={ListResultsScene} title="Results List" />
    </Scene>

    <Scene
      key="mapResultsTab"
      title="Map"
      icon={TabIcon}
    >
      <Scene key="mapResults" component={MapResultsScene} title="Results Map" />
    </Scene>
</Scene>

So far, it creates a tab bar with two tabs that alternate between the ListResults and MapResults components, which is what I want. However, the tabs each maintain their own navbar. This isn't necessarily an issue except that it overrides the parent navbar so I lose access to anything that came before query results.

My ideal setup would be something like:

launchScreen --> queryResults----->listResults -> ... ->
                   |
                   -->mapResults-> ... ->

Is there any way to keep queryResults's navbar while switching between the tabs?

The docs say

Every tab has its own navigation bar. However, if you do not set its parent  with hideNavBar={true}, the tabs' navigation bar will be overrided by their parent.

However this does not seem to be the case. I am not using hideNavBar and the parent's navigation bar is still being overridden by the tab's. I thought perhaps I could use hideNavBar on the tab's, but that only just removes the navBar entirely.

Edit: Updating with more detailed information.

This is my full Scenes list.

import React from 'react';
import {StyleSheet, Text } from 'react-native';
import { Actions, Scene, ActionConst } from 'react-native-router-flux';
import LaunchScene from '../scenes/LaunchScene';
import LoginScene from '../scenes/LoginScene';
import WorkspaceSelectionScene from '../scenes/WorkspaceSelectionScene';
import QuerySelectionScene from '../scenes/QuerySelectionScene';
import EditQueryScene from '../scenes/EditQueryScene';
import ListResultsScene from '../scenes/ListResultsScene';
import MapResultsScene from '../scenes/MapResultsScene';

const style = StyleSheet.create({
        tabBarStyle: {
            borderTopWidth : .5,
            borderColor    : '#b7b7b7',
            backgroundColor: 'white',
            opacity: 1
        },
        padForNavBar: {
          paddingTop: 64
        }
});

const TabIcon = ({ selected, title }) => {
  return (
    <Text style={{color: selected ? 'red' :'black'}}>{title}</Text>
  );
}

const scenes = Actions.create(
  <Scene key="root">
    <Scene key="login" component={LoginScene} title="Login" sceneStyle={style.padForNavBar} />
    <Scene key="workspaceSelection" component={WorkspaceSelectionScene}
      title="Workspace Selection" sceneStyle={style.padForNavBar} />
    <Scene key="querySelection" component={QuerySelectionScene}
      title="Query Selection" sceneStyle={style.padForNavBar} />
    <Scene key="launch" component={LaunchScene} title="Launch" sceneStyle={style.padForNavBar} />
    <Scene key="editQuery" component={EditQueryScene} title="Edit Query" sceneStyle={style.padForNavBar} />
    <Scene key="results" title="Query Results"
        tabs={true} tabBarStyle={style.tabBarStyle}>
        <Scene
          key="listResultsTab"
          title="List"
          icon={TabIcon}
        >
          <Scene key="listResults" component={ListResultsScene} title="Results List" sceneStyle={style.padForNavBar} />
        </Scene>

        <Scene
          key="mapResultsTab"
          title="Map"
          icon={TabIcon}
        >
          <Scene key="mapResults" component={MapResultsScene} title="Results Map" sceneStyle={style.padForNavBar} />
        </Scene>
    </Scene>
  </Scene>
);

export default scenes

This is what my tabs look like when I hit the listResults tab nested inside the results scene. Note that I can still return to the previous pages.

But when I switch tabs to the mapResults tab, still within the results scene, the navbar is reset. I no longer have access to the back button. Switching back to listResults will not restore it.


问:
Xcode: Error Domain=DVTPlaygroundCommunicationErrorDomain Code=1
I'm attempting to test the cancellation of a DispatchWork item within a Swift Playground, although during the first few milliseconds of execution there's an error, which I'm not sure what it's actually indicating, nor can I tell if the error is causing the cancellation rather than the cancel() method...

```<code>func testDispatchWorkItems() {
    let queue = DispatchQueue.global(qos: .userInitiated)
    var item: DispatchWorkItem?

    // create work item

    item = DispatchWorkItem {
        for i in 0 ... 100000 {
            if item!.isCancelled { break }
            print(i)
        }
    }

    // start it

    queue.async(execute: item!)

    // after three seconds, stop it

    queue.asyncAfter(deadline: .now() + 3) {
        item?.cancel()
    }
}

testDispatchWorkItems()
</code>```

```<code> 2016-10-26 11:14:33.898
 com.apple.dt.Xcode.PlaygroundStub-macosx[30685:18567692] Error
 encountered communicating with Xcode: Error
 Domain=DVTPlaygroundCommunicationErrorDomain Code=1 "Cannot send data
 because stream is closed." UserInfo={NSLocalizedDescription=Cannot
 send data because stream is closed.}
</code>```

Has someone got an idea what that error is indicating?

答:
Set needsIndefiniteExecution to true can omit this warning. The warning happens once playground execution ends earlier than thread processing.

```<code>import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

Body:
I'm attempting to test the cancellation of a DispatchWork item within a Swift Playground, although during the first few milliseconds of execution there's an error, which I'm not sure what it's actually indicating, nor can I tell if the error is causing the cancellation rather than the cancel() method...

func testDispatchWorkItems() {
    let queue = DispatchQueue.global(qos: .userInitiated)
    var item: DispatchWorkItem?

    // create work item

    item = DispatchWorkItem {
        for i in 0 ... 100000 {
            if item!.isCancelled { break }
            print(i)
        }
    }

    // start it

    queue.async(execute: item!)

    // after three seconds, stop it

    queue.asyncAfter(deadline: .now() + 3) {
        item?.cancel()
    }
}

testDispatchWorkItems()

 2016-10-26 11:14:33.898
 com.apple.dt.Xcode.PlaygroundStub-macosx[30685:18567692] Error
 encountered communicating with Xcode: Error
 Domain=DVTPlaygroundCommunicationErrorDomain Code=1 "Cannot send data
 because stream is closed." UserInfo={NSLocalizedDescription=Cannot
 send data because stream is closed.}

Has someone got an idea what that error is indicating?

Body:
Set needsIndefiniteExecution to true can omit this warning. The warning happens once playground execution ends earlier than thread processing.

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true


问:
IBM Watson Conversation: Keep relative scoring after workspace upgrade?
I'm using conversation version 2016-09-20 and I'm happy with the dialog results. Now I want to upgrade to version 2017-04-21 for some new features. In that process I need to upgrade the conversation workspace.

Is it possible for me to turn off absolute scoring but keep relative scoring?

答:
My understanding is that it is not possible to keep "old behavior" after upgrading a workspace. In your case, the scoring would change from relative to absolute scoring. This will impact how and which intents are going to be returned.

There are some general guidelines on upgrading workspaces. The changes to the scoring and the impact on a workspace are discussed in the feature overview. It will require changes to your dialog and hence some testing.


问:
How to append a newline to StringBuilder
I have a StringBuilder object,

```<code>StringBuilder result = new StringBuilder();
result.append(someChar);
</code>```

Now I want to append a newline character to the StringBuilder. How can I do it?

```<code>result.append("/n");
</code>```

Does not work. So, I was thinking about writing a newline using Unicode. Will this help? If so, how can I add one?

答:
I create original class that similar to StringBuidler and can append line by calling method appendLine(String str).

```<code>public class StringBuilderPlus {

    private StringBuilder sb;

    public StringBuilderPlus(){
         sb = new StringBuilder();
    }

    public void append(String str)
    {
        sb.append(str != null ? str : "");
    }

    public void appendLine(String str)
    {
        sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
    }

    public String toString()
    {
        return sb.toString();
    }
}
</code>```

Usage:

```<code>StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());
</code>```

Console:

```<code>aaaaa
bbbbb
</code>```

Body:
I have a StringBuilder object,

StringBuilder result = new StringBuilder();
result.append(someChar);

Now I want to append a newline character to the StringBuilder. How can I do it?

result.append("/n");

Does not work. So, I was thinking about writing a newline using Unicode. Will this help? If so, how can I add one?

Body:
I create original class that similar to StringBuidler and can append line by calling method appendLine(String str).

public class StringBuilderPlus {

    private StringBuilder sb;

    public StringBuilderPlus(){
         sb = new StringBuilder();
    }

    public void append(String str)
    {
        sb.append(str != null ? str : "");
    }

    public void appendLine(String str)
    {
        sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
    }

    public String toString()
    {
        return sb.toString();
    }
}

Usage:

StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());

Console:

aaaaa
bbbbb


问:
How to edit the variables of a php file with another php file
Ok so I want to do something similar to how Simple Machine Forum edits some variable within the Admin panel on the forum. For instance
I have a settings.php file. I want tool.php to open and find all declared php variables in the settings.php like $background_color='Orange' and output in tools.php Background Color: Orange inside of a form tag that, once changed to 'Purple' and submitted, replaces 'Orange' with 'Purple' and now if i open 'settings.php' the variable inside the file is now "$background_color='Purple'" without having to go in an manually edit it. I can just submit the new data for the variable and replace the old.

答:
To load the variables in tool.php, simply include("settings.php").

In order to change settings, you will need to modify settings.php.

The easiest way to do this should be by regex-replacing the old value with the new one, e.g. ["\$background_color *= *'\d*'"] and replace that with ["\$background_color = 'Purple'"].

Just overwrite the file with the new string.

I'm not sure I escaped everything correctly, but this way you should be able to replace the whole file.

See http://php.net/manual/en/function.preg-replace.php

The drawback is, that if the settings file is very large, it may take some time to do that, although that will probably not be a problem for your use case.

alternatively, you could read the file line by line and replace that (either manually or by using regex-replacing again.


问:
Why does the Ajax not updating the model correctly?
I am new to angularjs and is using code sample in book "pro-angularjs" to do some test run (it has an initial list of items, but then use Ajax to update list):

```<code><!DOCTYPE html>
<html ng-app="todoApp">
    <head>
        <title>TO DO List</title>
        <link href="bootstrap.css" rel="stylesheet" />
        <link href="bootstrap-theme.css" rel="stylesheet" />
        <script src="angular.js"></script>
        <script>
            var model = {
                user: "Adam",
                items: [{ action: "Buy Flowers", done: false },
                        { action: "Get Shoes", done: false },
                        { action: "Collect Tickets", done: true },
                        { action: "Call Joe", done: false }],
            };
            var todoApp = angular.module("todoApp", []);

            todoApp.run(function ($http) {
                $http.get("todo.json").then(function successCallback(data) {
                    model.items = data;
                });
            });

            todoApp.filter("checkedItems", function () {
                return function (items, showComplete) {
                    var resultArr = [];
                    angular.forEach(items, function (item) {
                        if (item.done == false || showComplete == true) {
                            resultArr.push(item);
                        }
                    });
                    return resultArr;
                }
            });

            todoApp.controller("ToDoCtrl", function ($scope) {
                $scope.todo = model;
                $scope.incompleteCount = function () {
                    var count = 0;
                    angular.forEach($scope.todo.items, function (item) {
                        if (!item.done) { count++ }
                    });
                    return count;
                }
                $scope.warningLevel = function () {
                    return $scope.incompleteCount() < 3 ? "label-success" : "label-warning";
                }
                $scope.addNewItem = function (actionText) {
                    $scope.todo.items.push({ action: actionText, done: false });
                }
            });
        </script>
    </head>
    <body ng-controller="ToDoCtrl">
        <div class="page-header">
            <h1>
                {{todo.user}}'s To Do List
                <span class="label label-default" ng-class="warningLevel()"
                      ng-hide="incompleteCount() == 0">
                    {{incompleteCount()}}
                </span>
            </h1>
        </div>
        <div class="panel">
            <div class="input-group">
                <input class="form-control" ng-model="actionText" />
                <span class="input-group-btn">
                    <button class="btn btn-default"
                            ng-click="addNewItem(actionText)">Add</button>
                </span>
            </div>
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Done</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat=
                        "item in todo.items | checkedItems:showComplete | orderBy:'action'">
                        <td>{{item.action}}</td>
                        <td><input type="checkbox" ng-model="item.done" /></td>
                    </tr>
                </tbody>
            </table>

            <div class="checkbox-inline">
                <label><input type="checkbox" ng_model="showComplete"> Show Complete</label>
            </div>
        </div>
    </body>
</html>
</code>```

the only change i made was:

```<code>        todoApp.run(function ($http) {
            $http.get("todo.json").then(function successCallback(data) {
                model.items = data;
            });
        });
</code>```

it was initially:

```<code>$http.get("todo.json").success(function (data) {
model.items = data;
});
</code>```

which does not run with the latetest version angularjs, and so i made the change.

when debugging, i found that the initial value of model.items is:

and it is correctly showing in UI (see left side of screenshot).

After the ajax, its value is updated to 'data' whose value is:

the value of data looks fine to me (same as initial value of items).

But after i let go the debugger, finally in UI all items are gone.

I do understand why? it seems 'items' is the same as 'data'. Anyone has a clue on how i can debug further to find out the root cause?

Thanks,

btw, the 'todo.json' i used is below:

```<code>[{ "action": "Buy Flowers", "done": false },
{ "action": "Get Shoes", "done": false },
{ "action": "Collect Tickets", "done": true },
{ "action": "Call Joe", "done": false }]
</code>```

答:
You are not updating your model correctly. As you can see from your screenshot, data contains an object data which should be assigned to your model.</p>

```<code>todoApp.run(function ($http) {
    $http.get("todo.json").then(function successCallback(data) {
        model.items = data.data;
    });
});
</code>```

Body:
I am new to angularjs and is using code sample in book "pro-angularjs" to do some test run (it has an initial list of items, but then use Ajax to update list):

<!DOCTYPE html>

        <title>TO DO List</title>
        <link href="bootstrap.css" rel="stylesheet" />
        <link href="bootstrap-theme.css" rel="stylesheet" />

                {{todo.user}}'s To Do List

                    {{incompleteCount()}}

                <input class="form-control" ng-model="actionText" />

                    <button class="btn btn-default"
                            ng-click="addNewItem(actionText)">Add</button>

                        Description
                        Done

                        {{item.action}}
                        <input type="checkbox" ng-model="item.done" />

                <input type="checkbox" ng_model="showComplete"> Show Complete

the only change i made was:

        todoApp.run(function ($http) {
            $http.get("todo.json").then(function successCallback(data) {
                model.items = data;
            });
        });

it was initially:

$http.get("todo.json").success(function (data) {
model.items = data;
});

which does not run with the latetest version angularjs, and so i made the change.

when debugging, i found that the initial value of model.items is:

and it is correctly showing in UI (see left side of screenshot).

After the ajax, its value is updated to 'data' whose value is:

the value of data looks fine to me (same as initial value of items).

But after i let go the debugger, finally in UI all items are gone.

I do understand why? it seems 'items' is the same as 'data'. Anyone has a clue on how i can debug further to find out the root cause?

Thanks,

btw, the 'todo.json' i used is below:

[{ "action": "Buy Flowers", "done": false },
{ "action": "Get Shoes", "done": false },
{ "action": "Collect Tickets", "done": true },
{ "action": "Call Joe", "done": false }]

Body:
You are not updating your model correctly. As you can see from your screenshot, data contains an object data which should be assigned to your model.

todoApp.run(function ($http) {
    $http.get("todo.json").then(function successCallback(data) {
        model.items = data.data;
    });
});


问:
How to Update Firebase Database where certain Email exists in Android?
I have searched the docs and stack overflow questions but am unable to find the answer I am looking for.

I have registered users in the database and I want to update the child where the same email exists(If a user chooses to change their details aka name and number then the details should be updated where the email is "user_email").

If the same email doesn't exist then it should create a new user. But my problem is that it only updates the most recent userid and doesn't search the entire database for the email.

Firebase Database Structure

Here is the RegisterActivity where the UpdateUser() is called and the CreateNewUser() is called:

```<code>          final String newnum = mob.getText().toString().trim();
            final String n = Name.getText().toString().trim();
            final String p = pass.getText().toString().trim();
            if (Name.getText().toString().equals("") ||
              pass.getText().toString().equals("") ||
       email.getText().toString().equals("") ||
                  mob.getText().toString().equals("")) {
                Toast.makeText(getApplicationContext(), "Please fill in all
            the fields!", Toast.LENGTH_SHORT).show();
            } else if (mob.getText().toString().length() < 10 || mob.getText().toString().length() > 10) {
                mob.setError("Invalid Phone Number");
           }
     else {
                mAuth.createUserWithEmailAndPassword(e, p)
              .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
               @Override
              public void onComplete(@NonNull Task<AuthResult> task) {
               final String u_id = userc.getUsername();
              if (!task.isSuccessful()) {
     DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
         ref.child("users").child(u_id).child("Email").
            addListenerForSingleValueEvent(new ValueEventListener() {
                   @Override
                   public void onDataChange(DataSnapshot dataSnapshot) {
                          if (dataSnapshot.exists()) {
        Toast.makeText
      (getApplicationContext(), "Username already exists. Please try again!
          Or change your details if you wish", Toast.LENGTH_SHORT).show();
                             userc.updateUser(u_id, n, e, newnum);
                                                finish();
         }
     }
     @Override public void onCancelled(DatabaseError databaseError)
       {
       }
       });
       }
           final String userid = mAuth.getCurrentUser().getUid();
         SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putString("email", e);
                                 editor.putString("phoneno", newnum);
                                 editor.putString("Name",n);
                                editor.putString ("Password", p);
                                editor.commit();
                                userc.writeNewUser(userid, n, e, newnum);
                                finish();
                            }
                        });
                          }
</code>```

User Activity where the methods exist:

```<code>    public class User{

        private DatabaseReference database =
        FirebaseDatabase.getInstance().getReference();
      public static String FB_REFERENCE_USER = "user";
      public String username;
      public String email;
     public String pno;
     public String n;
      String uid;

    public User() {

        }

//public String getUsername() {return username;}
     public String getPno() {
       return pno;
         }
        public String getN() {return n;}
       public String getUsername() {return username;}

     public String getEmail() {
      return email;
         }

public User( String username, String n,  String email, String pno) {
  this.username = username;
    this.email = email;
    this.pno=pno;
   this.n=n;
}

public void writeNewUser( String uid, String name, String email, String pno)
       {
   //
   database.child("users").child(uid).child("Username").setValue(username);
    database.child("users").child(uid).child("Email").setValue(email);
    //database.child("users").child(uid).child("PhoneNumber").setValue(pno);
   database.child("users").child(uid).child("Name").setValue(name);
    database.child("users").child(uid).child("Phone Number").setValue(pno);
}

public void updateUser(String uid, String name, String email, String pno) {
    // Write a message to the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference(FB_REFERENCE_USER);
    User u = new User(uid, name, email,pno);
    Map<String, Object> postValues = u.toMap();

    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put(uid, postValues);

    myRef.updateChildren(childUpdates);

}

private Map<String,Object> toMap() {
    HashMap<String, Object> result = new HashMap<>();
 //   result.put("Username", username);
    result.put("Name", n);
    result.put("Email", email);
    result.put("Phone Number", pno);

    return result;
       }
       }
</code>```

答:
Try this way,this is exactly what you looking for

```<code>private void updateUser(String name, String email) {
        // updating the user via child nodes
        if (!TextUtils.isEmpty(name))
            mFirebaseDatabase.child(userId).child("name").setValue(name);

        if (!TextUtils.isEmpty(email))
            mFirebaseDatabase.child(userId).child("email").setValue(email);
    }
</code>```

http://www.androidhive.info/2016/10/android-working-with-firebase-realtime-database/

Body:
I have searched the docs and stack overflow questions but am unable to find the answer I am looking for.

I have registered users in the database and I want to update the child where the same email exists(If a user chooses to change their details aka name and number then the details should be updated where the email is "user_email").

If the same email doesn't exist then it should create a new user. But my problem is that it only updates the most recent userid and doesn't search the entire database for the email.

Firebase Database Structure

Here is the RegisterActivity where the UpdateUser() is called and the CreateNewUser() is called:

          final String newnum = mob.getText().toString().trim();
            final String n = Name.getText().toString().trim();
            final String p = pass.getText().toString().trim();
            if (Name.getText().toString().equals("") ||
              pass.getText().toString().equals("") ||
       email.getText().toString().equals("") ||
                  mob.getText().toString().equals("")) {
                Toast.makeText(getApplicationContext(), "Please fill in all
            the fields!", Toast.LENGTH_SHORT).show();
            } else if (mob.getText().toString().length() < 10 || mob.getText().toString().length() > 10) {
                mob.setError("Invalid Phone Number");
           }
     else {
                mAuth.createUserWithEmailAndPassword(e, p)
              .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
               @Override
              public void onComplete(@NonNull Task<AuthResult> task) {
               final String u_id = userc.getUsername();
              if (!task.isSuccessful()) {
     DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
         ref.child("users").child(u_id).child("Email").
            addListenerForSingleValueEvent(new ValueEventListener() {
                   @Override
                   public void onDataChange(DataSnapshot dataSnapshot) {
                          if (dataSnapshot.exists()) {
        Toast.makeText
      (getApplicationContext(), "Username already exists. Please try again!
          Or change your details if you wish", Toast.LENGTH_SHORT).show();
                             userc.updateUser(u_id, n, e, newnum);
                                                finish();
         }
     }
     @Override public void onCancelled(DatabaseError databaseError)
       {
       }
       });
       }
           final String userid = mAuth.getCurrentUser().getUid();
         SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putString("email", e);
                                 editor.putString("phoneno", newnum);
                                 editor.putString("Name",n);
                                editor.putString ("Password", p);
                                editor.commit();
                                userc.writeNewUser(userid, n, e, newnum);
                                finish();
                            }
                        });
                          }

User Activity where the methods exist:

    public class User{

        private DatabaseReference database =
        FirebaseDatabase.getInstance().getReference();
      public static String FB_REFERENCE_USER = "user";
      public String username;
      public String email;
     public String pno;
     public String n;
      String uid;

    public User() {

        }

//public String getUsername() {return username;}
     public String getPno() {
       return pno;
         }
        public String getN() {return n;}
       public String getUsername() {return username;}

     public String getEmail() {
      return email;
         }

public User( String username, String n,  String email, String pno) {
  this.username = username;
    this.email = email;
    this.pno=pno;
   this.n=n;
}

public void writeNewUser( String uid, String name, String email, String pno)
       {
   //
   database.child("users").child(uid).child("Username").setValue(username);
    database.child("users").child(uid).child("Email").setValue(email);
    //database.child("users").child(uid).child("PhoneNumber").setValue(pno);
   database.child("users").child(uid).child("Name").setValue(name);
    database.child("users").child(uid).child("Phone Number").setValue(pno);
}

public void updateUser(String uid, String name, String email, String pno) {
    // Write a message to the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference(FB_REFERENCE_USER);
    User u = new User(uid, name, email,pno);
    Map<String, Object> postValues = u.toMap();

    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put(uid, postValues);

    myRef.updateChildren(childUpdates);

}

private Map<String,Object> toMap() {
    HashMap<String, Object> result = new HashMap<>();
 //   result.put("Username", username);
    result.put("Name", n);
    result.put("Email", email);
    result.put("Phone Number", pno);

    return result;
       }
       }

Body:
Try this way,this is exactly what you looking for

private void updateUser(String name, String email) {
        // updating the user via child nodes
        if (!TextUtils.isEmpty(name))
            mFirebaseDatabase.child(userId).child("name").setValue(name);

        if (!TextUtils.isEmpty(email))
            mFirebaseDatabase.child(userId).child("email").setValue(email);
    }

http://www.androidhive.info/2016/10/android-working-with-firebase-realtime-database/


问:
Public Properties instead of PRIVATE fields
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".

My question is why should I write something like this (Public Properties)

```<code>class myClass{

public int AValue{get; set;}
}
</code>```

when I can write instead (Private fields  without any properties involved) (Just classic old C++ style way of writing things)

```<code>class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}
</code>```

I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).

I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)

答:
The main reason for using public int AValue { get; set; } instead of a private field and a getAValue and setAValue pair of functions is that that's just the way that things are done in C#. From a "what the code does at runtime" perspective, the two are pretty much the same as an "auto property" (the type of property you've got where you let the compiler take care of generating a private backing field) compiles down into code very similar to that which you've written (see this stackoverflow questions accepted answer for an example).

The main "advantage" in the context of your question (why use a property instead of a field and a get/set pair of methods) is predictability and comprehensibility. Anyone who's working with your code will expect to see properties, rather than a private field/get/set implementation and thus your code will be more immediately comprehensible to them. Seeing it implemented differently will cause them to question why, assume that there's a reason for it and thus slow them down when it comes to understanding your code.

Body:
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".

My question is why should I write something like this (Public Properties)

class myClass{

public int AValue{get; set;}
}

when I can write instead (Private fields  without any properties involved) (Just classic old C++ style way of writing things)

class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}

I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).

I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)


问:
Learning C# prior to learning ASP.NET MVC?
With only mild programming experience in the past, I was wondering about C# and ASP.NET MVC..

Do you guys think it's a better idea to learn C# before learning ASP.NET MVC?  I've already delved a little into both of these already, but I still need some help deciding.

I think I would be a much stronger MVC user if I had more knowledge of the C# language itself.

What do you guys think?

Thanks!

答: I agree with your third paragraph with C# at your back you'll be a stronger ASP.NET MVC developer; but I also think that they (C# and ASP.NET MVC) make great co-learning tools. And if you're going to try to pick up both tools, doing it together makes a lot of sense.</p>

ContentLicense: CC BY-SA 2.5


问:
Unable to add python to PATH
I am very new to python, but it seems like I should be able to activate the python environment by simply typing python. Unfortunately, I keep getting the error "'python' is not recognized as an internal or external command,
operable program or batch file." I can access python through it's path at C:\Python27\python, which works fine, but I can't seem to get the shortcut to work.

Details: I manually installed Python 2.7, and I run Windows 10. I have tried going to the Advanced System Settings to add the PATH manually, but with no result. None of the tutorials or help articles have suggestions for what to do if adding it manually fails. Is there any way I can fix this? It seems like a small thing, but it's really bugging me.

答:
Your path is bugged:

C:\Program Files\Git\cmd;"C:\Windows;C:\Windows\System32;C:\Python27";C:\Python27\Scripts

should not have those random " characters.

Title: Unable to add python to PATH


问:
Error in build for Xamarin Android when adding Google Map
I have an android xamarin project, and I only add Xamarin.GooglePlayServices.Maps nuget.

my build has this error :

error: package com.google.android.gms.maps does not exist
        com.google.android.gms.maps.OnMapReadyCallback

答:
Please try this :

From the Tools menu, select Open AVD Manager

From the Tools menu of the Android Virtual Device Manager app, select
Manage SDK..

For each of the Android SDK you are targeting, check the "Google
APIs" checkbox and install the packages.

You should now have the Google Maps SDK installed.


问:
is it possible/good to have two helper class for one controller and view in rails?
i have too many functions that needs to be used in my view, and my helper class is looking too long. so is it possible/good to have two helper class for a single controller and view?

if so how to define the second helper class?

答:
try this.

```<code>rails new example_app
cd example_app/
rails g scaffold Page title:string
rake db:migrate
rails s -p 3001
</code>```

now create 2 helpers:

```<code>touch ./app/helpers/a_helper.rb
touch ./app/helpers/b_helper.rb
</code>```

now put the following modules in their respective file.

```<code>module AHelper
  def same_method_name
    "Hi from AHelper"
  end
end

module BHelper
  def same_method_name
    "Hi from BHelper"
  end
end
</code>```

now inside ./app/views/pages/index.html.erb put this helper method somewhere.

```<code><%= same_method_name %>
</code>```

and visit localhost:3001/pages

You will see Hi from BHelper rendered in the page.

All helper modules, are included in your views and will override each other depending on the order they get included.

Now try this:

```<code>module BHelper
  def same_method_name
    "Hi from BHelper #{super}"
  end
end
</code>```

super will keep going up the inheritance chain, to the next method called same_method_name and that method is AHelper's #same_method_name so you will get "Hi from BHelper Hi from AHelper"

Rails helpers are good if want a quick and simple solution but if need more encapsulation consider using the decorator pattern (using a gem like Draper for example).

Body:
try this.

rails new example_app
cd example_app/
rails g scaffold Page title:string
rake db:migrate
rails s -p 3001

now create 2 helpers:

touch ./app/helpers/a_helper.rb
touch ./app/helpers/b_helper.rb

now put the following modules in their respective file.

module AHelper
  def same_method_name
    "Hi from AHelper"
  end
end

module BHelper
  def same_method_name
    "Hi from BHelper"
  end
end

now inside ./app/views/pages/index.html.erb put this helper method somewhere.

<%= same_method_name %>

and visit localhost:3001/pages

You will see Hi from BHelper rendered in the page.

All helper modules, are included in your views and will override each other depending on the order they get included.

Now try this:

module BHelper
  def same_method_name
    "Hi from BHelper #{super}"
  end
end

super will keep going up the inheritance chain, to the next method called same_method_name and that method is AHelper's #same_method_name so you will get "Hi from BHelper Hi from AHelper"

Rails helpers are good if want a quick and simple solution but if need more encapsulation consider using the decorator pattern (using a gem like Draper for example).


问:
Combine results from two tables into one recordset
I have two tables items and content.

```<code> items:|ID|menu|img
</code>```

table

```<code> itemcontent |ID|parent|title|content
</code>```

content holds is paired to items by parent holding the title and content

i want to search all the items and also print out those records wich do not have a title present in the itemcontent table
whereby the titles will be printed as "Empty".
so printing out the output would look something like:

```
title: test1 and ID: items.ID=1
title: Empty and ID: items.ID=2
title: Empty and ID: items.ID=3
title: test2 and ID: items.ID=4
title: Empty and ID: items.ID=5
etc...
```

I tried the following and then some but to no avail:

```<code>SELECT items.*, itemcontent.title, itemcontent.content
FROM items, itemcontent
WHERE itemcontent.title LIKE '%$search%'
     AND itemcontent.parent = items.ID
order by title ASC
</code>```

A little help would be much appreciated

答:
Since you want all the rows from items whether or not they have a match in itemcontent, plus a field from itemcontent when there is a match you need to use an OUTER JOIN:

```<code>SELECT items.*, COALESCE(itemcontent.title, 'empty'), itemcontent.content
FROM items LEFT OUTER JOIN itemcontent ON itemcontent.parent = items.ID
 WHERE (itemcontent.title LIKE '%$search%' OR itemcontent.title IS NULL)
 ORDER BY items.ID, itemcontent.title ASC
</code>```

There are small differences among SQL dialects (for instance, not all versions have COALESCE) so if you want a more precise answer indicate which product you're using.

Body:
I have two tables items and content.

 items:|ID|menu|img

table

 itemcontent |ID|parent|title|content

content holds is paired to items by parent holding the title and content

i want to search all the items and also print out those records wich do not have a title present in the itemcontent table
whereby the titles will be printed as "Empty".
so printing out the output would look something like:

title: test1 and ID: items.ID=1
title: Empty and ID: items.ID=2
title: Empty and ID: items.ID=3
title: test2 and ID: items.ID=4
title: Empty and ID: items.ID=5
etc...

I tried the following and then some but to no avail:

SELECT items.*, itemcontent.title, itemcontent.content
FROM items, itemcontent
WHERE itemcontent.title LIKE '%$search%'
     AND itemcontent.parent = items.ID
order by title ASC

A little help would be much appreciated

Body:
Since you want all the rows from items whether or not they have a match in itemcontent, plus a field from itemcontent when there is a match you need to use an OUTER JOIN:

SELECT items.*, COALESCE(itemcontent.title, 'empty'), itemcontent.content
FROM items LEFT OUTER JOIN itemcontent ON itemcontent.parent = items.ID
 WHERE (itemcontent.title LIKE '%$search%' OR itemcontent.title IS NULL)
 ORDER BY items.ID, itemcontent.title ASC

There are small differences among SQL dialects (for instance, not all versions have COALESCE) so if you want a more precise answer indicate which product you're using.


问:
when i use setOnPageChangeListener it will show error like image
When I use setOnPageChangeListener it will show an error like below:

How can I solve this error?

Please help me!

I am using fragment.

答:
ViewPager.setOnPageChangeListener is deprecated now. Need to use ViewPager.addOnPageChangeListener instead.

```<code>ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
</code>```

Source Link

Body:
ViewPager.setOnPageChangeListener is deprecated now. Need to use ViewPager.addOnPageChangeListener instead.

ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

Source Link


问:
how to remove underline from link label in compact framework (windows ce)
How can I remove underline from the link label in compact framework? As there is no click event for label and textbox I have to use linklabel as its support click event.

Tried this solution but its not working showing error Error : Operator '!' cannot be applied to operand of type 'System.Drawing.FontStyle'

Any clue how to remove underline and change font color?

答:
One easy way would be to inherit a user control from LinkLabel and override OnPaint. Therein use GDI+ to render the content of your LinkLabel. You'll still have all other functionality of the LinkLabel, except that the text won't have an underline, as you wish.

Something on the following lines:

```<code>class CustomLinkLabel : LinkLabel
{
  protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
  {
    //MyBase.OnPaint(e)

    using (SolidBrush B = new SolidBrush(this.ForeColor))
    {
      e.Graphics.DrawString(this.Text, this.Font, B, e.ClipRectangle.X, e.ClipRectangle.Y);
    }
  }
}
</code>```

Body:
One easy way would be to inherit a user control from LinkLabel and override OnPaint. Therein use GDI+ to render the content of your LinkLabel. You'll still have all other functionality of the LinkLabel, except that the text won't have an underline, as you wish.

Something on the following lines:

class CustomLinkLabel : LinkLabel
{
  protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
  {
    //MyBase.OnPaint(e)

    using (SolidBrush B = new SolidBrush(this.ForeColor))
    {
      e.Graphics.DrawString(this.Text, this.Font, B, e.ClipRectangle.X, e.ClipRectangle.Y);
    }
  }
}


问:
Can you apply visible binding based on the data currently being bound?
I'm trying to set some content in a template to be visible only if the item being rendered is the "current item".

Here is the code so far, I want to be able to only render a part of the inner template if the data item being rendered has ID == window.viewModel.activeObject.

```

How would I go about doing that?

答:
You'll want to use {if}{/if}

```<code><script type="text/html" id="objectTemplate">
    <article>
        <h3>${Name}</h3>
        {if $item.data.id === viewModel.activeObject()}
        {{html Text}}
        {/if}
    </article>
</script>
</code>```

Body:
I'm trying to set some content in a template to be visible only if the item being rendered is the "current item".

Here is the code so far, I want to be able to only render a part of the inner template if the data item being rendered has ID == window.viewModel.activeObject.

How would I go about doing that?

Body:
You'll want to use {if}{/if}

<script type="text/html" id="objectTemplate">
    <article>
        <h3>${Name}</h3>
        {if $item.data.id === viewModel.activeObject()}
        {{html Text}}
        {/if}
    </article>
</script>


问:
Visual Studio 2015 RTM - Debugging not working
I have installed VS 2015 RTM (nothing else) and I'm unable to debug any solution, not matter if it's an existing one or a brand new one (created with VS 2015 and compiled against .Net Framework 4.6), it only opens a new tab in VS which is called Break Mode with the following text:
The application is in break mode
Your app has entered a break state, but no code is executing that is supported by the selected debug  engine  (for e.g. only native runtime code is executing).
And if I check the Debug --> Module Window:
VS2015Test.vshost.exe no symbols loaded (even if I click load symbol it does not work)
VS2015Test.exe symbols loaded

And it also doesn't show the output on the console(it's a console application that just has the following lines of code:

```<code>class Program
{
        static void Main(string[] args)
        {
            Console.WriteLine("TEST");
            Console.ReadKey();
        }
    }
</code>```

I tried to reinstall VS 2015, restarted the computer, deleted all files in %temp%/AppData/Microsoft/Visual Studio/14, started VS in Admin Mode but nothing seems to work.

One thing which makes debugging working is this option:
Tools --> Options --> Debugging --> Use Managed Compability Mode

^^But that can't be the solution to use an old/legacy mode.

BTW: Debugging in VS 2013 is working fine.

Any help would be appreciated.

答: After installtion of vs 2017,while debugging the solution,there was an error like "Webkit has stopped functioning correctly; Visual Studio will not be able to debug your app any further.",this makes unable to proceed the debugging.To resolve this issue,Go to Tools->Options->Debugging->General then disable the javascript debugging for asp.net

Body:
I have installed VS 2015 RTM (nothing else) and I'm unable to debug any solution, not matter if it's an existing one or a brand new one (created with VS 2015 and compiled against .Net Framework 4.6), it only opens a new tab in VS which is called Break Mode with the following text:
The application is in break mode
Your app has entered a break state, but no code is executing that is supported by the selected debug  engine  (for e.g. only native runtime code is executing).
And if I check the Debug --> Module Window:
VS2015Test.vshost.exe no symbols loaded (even if I click load symbol it does not work)
VS2015Test.exe symbols loaded

And it also doesn't show the output on the console(it's a console application that just has the following lines of code:

class Program
{
        static void Main(string[] args)
        {
            Console.WriteLine("TEST");
            Console.ReadKey();
        }
    }

I tried to reinstall VS 2015, restarted the computer, deleted all files in %temp%/AppData/Microsoft/Visual Studio/14, started VS in Admin Mode but nothing seems to work.

One thing which makes debugging working is this option:
Tools --> Options --> Debugging --> Use Managed Compability Mode

^^But that can't be the solution to use an old/legacy mode.

BTW: Debugging in VS 2013 is working fine.

Any help would be appreciated.


问:
Elixir how to iterate over two lists at once to produce a new list?
I'd like to iterate over two lists at once, but can't figure out how. The for loop, which allows you to have multiple lists acts as nested for loops and I'm not that familiar with Enum, but perhaps there's a solution there.

Python has zip(list_1,list_2) and enumerate(list_1) to accomplish this

In Tcl is even easier for me:

```<code>% foreach var1 [list 1 3] var2 [list 2 4] {
    puts "$var1 $var2"
  }
1 2
3 4
</code>```

But I cannot figure out how to do it in Elixir.

The reason I want to do it is because I have a list of maps like this

```<code>[%{"a" => "1539", "b" => "300"},
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "8267", "b" => "27"}]
</code>```

and I have a list of items of the same size:

```<code>["a","b","c","d","e"]
</code>```

and I'd like to run them through a loop together to replace items in the map if and when one of the elements in the map is a certain condition (not 0):

```<code>[%{"a" => "a", "b" => "300"},   # notice the change in element "a"
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "e", "b" => "27"}]    # notice the change in element "a"
</code>```

Anyway. Can someone help me understand enumerable or how to iterate over two lists in elixir?

答:
Or, using the comprehension:</p>

```<code>for {map, item} <- Enum.zip(list_of_maps, list_of_items),
  into: [],
    do: if (map["b"] == "0"), do: map, else: %{map | "a" => item}
</code>```

Body:
I'd like to iterate over two lists at once, but can't figure out how. The for loop, which allows you to have multiple lists acts as nested for loops and I'm not that familiar with Enum, but perhaps there's a solution there.

Python has zip(list_1,list_2) and enumerate(list_1) to accomplish this

In Tcl is even easier for me:

% foreach var1 [list 1 3] var2 [list 2 4] {
    puts "$var1 $var2"
  }
1 2
3 4

But I cannot figure out how to do it in Elixir.

The reason I want to do it is because I have a list of maps like this

[%{"a" => "1539", "b" => "300"},
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "8267", "b" => "27"}]

and I have a list of items of the same size:

["a","b","c","d","e"]

and I'd like to run them through a loop together to replace items in the map if and when one of the elements in the map is a certain condition (not 0):

[%{"a" => "a", "b" => "300"},   # notice the change in element "a"
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "e", "b" => "27"}]    # notice the change in element "a"

Anyway. Can someone help me understand enumerable or how to iterate over two lists in elixir?

Body:
Or, using the comprehension:

for {map, item} <- Enum.zip(list_of_maps, list_of_items),
  into: [],
    do: if (map["b"] == "0"), do: map, else: %{map | "a" => item}


问:
Javascript prototype extension method
I have a prototype model where I need to include the following extension methods into the prototype:

```<code>String.prototype.startsWith = function(str){
    return (this.indexOf(str) === 0);
}
</code>```

Example:
[JS]

```<code>sample = function() {
    this.i;
}

sample.prototype = {
    get_data: function() {
        return this.i;
    }
}
</code>```

In the prototype model, how can I use the extension methods or any other way to create extension methods in JS prototype model.

答:
Not sure how correct this is, but please try this code. It worked in IE for me.

Add in JavaScript file:

```<code>String.prototype.includes = function (str) {
    var returnValue = false;

    if(this.indexOf(str) != -1){

        returnValue = true;
    }

    return returnValue;
}
</code>```

Title: Javascript prototype extension method

Body:
I have a prototype model where I need to include the following extension methods into the prototype:

String.prototype.startsWith = function(str){
    return (this.indexOf(str) === 0);
}

Example:
[JS]

sample = function() {
    this.i;
}

sample.prototype = {
    get_data: function() {
        return this.i;
    }
}

In the prototype model, how can I use the extension methods or any other way to create extension methods in JS prototype model.

Body:
Not sure how correct this is, but please try this code. It worked in IE for me.

Add in JavaScript file:

String.prototype.includes = function (str) {
    var returnValue = false;

    if(this.indexOf(str) != -1){

        returnValue = true;
    }

    return returnValue;
}