问:
SQL - Fill NULL values with previous value
After seeing a lot of examples, I didn't find a simple way to replace NULL values for each column with last value.

After pivot my table, I have this example:

```<code>IDS 1234,4567,7890

| 1234     |   4567    |   7890  |
|  1       |    2      |    3    |
| NULL     |    4      |    5    |
| NULL     |    6      |   NULL  |
|  8       |   NULL    |    9    |
</code>```

Result:

```<code>| 1234      |      4567      |     7890 |
|  1        |       2        |       3  |
|  1        |       4        |       5  |
|  1        |       6        |       5  |
|  8        |       6        |       9  |
</code>```

答:
Use CURSOR as there are probability of having more than 2 consecutive NULL in the result set and that case LEAD and LAG method will not work as they only can check 1 row around.</p>

```<code>DECLARE @id INT,@col_1234 INT, @col_4567 INT,@col_7890 INT
DECLARE @id_prev INT,@col_1234_prev INT,@col_4567_prev INT,@col_7890_prev INT
DECLARE @LoopOne INT = 1

DECLARE @TempTable TABLE
(
    id INT, col_1234 INT, col_4567 INT, col_7890 INT
)

DECLARE db_cursor CURSOR FOR
SELECT id, col_1234, col_4567, col_7890
FROM your_table

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @id, @col_1234, @col_4567, @col_7890

WHILE @@FETCH_STATUS = 0
BEGIN

    IF @LoopOne = 1
    BEGIN
        SET @id_prev = @id
        SET @col_1234_prev = @col_1234
        SET @col_4567_prev = @col_4567
        SET @col_7890_prev = @col_7890

        INSERT INTO @TempTable(id, col_1234, col_4567, col_7890)
        VALUES (@id, @col_1234, @col_4567, @col_7890 )

        SET @LoopOne = 2
    END

    ELSE
    BEGIN
        SET @id_prev = CASE WHEN @id IS NULL THEN @id_prev ELSE @id END
        SET @col_1234_prev = CASE WHEN @col_1234 IS NULL THEN @col_1234_prev ELSE @col_1234 END
        SET @col_4567_prev = CASE WHEN @col_4567 IS NULL THEN @col_4567_prev ELSE @col_4567 END
        SET @col_7890_prev = CASE WHEN @col_7890 IS NULL THEN @col_7890_prev ELSE @col_7890 END

        INSERT INTO @TempTable(id, col_1234, col_4567, col_7890)
        VALUES (@id_prev, @col_1234_prev, @col_4567_prev, @col_7890_prev )
    END

    FETCH NEXT FROM db_cursor INTO @id, @col_1234, @col_4567, @col_7890
END

CLOSE db_cursor
DEALLOCATE db_cursor

SELECT * FROM @TempTable
</code>```

Body:
After seeing a lot of examples, I didn't find a simple way to replace NULL values for each column with last value.

After pivot my table, I have this example:

IDS 1234,4567,7890

| 1234     |   4567    |   7890  |
|  1       |    2      |    3    |
| NULL     |    4      |    5    |
| NULL     |    6      |   NULL  |
|  8       |   NULL    |    9    |

Result:

| 1234      |      4567      |     7890 |
|  1        |       2        |       3  |
|  1        |       4        |       5  |
|  1        |       6        |       5  |
|  8        |       6        |       9  |

Body:
Use CURSOR as there are probability of having more than 2 consecutive NULL in the result set and that case LEAD and LAG method will not work as they only can check 1 row around.

DECLARE @id INT,@col_1234 INT, @col_4567 INT,@col_7890 INT
DECLARE @id_prev INT,@col_1234_prev INT,@col_4567_prev INT,@col_7890_prev INT
DECLARE @LoopOne INT = 1

DECLARE @TempTable TABLE
(
    id INT, col_1234 INT, col_4567 INT, col_7890 INT
)

DECLARE db_cursor CURSOR FOR
SELECT id, col_1234, col_4567, col_7890
FROM your_table

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @id, @col_1234, @col_4567, @col_7890

WHILE @@FETCH_STATUS = 0
BEGIN

    IF @LoopOne = 1
    BEGIN
        SET @id_prev = @id
        SET @col_1234_prev = @col_1234
        SET @col_4567_prev = @col_4567
        SET @col_7890_prev = @col_7890

        INSERT INTO @TempTable(id, col_1234, col_4567, col_7890)
        VALUES (@id, @col_1234, @col_4567, @col_7890 )

        SET @LoopOne = 2
    END

    ELSE
    BEGIN
        SET @id_prev = CASE WHEN @id IS NULL THEN @id_prev ELSE @id END
        SET @col_1234_prev = CASE WHEN @col_1234 IS NULL THEN @col_1234_prev ELSE @col_1234 END
        SET @col_4567_prev = CASE WHEN @col_4567 IS NULL THEN @col_4567_prev ELSE @col_4567 END
        SET @col_7890_prev = CASE WHEN @col_7890 IS NULL THEN @col_7890_prev ELSE @col_7890 END

        INSERT INTO @TempTable(id, col_1234, col_4567, col_7890)
        VALUES (@id_prev, @col_1234_prev, @col_4567_prev, @col_7890_prev )
    END

    FETCH NEXT FROM db_cursor INTO @id, @col_1234, @col_4567, @col_7890
END

CLOSE db_cursor
DEALLOCATE db_cursor

SELECT * FROM @TempTable


来源: stackexchange

问:
Error when implementing springboot with H2db
I am new to coding. I am getting below error when trying to run java application in springboot with H2db.

```<code>
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.777 s <<< FAILURE! - in com.example.demo.DemoApplicationTests
[ERROR] contextLoads(com.example.demo.DemoApplicationTests)  Time elapsed: 0.002 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   DemoApplicationTests.contextLoads » IllegalState Failed to load ApplicationCon...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  13.028 s
[INFO] Finished at: 2019-05-26T22:46:54+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project demo: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\v\Desktop\demo\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

Here is my xml:

```<code>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Application :

```<code>package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.example.demo.StudentRepository;

@SpringBootApplication
@EntityScan("com.example.demo.Student")
@EnableJpaRepositories("com.example.demo.StudentRepository")
public class H2demoApplication implements CommandLineRunner {

    // mvn spring-boot:run
    private Logger LOG = LoggerFactory.getLogger("H2demoApplication");

    StudentRepository studentRepository;

    @Autowired
    public H2demoApplication(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public static void main(String[] args) {
        SpringApplication.run(H2demoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("Student count in DB: {}", studentRepository.count());
    }
}

Entity:

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue
    private Long ID;
    private String NAME;
    private String SECTION;

    public Student() {
    }

    public Student(Long ID, String NAME, String SECTION) {
        this.ID = ID;
        this.NAME = NAME;
        this.SECTION = SECTION;
    }

    public Long getId() {
        return ID;
    }

    public void setId(Long ID) {
        this.ID = ID;
    }

    public String getName() {
        return NAME;
    }

    public void setName(String NAME) {
        this.NAME = NAME;
    }

    public String getSection() {
        return SECTION;
    }

    public void setSection(String SECTION) {
        this.SECTION = SECTION;
    }

}

Repository:

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}
</code>```

O/p should have "Student count in DB: 2"

my java version is :
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

Getting above error when running mvn clean install in command line.
I defined h2db configurations in application.properties file as below

H2 configurarion

```<code>spring.h2.console.enabled=true

spring.h2.console.path=/h2

Datasource

spring.datasource.url=jdbc:h2:~/test

spring.datasource.username=

spring.datasource.password=

spring.datasource.driver-class-name=org.h2.Driver
</code>```

in data.sql file kept data to be inserted :

```<code>insert into STUDENT
values(10001,'Ajay', 'AAA1');

insert into STUDENT
values(10002,'Ajit', 'AAA2');
</code>```

答:
You need to provide the hibernate dialect to configure hibernate befor connecting

use

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

ContentLicense: CC BY-SA 4.0

Body:
I am new to coding. I am getting below error when trying to run java application in springboot with H2db.

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.777 s <<< FAILURE! - in com.example.demo.DemoApplicationTests
[ERROR] contextLoads(com.example.demo.DemoApplicationTests)  Time elapsed: 0.002 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   DemoApplicationTests.contextLoads » IllegalState Failed to load ApplicationCon...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  13.028 s
[INFO] Finished at: 2019-05-26T22:46:54+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project demo: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\v\Desktop\demo\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Here is my xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Application :

package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.example.demo.StudentRepository;

@SpringBootApplication
@EntityScan("com.example.demo.Student")
@EnableJpaRepositories("com.example.demo.StudentRepository")
public class H2demoApplication implements CommandLineRunner {

    // mvn spring-boot:run
    private Logger LOG = LoggerFactory.getLogger("H2demoApplication");

    StudentRepository studentRepository;

    @Autowired
    public H2demoApplication(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public static void main(String[] args) {
        SpringApplication.run(H2demoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("Student count in DB: {}", studentRepository.count());
    }
}

Entity:

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue
    private Long ID;
    private String NAME;
    private String SECTION;

    public Student() {
    }

    public Student(Long ID, String NAME, String SECTION) {
        this.ID = ID;
        this.NAME = NAME;
        this.SECTION = SECTION;
    }

    public Long getId() {
        return ID;
    }

    public void setId(Long ID) {
        this.ID = ID;
    }

    public String getName() {
        return NAME;
    }

    public void setName(String NAME) {
        this.NAME = NAME;
    }

    public String getSection() {
        return SECTION;
    }

    public void setSection(String SECTION) {
        this.SECTION = SECTION;
    }

}

Repository:

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}

O/p should have "Student count in DB: 2"

my java version is :
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

Getting above error when running mvn clean install in command line.
I defined h2db configurations in application.properties file as below

H2 configurarion

spring.h2.console.enabled=true

spring.h2.console.path=/h2

Datasource

spring.datasource.url=jdbc:h2:~/test

spring.datasource.username=

spring.datasource.password=

spring.datasource.driver-class-name=org.h2.Driver

in data.sql file kept data to be inserted :

insert into STUDENT
values(10001,'Ajay', 'AAA1');

insert into STUDENT
values(10002,'Ajit', 'AAA2');


问:
MustacheException: No method or field with name 'Id' on line 15. Whitelabel Error Page
I'm using MySQL Ver 15.1 Distrib 10.1.38-MariaDB, for debian-linux-gnu (x86_64).
Open-JDK 1.8.0
Spring Boot 2.1.4 RELEASE

Accessing my application I got this stacktrace on my whitelable page:

```<code> This application has no explicit mapping for /error, so you are seeing
 this as a fallback.

Mon May 27 16:12:06 AZOST 2019
There was an unexpected error (type=Internal Server Error, status=500).
No method or field with name 'id' on line 15
com.samskivert.mustache.MustacheException$Context: No method or field
with name 'id' on line 15
at com.samskivert.mustache.Template.checkForMissing(Template.java:326)
at com.samskivert.mustache.Template.getValue(Template.java:234)
at com.samskivert.mustache.Template.getValueOrDefault(Template.java:279)
at com.samskivert.mustache.Mustache$VariableSegment.execute(Mustache.java:802)
at com.samskivert.mustache.Mustache$BlockSegment.executeSegs(Mustache.java:845)
at com.samskivert.mustache.Mustache$SectionSegment.execute(Mustache.java:881)
at com.samskivert.mustache.Template.executeSegs(Template.java:157)
at com.samskivert.mustache.Template.execute(Template.java:134)
at org.springframework.boot.web.servlet.view.MustacheView.renderMergedTemplateModel(MustacheView.java:81)
at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:178)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
</code>```

This is my code:

main.mustache

```<code><html>

<body>
<div>
    <form method="POST">
        <input type ="text" name="text" placeholder="Введите сообщение" />
        <input type ="text" name="tag" placeholder="Тег"/>
        <button type="submit">Добавить</button>
    </form>
</div>

<div>Message list</div>
{{#messages}}
<div>
<b>{{id}}</b>
<span>{{text}}</span>
<i>{{tag}}</i>
</div>
{{/messages}}
</code>```

This is my Controller:

GreetingController

```<code>package com.example.sweater;

import com.example.sweater.domain.Message;
import com.example.sweater.repos.MessageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class GreetingsController {

@Autowired
private MessageRepo messageRepo;

@RequestMapping("/greeting")
public String greeting(@RequestParam(name="name", required = false, defaultValue = "World") String name,
                       Map<String, Object> model)
{
    model.put("name", name);
    return "greeting";
}
@GetMapping
public String main(Map<String, Object> model){
    Iterable<Message> messages = messageRepo.findAll();
    model.put("messages", "messages");
    return "main";
}
@PostMapping
public String add(@RequestParam String text, @RequestParam String tag, Map<String, Object> model){
    Message message = new Message(text, tag);
    messageRepo.save(message);
    Iterable<Message> messages = messageRepo.findAll();
    model.put("messages", messages);
    return "main";
}
</code>```

}

This is my project structure:
![ProjectStructure]: (https://lh3.googleusercontent.com/PKENYsmd29WxawAs-jMtrwBTBqDHNMoS3LWU_BTyDOjO7L5z8DrojsmB-pHfb03QE2Ce7Q3_xE4HrMk3PZax06Cd2b-NY42pB9e5DzCv-Uh6VlkbtebFb2W0HYq8u7WaG7WWU7uC7_7z5x8TXTXl65Wg-rMCes6HkQ8PTQ2_-QOMBW_I2yV8dXN2Xs2-vsHAWX5upPKw2oi3ZAtxOVvDKUm-znDD4czMIPAMKsDAfBXWWf5QbVpTysOEoE_rF7_7z9lWBf0ujZBYpllK5aXxsWB0OorsnnLb9XvmCMaGU-3xsOykLRFiq_LcYk5erFkEsBSkkobYT67ZPIPxrcnC3iGluBy5IYjDUrhwVpn-WPv76RsEID0qF0PYrAGO01M1Xb0QzhOJjx0wKsIKIDBRSEfxSRSLp-rGVW0rsDF_VIQeRXLs-Bvt45LznMXIBjCH_OLA3sg5p7RsgmiiRrjtsFhKmH-GOUds1GvrUTfpdpjlcySm_vpYK84WhyGfc64As45xB04w62mkD0LgZpw9pFcENbp8l9_MNhRlh0dLccB0Tku5H9h1-9H4FD3OzHYlw6SlsoNfYob_7BeZK3QXaTujtu1K7Hn-5zaxJ_oI4Ea_4P59BSmzAp6X_D6O0Rs9rZ8zPtSPNHiBzB6SP_vOuCfMuOAa8w=w340-h520-no)

I expected this code to display HTML code with empty fields waiting for me to fill in them, access the database and show all tuples which was typed into empty fields, but instead I ran into this stacktrace. What should i fix to make it work correctly?

答:
From your stack trace it can be seen that you are passing messages to be iterated in the template :

```<code>There was an unexpected error (type=Internal Server Error, status=500).
No method or field with name 'id' on line 15
</code>```

But the messages model being returned from the controller might be missing 'id' values . If we didn’t assign a value to a {{id}} on the Mustache’s page, the jmustache will throw the above error message.Can you please check if the data returned from the main method is returning correctly.Or mark the value as optional in the template.

If not check the following :
Ensure that you have configured mustache properly.Ensure that you have the following dependency added in pom :

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mustache</artifactId>
    </dependency>
</code>```

Also ensure that all your dynamic html content is kept in the directory :

```<code>src/main/resources/templates/
</code>```

folder so that spring will take it up.

Body:
I'm using MySQL Ver 15.1 Distrib 10.1.38-MariaDB, for debian-linux-gnu (x86_64).
Open-JDK 1.8.0
Spring Boot 2.1.4 RELEASE

Accessing my application I got this stacktrace on my whitelable page:

 This application has no explicit mapping for /error, so you are seeing
 this as a fallback.

Mon May 27 16:12:06 AZOST 2019
There was an unexpected error (type=Internal Server Error, status=500).
No method or field with name 'id' on line 15
com.samskivert.mustache.MustacheException$Context: No method or field
with name 'id' on line 15
at com.samskivert.mustache.Template.checkForMissing(Template.java:326)
at com.samskivert.mustache.Template.getValue(Template.java:234)
at com.samskivert.mustache.Template.getValueOrDefault(Template.java:279)
at com.samskivert.mustache.Mustache$VariableSegment.execute(Mustache.java:802)
at com.samskivert.mustache.Mustache$BlockSegment.executeSegs(Mustache.java:845)
at com.samskivert.mustache.Mustache$SectionSegment.execute(Mustache.java:881)
at com.samskivert.mustache.Template.executeSegs(Template.java:157)
at com.samskivert.mustache.Template.execute(Template.java:134)
at org.springframework.boot.web.servlet.view.MustacheView.renderMergedTemplateModel(MustacheView.java:81)
at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:178)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

This is my code:

main.mustache

    <form method="POST">
        <input type ="text" name="text" placeholder="Введите сообщение" />
        <input type ="text" name="tag" placeholder="Тег"/>
        <button type="submit">Добавить</button>
    </form>

Message list

{{#messages}}

{{id}}
{{text}}
{{tag}}

{{/messages}}

This is my Controller:

GreetingController

package com.example.sweater;

import com.example.sweater.domain.Message;
import com.example.sweater.repos.MessageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class GreetingsController {

@Autowired
private MessageRepo messageRepo;

@RequestMapping("/greeting")
public String greeting(@RequestParam(name="name", required = false, defaultValue = "World") String name,
                       Map<String, Object> model)
{
    model.put("name", name);
    return "greeting";
}
@GetMapping
public String main(Map<String, Object> model){
    Iterable<Message> messages = messageRepo.findAll();
    model.put("messages", "messages");
    return "main";
}
@PostMapping
public String add(@RequestParam String text, @RequestParam String tag, Map<String, Object> model){
    Message message = new Message(text, tag);
    messageRepo.save(message);
    Iterable<Message> messages = messageRepo.findAll();
    model.put("messages", messages);
    return "main";
}

}

This is my project structure:
![ProjectStructure]: (<a href="https://lh3.googleusercontent.com/PKENYsmd29WxawAs-jMtrwBTBqDHNMoS3LWU_BTyDOjO7L5z8DrojsmB-pHfb03QE2Ce7Q3_xE4HrMk3PZax06Cd2b-NY42pB9e5DzCv-Uh6VlkbtebFb2W0HYq8u7WaG7WWU7uC7_7z5x8TXTXl65Wg-rMCes6HkQ8PTQ2_-QOMBW_I2yV8dXN2Xs2-vsHAWX5upPKw2oi3ZAtxOVvDKUm-znDD4czMIPAMKsDAfBXWWf5QbVpTysOEoE_rF7_7z9lWBf0ujZBYpllK5aXxsWB0OorsnnLb9XvmCMaGU-3xsOykLRFiq_LcYk5erFkEsBSkkobYT67ZPIPxrcnC3iGluBy5IYjDUrhwVpn-WPv76RsEID0qF0PYrAGO01M1Xb0QzhOJjx0wKsIKIDBRSEfxSRSLp-rGVW0rsDF_VIQeRXLs-Bvt45LznMXIBjCH_OLA3sg5p7RsgmiiRrjtsFhKmH-GOUds1GvrUTfpdpjlcySm_vpYK84WhyGfc64As45xB04w62mkD0LgZpw9pFcENbp8l9_MNhRlh0dLccB0Tku5H9h1-9H4FD3OzHYlw6SlsoNfYob_7BeZK3QXaTujtu1K7Hn-5zaxJ_oI4Ea_4P59BSmzAp6X_D6O0Rs9rZ8zPtSPNHiBzB6SP_vOuCfMuOAa8w=w340-h520-no" rel="nofollow noreferrer">https://lh3.googleusercontent.com/PKENYsmd29WxawAs-jMtrwBTBqDHNMoS3LWU_BTyDOjO7L5z8DrojsmB-pHfb03QE2Ce7Q3_xE4HrMk3PZax06Cd2b-NY42pB9e5DzCv-Uh6VlkbtebFb2W0HYq8u7WaG7WWU7uC7_7z5x8TXTXl65Wg-rMCes6HkQ8PTQ2_-QOMBW_I2yV8dXN2Xs2-vsHAWX5upPKw2oi3ZAtxOVvDKUm-znDD4czMIPAMKsDAfBXWWf5QbVpTysOEoE_rF7_7z9lWBf0ujZBYpllK5aXxsWB0OorsnnLb9XvmCMaGU-3xsOykLRFiq_LcYk5erFkEsBSkkobYT67ZPIPxrcnC3iGluBy5IYjDUrhwVpn-WPv76RsEID0qF0PYrAGO01M1Xb0QzhOJjx0wKsIKIDBRSEfxSRSLp-rGVW0rsDF_VIQeRXLs-Bvt45LznMXIBjCH_OLA3sg5p7RsgmiiRrjtsFhKmH-GOUds1GvrUTfpdpjlcySm_vpYK84WhyGfc64As45xB04w62mkD0LgZpw9pFcENbp8l9_MNhRlh0dLccB0Tku5H9h1-9H4FD3OzHYlw6SlsoNfYob_7BeZK3QXaTujtu1K7Hn-5zaxJ_oI4Ea_4P59BSmzAp6X_D6O0Rs9rZ8zPtSPNHiBzB6SP_vOuCfMuOAa8w=w340-h520-no)

I expected this code to display HTML code with empty fields waiting for me to fill in them, access the database and show all tuples which was typed into empty fields, but instead I ran into this stacktrace. What should i fix to make it work correctly?

Body:
From your stack trace it can be seen that you are passing messages to be iterated in the template :

There was an unexpected error (type=Internal Server Error, status=500).
No method or field with name 'id' on line 15

But the messages model being returned from the controller might be missing 'id' values . If we didn’t assign a value to a {{id}} on the Mustache’s page, the jmustache will throw the above error message.Can you please check if the data returned from the main method is returning correctly.Or mark the value as optional in the template.

If not check the following :
Ensure that you have configured mustache properly.Ensure that you have the following dependency added in pom :

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mustache</artifactId>
    </dependency>

Also ensure that all your dynamic html content is kept in the directory :

src/main/resources/templates/

folder so that spring will take it up.


问:
Is there any way to add swipeable tab to an existing Ionic blank project?
I tried installing  npm i -S @ionic-super-tabs/angular , which doesn’t work in Ionic 4. Please let me know if there any way to do this</p>

答:
Yes, there is a way to achieve this.

page.ts

```<code>import { Component, ViewChild } from '@angular/core';
import { IonSlides } from '@ionic/angular';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
  @ViewChild('slider') slider: IonSlides;
  page = "0";

  selectedTab(index) {
    this.slider.slideTo(index);
  }

  async moveButton() {
    let index = await this.slider.getActiveIndex();
    this.page = index.toString();
    // console.log("0")
  }

  segmentChanged(ev: any) {
    // console.log('Segment changed', ev);
  }
}
</code>```

page.html

```<code>  <ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>Notifications</ion-title>
  </ion-toolbar>
  <ion-toolbar>
    <ion-segment (ionChange)="segmentChanged($event)" [(ngModel)]="page">
      <ion-segment-button value="0" (click)="selectedTab(0)">
        <ion-label>All</ion-label>
      </ion-segment-button>
      <ion-segment-button value="1" (click)="selectedTab(1)">
        <ion-label>Mentions</ion-label>
      </ion-segment-button>
    </ion-segment>
  </ion-toolbar>
</ion-header>
<ion-content>
  <ion-slides #slider (ionSlideWillChange)="moveButton()">
    <ion-slide>
      <ion-label>All</ion-label>
    </ion-slide>
    <ion-slide>
      <ion-label>Mentions</ion-label>
    </ion-slide>
  </ion-slides>
</ion-content>
</code>```

Segment work as swipeable tabs, Hope it help you :)

Body:
Yes, there is a way to achieve this.

page.ts

import { Component, ViewChild } from '@angular/core';
import { IonSlides } from '@ionic/angular';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
  @ViewChild('slider') slider: IonSlides;
  page = "0";

  selectedTab(index) {
    this.slider.slideTo(index);
  }

  async moveButton() {
    let index = await this.slider.getActiveIndex();
    this.page = index.toString();
    // console.log("0")
  }

  segmentChanged(ev: any) {
    // console.log('Segment changed', ev);
  }
}

page.html

  <ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>Notifications</ion-title>
  </ion-toolbar>
  <ion-toolbar>
    <ion-segment (ionChange)="segmentChanged($event)" [(ngModel)]="page">
      <ion-segment-button value="0" (click)="selectedTab(0)">
        <ion-label>All</ion-label>
      </ion-segment-button>
      <ion-segment-button value="1" (click)="selectedTab(1)">
        <ion-label>Mentions</ion-label>
      </ion-segment-button>
    </ion-segment>
  </ion-toolbar>
</ion-header>
<ion-content>
  <ion-slides #slider (ionSlideWillChange)="moveButton()">
    <ion-slide>
      <ion-label>All</ion-label>
    </ion-slide>
    <ion-slide>
      <ion-label>Mentions</ion-label>
    </ion-slide>
  </ion-slides>
</ion-content>

Segment work as swipeable tabs, Hope it help you :)


问:
What does the "declare a static final serialVersionUID" warning mean and how to fix?

Possible Duplicate:

  What does it mean: The serializable class does not declare a static final serialVersionUID field?

Java compiler warning: The serializable class [*****] does not declare a static final serialVersionUID field of type long.

Why? How to fix it?

答:
This is explained fairly well here:

The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If no match is found, then an InvalidClassException is thrown.

You fix the error by adding

```<code>private static final long serialVersionUID = 7526472295622776147L;  // unique id
</code>```

to the class.

Further reading:

java.io.Serializable

Why should I bother about serialVersionUID? (stackoverflow)

A side note: If you're using Eclipse and if you (and no one else) ever plan to serialize your classes, you can also suppress the error by going to

     Window → Preferences → Java → Compiler → Errors/Warnings

and select "Ignore" on "Serializable Class without serialVersionUID".

ContentLicense: CC BY-SA 3.0

Body:
This is explained fairly well here:

The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If no match is found, then an InvalidClassException is thrown.

You fix the error by adding

private static final long serialVersionUID = 7526472295622776147L;  // unique id

to the class.

Further reading:

java.io.Serializable

Why should I bother about serialVersionUID? (stackoverflow)

A side note: If you're using Eclipse and if you (and no one else) ever plan to serialize your classes, you can also suppress the error by going to

     Window → Preferences → Java → Compiler → Errors/Warnings

and select "Ignore" on "Serializable Class without serialVersionUID".


问:
how to find the height and width of an alphabet/letter
I want to find the height and width of a letter in generalize form but I dont know what algorithm should I apply so that I can find the height and width of any letter
I am using MATLAB as well as openCv. Anyone can suggest me anything how to approach

this image is my test image

my main task is to find the height and width of words say for eg "Football"

答:
You read the image with imread. You find the first instance where pixels are not white (255). You can sum rows and columns to get it quick, but you have to hide the add in the corner for this to work. You can then use the difference between y and x to get the width and height.</p>

```<code>img = imread('unKDO.jpg');
% hide lettergenerator add
img(565:end,448:end) = 255;
% see when pixels are less than white
y(1) = find(mean(img) < 255,1);
y(2) = find(mean(img) < 255,1,'last');
x(1) = find(mean(img,2) < 255,1);
x(2) = find(mean(img,2) < 255,1,'last');
figure;
imshow(img)
hold on
plot(y(1),x(1),'*r')
plot(y(2),x(2),'*g')
</code>```

Body:
You read the image with imread. You find the first instance where pixels are not white (255). You can sum rows and columns to get it quick, but you have to hide the add in the corner for this to work. You can then use the difference between y and x to get the width and height.

img = imread('unKDO.jpg');
% hide lettergenerator add
img(565:end,448:end) = 255;
% see when pixels are less than white
y(1) = find(mean(img) < 255,1);
y(2) = find(mean(img) < 255,1,'last');
x(1) = find(mean(img,2) < 255,1);
x(2) = find(mean(img,2) < 255,1,'last');
figure;
imshow(img)
hold on
plot(y(1),x(1),'*r')
plot(y(2),x(2),'*g')


问:
Which is better approach?
I need to find subject, but it could be null. So have to do this without throwing exception. I have two approach and please suggest which is better?</p>

```<code>public static String getSafeSubject(SNSEvent.SNSRecord record){
        try{
            return record.getSNS().getSubject();
        }catch (Exception e){
            return "Failed to retrieve subject";
        }
}
</code>```

```<code>public static String getSafeSubject(SNSEvent.SNSRecord record){
  if(record == null || record.getSNS() == null ||
  record.getSNS().getSubject() == null){
            return "Failed to retrieve subject";
        }
        return record.getSNS().getSubject();
    }
</code>```

答:
This question isn't easy to answer and there are many things to consider. This can be up for debate, depending on the style a developer wants to use. There are pros and cons of both approaches. I will list some below:

Using try-catch:

Pro:

Generally easier to read

Faster to develop

Con:

Hides the error

May be slower to execute (more overhead) - this one will vary depending on guard conditions

Using guard-conditions:

Pro:

Explicit, meaning the dev decides what is valid and what is not

Method may throw if there are other issues

Con:

Slower to write

May forget to include valid guard conditions

Title: Which is better approach?

Body:
I need to find subject, but it could be null. So have to do this without throwing exception. I have two approach and please suggest which is better?

public static String getSafeSubject(SNSEvent.SNSRecord record){
        try{
            return record.getSNS().getSubject();
        }catch (Exception e){
            return "Failed to retrieve subject";
        }
}

public static String getSafeSubject(SNSEvent.SNSRecord record){
  if(record == null || record.getSNS() == null ||
  record.getSNS().getSubject() == null){
            return "Failed to retrieve subject";
        }
        return record.getSNS().getSubject();
    }


问:
Python, what is this for loop doing?
I have scoured the internet and I cannot find any reference to this type of for loop:

```<code>variable = [(item["attribute1"], item["attribute2]") for item in piece_of_json_data]
</code>```

I am using this to update wtform's SelecField choices:

```<code>form.SelectField.choices = variable
</code>```

but I can only get it to work if I replace one of the attributes in parenthesis with a static number:

```<code>variable = [(1, item["attribute2"]) for item in piece_of_json_data]
</code>```

but that sets the value of the option field to "1", when I need the option values to be one of the attributes as a string.

Does this create a dict? a tuple? is there some kind of terminology for this that I can use to find documentation?

答:
Thanks to the comments, I now understand that I am using list comprehension to create a tuple. The tuple works fine with both string and integer values. My issue has to do with .choices not accepting a string.

I found that my only problem is that I had coerce set to int on my selectfield, so naturally it wanted an integer.

Title: Python, what is this for loop doing?

Body:
I have scoured the internet and I cannot find any reference to this type of for loop:

variable = [(item["attribute1"], item["attribute2]") for item in piece_of_json_data]

I am using this to update wtform's SelecField choices:

form.SelectField.choices = variable

but I can only get it to work if I replace one of the attributes in parenthesis with a static number:

variable = [(1, item["attribute2"]) for item in piece_of_json_data]

but that sets the value of the option field to "1", when I need the option values to be one of the attributes as a string.

Does this create a dict? a tuple? is there some kind of terminology for this that I can use to find documentation?


问:
How could I implement image channel drop with the python lib of pillow
I need to randomly zero out 0, 1 or 2 channel of a pillow image. That means I need to randomly set 0, 1 or 2 channels of an image to 0.

How could I do that with pil?

答:
TRY:-

```<code>from PIL import Image
import random

# Provide path to your image
img = Image.open(r"Image_Path")

# Converting the Image's mode to RGB, coz you wanted a random channel out of 3 channels
img.convert("RGB")

# Getting individual channels off the image
r, g, b = img.split()

# choice will store a random number b/w 0-2 we will use this value to extract a random channel
choice = random.randrange(0, 3)
null_channel = (r, g, b)[choice]

# printing the index of our randomly selected channel, ( 0 = Red; 1 = Green; 2 = Blue)
print(choice)

# changing each individual pixel value to 0, of our randomly selected channel
null_channel = null_channel.point(lambda p: 0)

# These conditions will provide the null channel to it's original channel's variable
if choice is 1:
    g = null_channel

elif choice is 2:
    b = null_channel

else:
    r = null_channel

# creating a new image with the original two channels' and our null'd channel
new_img = Image.merge("RGB", (r, g, b))

new_img.save("new_img.jpg")
</code>```

The above code will first convert an image's color mode to RGB, so that we can deal with 3 channels. Then it will extract the individual image channels. Then it will select a random channel of the 3 channel, and convert each pixel value of that channel to (0, 0, 0). Then it will figure out which channel was originally used (R or G or B) and then overwrite the modified values to the channel. In the end, it will create a Image Object by merging all the new channels and saves it.

Sample Image:-

Image after modification:-

After analysing the modified Image, we can clearly deduce that the red channel of the image was converted into null channel.

Body:
TRY:-

from PIL import Image
import random

# Provide path to your image
img = Image.open(r"Image_Path")

# Converting the Image's mode to RGB, coz you wanted a random channel out of 3 channels
img.convert("RGB")

# Getting individual channels off the image
r, g, b = img.split()

# choice will store a random number b/w 0-2 we will use this value to extract a random channel
choice = random.randrange(0, 3)
null_channel = (r, g, b)[choice]

# printing the index of our randomly selected channel, ( 0 = Red; 1 = Green; 2 = Blue)
print(choice)

# changing each individual pixel value to 0, of our randomly selected channel
null_channel = null_channel.point(lambda p: 0)

# These conditions will provide the null channel to it's original channel's variable
if choice is 1:
    g = null_channel

elif choice is 2:
    b = null_channel

else:
    r = null_channel

# creating a new image with the original two channels' and our null'd channel
new_img = Image.merge("RGB", (r, g, b))

new_img.save("new_img.jpg")

The above code will first convert an image's color mode to RGB, so that we can deal with 3 channels. Then it will extract the individual image channels. Then it will select a random channel of the 3 channel, and convert each pixel value of that channel to (0, 0, 0). Then it will figure out which channel was originally used (R or G or B) and then overwrite the modified values to the channel. In the end, it will create a Image Object by merging all the new channels and saves it.

Sample Image:-

Image after modification:-

After analysing the modified Image, we can clearly deduce that the red channel of the image was converted into null channel.


问:
org.gradle.api.tasks.compile.CompileOptions.setBootClasspath(Ljava/lang/String;)V'
I'm unable to build the project after updating android studio to 3.4. can anyone please help me.

Unable to find method 'org.gradle.api.tasks.compile.CompileOptions.setBootClasspath(Ljava/lang/String;)V'.
Possible causes for this unexpected error include:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)

The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

Caused by: org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':LogManagerAndroidProject'.
        at org.gradle.configuration.project.LifecycleProjectEvaluator.wrapException(LifecycleProjectEvaluator.java:79)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:72)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$600(LifecycleProjectEvaluator.java:53)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate.run(LifecycleProjectEvaluator.java:198)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:301)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:293)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$EvaluateProject$1.run(LifecycleProjectEvaluator.java:111)
        at org.gradle.internal.Factories$1.create(Factories.java:25)
        at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.withMutableState(DefaultProjectStateRegistry.java:200)
        at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.withMutableState(DefaultProjectStateRegistry.java:186)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$EvaluateProject.run(LifecycleProjectEvaluator.java:95)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:301)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:293)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:67)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:693)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:141)
        at org.gradle.api.internal.project.DefaultProjectAccessListener.evaluateProjectAndDiscoverTasks(DefaultProjectAccessListener.java:32)
        at org.gradle.api.internal.project.DefaultProjectAccessListener.beforeResolvingProjectDependency(DefaultProjectAccessListener.java:28)
        at org.gradle.api.internal.artifacts.dependencies.DefaultProjectDependency.beforeResolved(DefaultProjectDependency.java:101)
        at org.gradle.api.internal.artifacts.ivyservice.moduleconverter.dependencies.ProjectIvyDependencyDescriptorFactory.createDependencyDescriptor(ProjectIvyDependencyDescriptorFactor
y.java:41)
        at org.gradle.api.internal.artifacts.ivyservice.moduleconverter.dependencies.DefaultDependencyDescriptorFactory.createDependencyDescriptor(DefaultDependencyDescriptorFactory.java
:46)
        at org.gradle.api.internal.artifacts.ivyservice.moduleconverter.dependencies.DefaultLocalConfigurationMetadataBuilder.addDependencies(DefaultLocalConfigurationMetadataBuilder.jav
a:58)
        at org.gradle.api.internal.artifacts.ivyservice.moduleconverter.dependencies.DefaultLocalConfigurationMetadataBuilder.addDependenciesAndExcludes(DefaultLocalConfigurationMetadata
Builder.java:48)
        at org.gradle.internal.component.local.model.DefaultLocalComponentMetadata$DefaultLocalConfigurationMetadata.realizeDependencies(DefaultLocalComponentMetadata.java:499)
        at org.gradle.internal.component.local.model.DefaultLocalComponentMetadata$DefaultLocalConfigurationMetadata.addDefinedExcludes(DefaultLocalComponentMetadata.java:456)
        at org.gradle.internal.component.local.model.DefaultLocalComponentMetadata$DefaultLocalConfigurationMetadata.getExcludes(DefaultLocalComponentMetadata.java:447)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.NodeState.getModuleResolutionFilter(NodeState.java:384)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.NodeState.visitOutgoingDependencies(NodeState.java:192)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.DependencyGraphBuilder.traverseGraph(DependencyGraphBuilder.java:169)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.DependencyGraphBuilder.resolve(DependencyGraphBuilder.java:131)
        at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultArtifactDependencyResolver.resolve(DefaultArtifactDependencyResolver.java:121)
        at org.gradle.api.internal.artifacts.ivyservice.DefaultConfigurationResolver.resolveGraph(DefaultConfigurationResolver.java:171)
        at org.gradle.api.internal.artifacts.ivyservice.ShortCircuitEmptyConfigurationResolver.resolveGraph(ShortCircuitEmptyConfigurationResolver.java:86)
        at org.gradle.api.internal.artifacts.ivyservice.ErrorHandlingConfigurationResolver.resolveGraph(ErrorHandlingConfigurationResolver.java:73)
        ... 160 more
Caused by: org.gradle.internal.event.ListenerNotificationException: Failed to notify project evaluation listener.
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:86)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
        at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
        at com.sun.proxy.$Proxy26.afterEvaluate(Unknown Source)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate$1.execute(LifecycleProjectEvaluator.java:190)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate$1.execute(LifecycleProjectEvaluator.java:187)
        at org.gradle.api.internal.project.DefaultProject.stepEvaluationListener(DefaultProject.java:1419)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate.run(LifecycleProjectEvaluator.java:196)
        ... 196 more
Caused by: java.lang.NoSuchMethodError: org.gradle.api.tasks.compile.CompileOptions.setBootClasspath(Ljava/lang/String;)V
        at com.android.build.gradle.tasks.factory.JavaCompileConfigAction.execute(JavaCompileConfigAction.java:82)
        at com.android.build.gradle.tasks.factory.JavaCompileConfigAction.execute(JavaCompileConfigAction.java:34)
        at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:360)
        at com.android.build.gradle.internal.TaskContainerAdaptor.create(TaskContainerAdaptor.java:59)
        at com.android.build.gradle.internal.scope.AndroidTaskRegistry.create(AndroidTaskRegistry.java:47)
        at com.android.build.gradle.internal.scope.AndroidTaskRegistry.create(AndroidTaskRegistry.java:89)
        at com.android.build.gradle.internal.TaskManager.createJavacTask(TaskManager.java:1124)
        at com.android.build.gradle.internal.LibraryTaskManager.lambda$createTasksForVariantData$9(LibraryTaskManager.java:215)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
        at com.android.build.gradle.internal.LibraryTaskManager.createTasksForVariantData(LibraryTaskManager.java:206)
        at com.android.build.gradle.internal.VariantManager.createTasksForVariantData(VariantManager.java:460)
        at com.android.build.gradle.internal.VariantManager.lambda$createAndroidTasks$1(VariantManager.java:282)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
        at com.android.build.gradle.internal.VariantManager.createAndroidTasks(VariantManager.java:278)
        at com.android.build.gradle.BasePlugin.lambda$createAndroidTasks$6(BasePlugin.java:601)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
        at com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.java:596)
        at com.android.build.gradle.BasePlugin.lambda$null$4(BasePlugin.java:526)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
        at com.android.build.gradle.BasePlugin.lambda$createTasks$5(BasePlugin.java:522)
        at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1$1.run(DefaultListenerBuildOperationDecorator.java:150)
        at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.reapply(DefaultUserCodeApplicationContext.java:58)
        at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1.run(DefaultListenerBuildOperationDecorator.java:147)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:301)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:293)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:175)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction.execute(DefaultListenerBuildOperationDecorator.java:144)
        at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
        at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
        ... 206 more
```

Body:
SampleProject/gradle/wrapper/gradle-wrapper.properties

distributionUrl=https://services.gradle.org/distributions/gradle-5.1.1-all.zip
▼ change
distributionUrl=https://services.gradle.org/distributions/gradle-4.6-all.zip


问:
Shopping cart component not updating with correct quantities
when I increment single card and click add button the card or cards is successfully added to the shopping cart but when I increment two or three cards first and then click the add button the respective card item quantity count does not match with the incremented values.

the full code is here -https://github.com/sivadass/react-shopping-cart

I think the problem is in Counter.js, it's not setting the previous state when increment and add later to the shopping card

```<code>import React, { Component } from "react";
import PropTypes from "prop-types";

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { value: this.props.productQuantity };
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
  }

  increment(e) {
    this.setState(
      prevState => ({
        value: Number(prevState.value) + 1
      }),
      function() {
        this.props.updateQuantity(this.state.value);
      }
    );
    e.preventDefault();
  }

  decrement(e) {
    e.preventDefault();
    if (this.state.value <= 1) {
      return this.state.value;
    } else {
      this.setState(
        prevState => ({
          value: Number(prevState.value) - 1
        }),
        function() {
          this.props.updateQuantity(this.state.value);
        }
      );
    }
  }

  feed(e) {
    this.setState(
      {
        value: this.refs.feedQty.value
      },
      function() {
        this.props.updateQuantity(this.state.value);
      }
    );
  }

  resetQuantity() {
    this.setState({
      value: 1
    });
  }
  render() {
    return (
      <div className="stepper-input">
        <a href="#" className="decrement" onClick={this.decrement}>
          –
        </a>
        <input
          ref="feedQty"
          type="number"
          className="quantity"
          value={this.state.value}
          onChange={this.feed.bind(this)}
        />
        <a href="#" className="increment" onClick={this.increment}>
          +
        </a>
      </div>
    );
  }
}

Counter.propTypes = {
  value: PropTypes.number
};

export default Counter;
</code>```

答:
The problem is that your components are all consuming the same quantity value stored in the parent via index.js. Your shopping cart takes the last-updated count value from any Counter and uses that to add the selected item. You need to isolate the quantity/count for each Product.

I cloned your repo and I was able to fix this by making an update to the Product.js component.

I gave Product.js its own private quantity to keep track of

```<code>class Product extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedProduct: {},
      quickViewProdcut: {},
      quantity: 1,
      isAdded: false
    };

    this.updateQuantity = this.updateQuantity.bind(this)
  }
</code>```

Create an event-handler that would update its own state-quantity.

```<code>  updateQuantity(value){
    this.setState({
      quantity: value
    })
  }
</code>```

Update definition of quantity in render() to use our isolated state-value instead of the value stored in the parent.

```<code>let quantity = this.state.quantity;
</code>```

Pass the event-handler above as a prop to Counter

```<code> <Counter
  productQuantity={quantity}
  updateQuantity={this.updateQuantity}
  resetQuantity={this.resetQuantity}
/>
</code>```

Your feature works completely fine after integrating those changes. See below for full-code:

```<code>import React, { Component } from "react";
import Counter from "./Counter";

class Product extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedProduct: {},
      quickViewProdcut: {},
      quantity: 1,
      isAdded: false
    };

    this.updateQuantity = this.updateQuantity.bind(this)
  }

  updateQuantity(value){
    this.setState({
      quantity: value
    })
  }

  addToCart(image, name, price, id, quantity) {
    this.setState(
      {
        selectedProduct: {
          image: image,
          name: name,
          price: price,
          id: id,
          quantity: quantity
        }
      },
      function() {
        this.props.addToCart(this.state.selectedProduct);
      }
    );
    this.setState(
      {
        isAdded: true
      },
      function() {
        setTimeout(() => {
          this.setState({
            isAdded: false,
            selectedProduct: {}
          });
        }, 3500);
      }
    );
  }
  quickView(image, name, price, id) {
    this.setState(
      {
        quickViewProdcut: {
          image: image,
          name: name,
          price: price,
          id: id
        }
      },
      function() {
        this.props.openModal(this.state.quickViewProdcut);
      }
    );
  }
  render() {
    let image = this.props.image;
    let name = this.props.name;
    let price = this.props.price;
    let id = this.props.id;
    let quantity = this.state.quantity;
    return (
      <div className="product">
        <div className="product-image">
          <img
            src={image}
            alt={this.props.name}
            onClick={this.quickView.bind(
              this,
              image,
              name,
              price,
              id,
              quantity
            )}
          />
        </div>
        <h4 className="product-name">{this.props.name}</h4>
        <p className="product-price">{this.props.price}</p>
        <Counter
          productQuantity={quantity}
          updateQuantity={this.updateQuantity}
          resetQuantity={this.resetQuantity}
        />
        <div className="product-action">
          <button
            className={!this.state.isAdded ? "" : "added"}
            type="button"
            onClick={this.addToCart.bind(
              this,
              image,
              name,
              price,
              id,
              quantity
            )}
          >
            {!this.state.isAdded ? "ADD TO CART" : "✔ ADDED"}
          </button>
        </div>
      </div>
    );
  }
}

export default Product;
</code>```

Body:
when I increment single card and click add button the card or cards is successfully added to the shopping cart but when I increment two or three cards first and then click the add button the respective card item quantity count does not match with the incremented values.

the full code is here -https://github.com/sivadass/react-shopping-cart

I think the problem is in Counter.js, it's not setting the previous state when increment and add later to the shopping card

import React, { Component } from "react";
import PropTypes from "prop-types";

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { value: this.props.productQuantity };
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
  }

  increment(e) {
    this.setState(
      prevState => ({
        value: Number(prevState.value) + 1
      }),
      function() {
        this.props.updateQuantity(this.state.value);
      }
    );
    e.preventDefault();
  }

  decrement(e) {
    e.preventDefault();
    if (this.state.value <= 1) {
      return this.state.value;
    } else {
      this.setState(
        prevState => ({
          value: Number(prevState.value) - 1
        }),
        function() {
          this.props.updateQuantity(this.state.value);
        }
      );
    }
  }

  feed(e) {
    this.setState(
      {
        value: this.refs.feedQty.value
      },
      function() {
        this.props.updateQuantity(this.state.value);
      }
    );
  }

  resetQuantity() {
    this.setState({
      value: 1
    });
  }
  render() {
    return (

          –

        <input
          ref="feedQty"
          type="number"
          className="quantity"
          value={this.state.value}
          onChange={this.feed.bind(this)}
        />

          +

    );
  }
}

Counter.propTypes = {
  value: PropTypes.number
};

export default Counter;

Body:
The problem is that your components are all consuming the same quantity value stored in the parent via index.js. Your shopping cart takes the last-updated count value from any Counter and uses that to add the selected item. You need to isolate the quantity/count for each Product.

I cloned your repo and I was able to fix this by making an update to the Product.js component.

I gave Product.js its own private quantity to keep track of

class Product extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedProduct: {},
      quickViewProdcut: {},
      quantity: 1,
      isAdded: false
    };

    this.updateQuantity = this.updateQuantity.bind(this)
  }

Create an event-handler that would update its own state-quantity.

  updateQuantity(value){
    this.setState({
      quantity: value
    })
  }

Update definition of quantity in render() to use our isolated state-value instead of the value stored in the parent.

let quantity = this.state.quantity;

Pass the event-handler above as a prop to Counter

 <Counter
  productQuantity={quantity}
  updateQuantity={this.updateQuantity}
  resetQuantity={this.resetQuantity}
/>

Your feature works completely fine after integrating those changes. See below for full-code:

import React, { Component } from "react";
import Counter from "./Counter";

class Product extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedProduct: {},
      quickViewProdcut: {},
      quantity: 1,
      isAdded: false
    };

    this.updateQuantity = this.updateQuantity.bind(this)
  }

  updateQuantity(value){
    this.setState({
      quantity: value
    })
  }

  addToCart(image, name, price, id, quantity) {
    this.setState(
      {
        selectedProduct: {
          image: image,
          name: name,
          price: price,
          id: id,
          quantity: quantity
        }
      },
      function() {
        this.props.addToCart(this.state.selectedProduct);
      }
    );
    this.setState(
      {
        isAdded: true
      },
      function() {
        setTimeout(() => {
          this.setState({
            isAdded: false,
            selectedProduct: {}
          });
        }, 3500);
      }
    );
  }
  quickView(image, name, price, id) {
    this.setState(
      {
        quickViewProdcut: {
          image: image,
          name: name,
          price: price,
          id: id
        }
      },
      function() {
        this.props.openModal(this.state.quickViewProdcut);
      }
    );
  }
  render() {
    let image = this.props.image;
    let name = this.props.name;
    let price = this.props.price;
    let id = this.props.id;
    let quantity = this.state.quantity;
    return (
      <div className="product">
        <div className="product-image">
          <img
            src={image}
            alt={this.props.name}
            onClick={this.quickView.bind(
              this,
              image,
              name,
              price,
              id,
              quantity
            )}
          />
        </div>
        <h4 className="product-name">{this.props.name}</h4>
        <p className="product-price">{this.props.price}</p>
        <Counter
          productQuantity={quantity}
          updateQuantity={this.updateQuantity}
          resetQuantity={this.resetQuantity}
        />
        <div className="product-action">
          <button
            className={!this.state.isAdded ? "" : "added"}
            type="button"
            onClick={this.addToCart.bind(
              this,
              image,
              name,
              price,
              id,
              quantity
            )}
          >
            {!this.state.isAdded ? "ADD TO CART" : "✔ ADDED"}
          </button>
        </div>
      </div>
    );
  }
}

export default Product;


问:
Save results from terminal in robot framework
I am having trouble output/saving the results from my terminal commands.

```<code>*** Settings ***
Library     Process
Suite Teardown      Terminate All Processes     kill=True

*** Test Cases ***
Example
    Run Process   adb devices -l
</code>```

Current Output

Expected Output

However, if i just run adb devices -l, it will provide me with a list of android devices id.

E.g. List of devices attached
0429329319 device usb: xxxx

My attempts

Based on the robot framework, it has this example that i tried to follow but gave me errors such as "No keyword with name ${result} = Run Process found"

Sample code from robot framework

```<code>${result} = Run Process program stdout=${TEMPDIR}/stdout.txt    stderr=${TEMPDIR}/stderr.txt
Log Many    stdout: ${result.stdout}    stderr: ${result.stderr}
</code>```

Another way that i have discovered is to use 'Get Process Result' keyword.

So my question is - how do i print/save the output of my terminal commands?

Would appreciate if anyone can take a look at it

Referenced to

http://robotframework.org/robotframework/latest/libraries/Process.html

https://github.com/robotframework/robotframework/blob/master/atest/testdata/standard_libraries/process/get_process_result.robot

答:
I just found out one way would be using the OperatingSystem library - 'Run'.

Then log the results of the command entered into the terminal/command prompt using 'Log To Console'

```<code>*** Settings ***
Library             OperatingSystem

*** Test Cases ***
Get list of devices
    ${result} =     Run     adb devices -l
    Log To Console  [${result}]
</code>```

To save the printed stuff in the console, just do
robot xx.robot > console.txt

Referenced to - how to run commands in CMD prompt using robot framework

Body:
I am having trouble output/saving the results from my terminal commands.

*** Settings ***
Library     Process
Suite Teardown      Terminate All Processes     kill=True

*** Test Cases ***
Example
    Run Process   adb devices -l

Current Output

Expected Output

However, if i just run adb devices -l, it will provide me with a list of android devices id.

E.g. List of devices attached
0429329319 device usb: xxxx

My attempts

Based on the robot framework, it has this example that i tried to follow but gave me errors such as "No keyword with name ${result} = Run Process found"

Sample code from robot framework

${result} = Run Process program stdout=${TEMPDIR}/stdout.txt    stderr=${TEMPDIR}/stderr.txt
Log Many    stdout: ${result.stdout}    stderr: ${result.stderr}

Another way that i have discovered is to use 'Get Process Result' keyword.

So my question is - how do i print/save the output of my terminal commands?

Would appreciate if anyone can take a look at it

Referenced to

http://robotframework.org/robotframework/latest/libraries/Process.html

https://github.com/robotframework/robotframework/blob/master/atest/testdata/standard_libraries/process/get_process_result.robot

Body:
I just found out one way would be using the OperatingSystem library - 'Run'.

Then log the results of the command entered into the terminal/command prompt using 'Log To Console'

*** Settings ***
Library             OperatingSystem

*** Test Cases ***
Get list of devices
    ${result} =     Run     adb devices -l
    Log To Console  [${result}]

To save the printed stuff in the console, just do
robot xx.robot > console.txt

Referenced to - how to run commands in CMD prompt using robot framework


问:
How to give a space along with printing result
So, i want to create a function. If i use 4 as input number, then it will give a result:

```<code>****
 ***
  **
   *
</code>```

I use code like this.

```<code>def print_pattern(input_number):
    for i in reversed(range(input_number)):
        integer = (i+1)
        if integer == input_number:
            output = (integer * '*')
        elif integer < input_number:
            output = " " + (integer * '*')
        print(output)

print_pattern(6)
</code>```

But, the result only show the first looping like this.

```<code>****
 ***
 **
 *
</code>```

what should i do?

答:
```<code>def print_pattern(input_number):
    for i in range(input_number):
        print((" " * i) + "*" * (input_number -i))
</code>```

Examples:

```<code>>>> print_pattern(4)
****
 ***
  **
   *
>>> print_pattern(6)
******
 *****
  ****
   ***
    **
     *

</code>```

Body:
So, i want to create a function. If i use 4 as input number, then it will give a result:

****
 ***
  **
   *

I use code like this.

def print_pattern(input_number):
    for i in reversed(range(input_number)):
        integer = (i+1)
        if integer == input_number:
            output = (integer * '*')
        elif integer < input_number:
            output = " " + (integer * '*')
        print(output)

print_pattern(6)

But, the result only show the first looping like this.

****
 ***
 **
 *

what should i do?

Body:
def print_pattern(input_number):
    for i in range(input_number):
        print((" " * i) + "*" * (input_number -i))

Examples:

>>> print_pattern(4)
****
 ***
  **
   *
>>> print_pattern(6)
******
 *****
  ****
   ***
    **
     *


问:
Trying to get property 'email' of non-object
I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.

A PHP Error was encountered Severity: Notice

Message: Trying to get property 'email' of non-object

Filename: controllers/forms.php

Line Number: 26

Backtrace:

File:
  E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
  Line: 26 Function: _error_handler

File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
  Function: require_once

Below is the controller

```<code><?php
class Forms extends CI_Controller
{
    public function __construct()
    {

        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('user_model', 'auth');
    }

   public function forgot_pass()
    {
        if($this->input->post('forgot_pass'))
        {
            $email=$this->input->post('email');
            $this->load->model('user_model', 'auth');
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'E-mail', 'required');

            if ($this->form_validation->run() == TRUE) {
            $que=$this->db->query("select password,email from users where email='$email'");
            $row=$que->row();
            $user_email=$row->email;
            if((!strcmp($email, $user_email)))
            {
                $pass=$row->password;
                $to = $user_email;
                $subject = "Password";
                $txt = "Your password is $pass .";
                $headers = "From: user@testdomain.com" . "\r\n" . "CC: hamza_zon@outlook.com ";
                mail($to,$subject,$txt,$headers);
                $this->load->view('user/header');
                $this->load->view('user/confirm');
                $this->load->view('user/footer');
                }
            else{
            $data['error']="Invalid Email ID !";
            }
        }
            else{
                $data['error']="Email ID is required !";
            }
    }
            $this->load->view('user/header');
            $this->load->view('user/forgot_pass',@$data);
            $this->load->view('user/footer');

   }
}
?>
</code>```

答:
You need to handle it like this,</p>

```<code>$query = $this->db->query("select password,email from users where email=".$email);
if ($query->num_rows() > 0) {
    $row = $query->row();
    $user_email = $row->email;
} else {
    $user_email = '';
}
//then your next if condition in which you are comparing two strings
</code>```

Body:
I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.

A PHP Error was encountered Severity: Notice

Message: Trying to get property 'email' of non-object

Filename: controllers/forms.php

Line Number: 26

Backtrace:

File:
  E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
  Line: 26 Function: _error_handler

File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
  Function: require_once

Below is the controller

<?php
class Forms extends CI_Controller
{
    public function __construct()
    {

        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('user_model', 'auth');
    }

   public function forgot_pass()
    {
        if($this->input->post('forgot_pass'))
        {
            $email=$this->input->post('email');
            $this->load->model('user_model', 'auth');
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'E-mail', 'required');

            if ($this->form_validation->run() == TRUE) {
            $que=$this->db->query("select password,email from users where email='$email'");
            $row=$que->row();
            $user_email=$row->email;
            if((!strcmp($email, $user_email)))
            {
                $pass=$row->password;
                $to = $user_email;
                $subject = "Password";
                $txt = "Your password is $pass .";
                $headers = "From: user@testdomain.com" . "\r\n" . "CC: hamza_zon@outlook.com ";
                mail($to,$subject,$txt,$headers);
                $this->load->view('user/header');
                $this->load->view('user/confirm');
                $this->load->view('user/footer');
                }
            else{
            $data['error']="Invalid Email ID !";
            }
        }
            else{
                $data['error']="Email ID is required !";
            }
    }
            $this->load->view('user/header');
            $this->load->view('user/forgot_pass',@$data);
            $this->load->view('user/footer');

   }
}
?>

Body:
You need to handle it like this,

$query = $this->db->query("select password,email from users where email=".$email);
if ($query->num_rows() > 0) {
    $row = $query->row();
    $user_email = $row->email;
} else {
    $user_email = '';
}
//then your next if condition in which you are comparing two strings


答:
Another data.table approach...

```<code>#first, clculate the difference between months, by student.
ans <- DT[, diff := shift( Month, type = "lead" ) - Month ), by = .(Student)]
#then filter rows that are at the start of 2 consecutive differences of 1
#also, drop the temporary diff-column
ans[ diff == 1 & shift( diff, type = "lead" ) == 1,][, diff := NULL][]
</code>```

voila

```<code>#    Student Month
# 1:       1     1
# 2:       1     5
# 3:       1     6
# 4:       2     2
# 5:       2     3
# 6:       2     7
# 7:       2     8
# 8:       3     1
# 9:       3     5
# 10:      3     6
# 11:      3     7
</code>```

Title: Identify groups of n consecutive numbers in a data.table field in a group

Body:
This data.table shows the months of year attended by students.

DT = data.table(
 Student = c(1, 1, 1, 1, 1, 1, 1, 1, 1,
             2, 2, 2, 2, 2, 2, 2, 2,
             3, 3, 3, 3, 3, 3, 3, 3),
 Month   = c(1, 2, 3, 5, 6, 7, 8, 11, 12,
             2, 3, 4, 5, 7, 8, 9, 10,
             1, 2, 3, 5, 6, 7, 8, 9))

DT
    Student Month
 1:       1     1
 2:       1     2
 3:       1     3
 4:       1     5
 5:       1     6
 6:       1     7
 7:       1     8
 8:       1    11
 9:       1    12
10:       2     2
11:       2     3
12:       2     4
13:       2     5
14:       2     7
15:       2     8
16:       2     9
17:       2    10
18:       3     1
19:       3     2
20:       3     3
21:       3     5
22:       3     6
23:       3     7
24:       3     8
25:       3     9

I want to identify periods of three consecutive months (identified by the first month in the period). This is visualization of the data table and the eligible periods.

       1   2   3   4   5   6   7   8   9   10  11  12

1      *   *   *       *   *   *   *           *   *
       [-------]       [-------]
                           [-------]

2          *   *   *   *       *   *   *   *
           [-------]           [-------]
               [-------]           [-------]

3      *   *   *       *   *   *   *   *
       [-------]       [-------]
                           [-------]
                               [-------]

Desired output:

id   First_month_in_the_period

1    1
1    5
1    6
2    2
2    3
2    7
2    8
3    1
3    5
3    6
3    7

Looking for data.table (or dplyr) solutions.

Body:
Another data.table approach...

#first, clculate the difference between months, by student.
ans <- DT[, diff := shift( Month, type = "lead" ) - Month ), by = .(Student)]
#then filter rows that are at the start of 2 consecutive differences of 1
#also, drop the temporary diff-column
ans[ diff == 1 & shift( diff, type = "lead" ) == 1,][, diff := NULL][]

voila

#    Student Month
# 1:       1     1
# 2:       1     5
# 3:       1     6
# 4:       2     2
# 5:       2     3
# 6:       2     7
# 7:       2     8
# 8:       3     1
# 9:       3     5
# 10:      3     6
# 11:      3     7