问:
Adding a map of string vector and different datatype vector
As suggested in https://stackoverflow.com/a/44884240/3782963. I created a method of return type std::map<std::string, Spikes::data> get_data1(). I create a struct called data:

```<code>struct data {

            std::vector<Eigen::MatrixXd> samples;
            std::vector<std::string> sample_names;
            int index = -1;
        };
</code>```

and placed it in my namespace and out of the class FileReader.

My method looks like:

```<code>std::map<std::string, Spikes::data> FileReader::get_data1() {
    std::map<std::string, Spikes::data> content;

    std::vector<Eigen::MatrixXd> samples;
    std::vector<std::string> sample_names;

    for (auto i : list_dir()) {
        if (contains_number(i)) {
            samples.push_back(load_csv(location + "/" + i));
            sample_names.push_back(i);
        }
    }

    content.emplace(std::make_pair("samples", Spikes::data{samples,0}));
    content.emplace(std::make_pair("sample_names", Spikes::data{sample_names,1}));

    return content;
</code>```

And in my main.cpp I am calling this method as:

```<code>for (auto i:a.get_data1()["samples"].samples){
        std::cout<<i;
    }
</code>```

But I get the following errors:

```<code>/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp: In member function 'std::map<std::basic_string<char>, Spikes::data> Spikes::FileReader::get_data1()':
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:154:69: error: no matching function for call to 'Spikes::data::data(<brace-enclosed initializer list>)'
     content.emplace(std::make_pair("samples", Spikes::data{samples,0}));
                                                                     ^
In file included from /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:3:0:
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data()
     struct data {
            ^
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 0 arguments, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(const Spikes::data&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(Spikes::data&&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:155:79: error: no matching function for call to 'Spikes::data::data(<brace-enclosed initializer list>)'
     content.emplace(std::make_pair("sample_names", Spikes::data{sample_names,1}));
                                                                               ^
In file included from /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:3:0:
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data()
     struct data {
            ^
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 0 arguments, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(const Spikes::data&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(Spikes::data&&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
</code>```

I have no clue as to what is going on.

I have even tried doing:

```<code>content["samples"] = Spikes::data{samples,0};
content["sample_names"] = Spikes::data{sample_names,1};
</code>```

I still get the same error. Any help would be highly appreciated.

答:
As suggested in https://stackoverflow.com/a/44884240/3782963. I created a method of return type std::map get_data1().

The suggested answer clearly states that you need to implement constructors for data:

```<code>struct data
{
    // constructors... <- here

    std::vector<Eigen::MatrixXd> samples;
    std::vector<std::string> names;
    int index = -1;
};
</code>```

@SamVarshavchik described the reason well.

I assume your intention would be having constructors as follows:

```<code>// Constructors
data(std::vector<Eigen::MatrixXd> && rhs, int idx)
{
    samples = std::move(rhs);
    index = idx;
}

data(std::vector<std::string> && rhs, int idx)
{
    samples = std::move(rhs);
    index = idx;
}

content.emplace(std::make_pair("samples", Spikes::data{ std::move(samples), 0}));
content.emplace(std::make_pair("sample_names", Spikes::data{ std::move(sample_names), 1}));
</code>```

Body:
As suggested in https://stackoverflow.com/a/44884240/3782963. I created a method of return type std::map<std::string, Spikes::data> get_data1(). I create a struct called data:

struct data {

            std::vector<Eigen::MatrixXd> samples;
            std::vector<std::string> sample_names;
            int index = -1;
        };

and placed it in my namespace and out of the class FileReader.

My method looks like:

std::map<std::string, Spikes::data> FileReader::get_data1() {
    std::map<std::string, Spikes::data> content;

    std::vector<Eigen::MatrixXd> samples;
    std::vector<std::string> sample_names;

    for (auto i : list_dir()) {
        if (contains_number(i)) {
            samples.push_back(load_csv(location + "/" + i));
            sample_names.push_back(i);
        }
    }

    content.emplace(std::make_pair("samples", Spikes::data{samples,0}));
    content.emplace(std::make_pair("sample_names", Spikes::data{sample_names,1}));

    return content;

And in my main.cpp I am calling this method as:

for (auto i:a.get_data1()["samples"].samples){
        std::cout<<i;
    }

But I get the following errors:

/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp: In member function 'std::map<std::basic_string<char>, Spikes::data> Spikes::FileReader::get_data1()':
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:154:69: error: no matching function for call to 'Spikes::data::data(<brace-enclosed initializer list>)'
     content.emplace(std::make_pair("samples", Spikes::data{samples,0}));
                                                                     ^
In file included from /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:3:0:
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data()
     struct data {
            ^
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 0 arguments, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(const Spikes::data&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(Spikes::data&&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:155:79: error: no matching function for call to 'Spikes::data::data(<brace-enclosed initializer list>)'
     content.emplace(std::make_pair("sample_names", Spikes::data{sample_names,1}));
                                                                               ^
In file included from /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:3:0:
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data()
     struct data {
            ^
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 0 arguments, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(const Spikes::data&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(Spikes::data&&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided

I have no clue as to what is going on.

I have even tried doing:

content["samples"] = Spikes::data{samples,0};
content["sample_names"] = Spikes::data{sample_names,1};

I still get the same error. Any help would be highly appreciated.

Body:
As suggested in https://stackoverflow.com/a/44884240/3782963. I created a method of return type std::map get_data1().

The suggested answer clearly states that you need to implement constructors for data:

struct data
{
    // constructors... <- here

    std::vector<Eigen::MatrixXd> samples;
    std::vector<std::string> names;
    int index = -1;
};

@SamVarshavchik described the reason well.

I assume your intention would be having constructors as follows:

// Constructors
data(std::vector<Eigen::MatrixXd> && rhs, int idx)
{
    samples = std::move(rhs);
    index = idx;
}

data(std::vector<std::string> && rhs, int idx)
{
    samples = std::move(rhs);
    index = idx;
}

content.emplace(std::make_pair("samples", Spikes::data{ std::move(samples), 0}));
content.emplace(std::make_pair("sample_names", Spikes::data{ std::move(sample_names), 1}));


来源: stackexchange

问:
"identifier is undefined" when calling function from a header file
All I'm trying to do is create a separate class to hold my Hello World function (this is for a class), but I am getting an "identifier is undefined" compiler error. What is the issue?

Here is my main function (helloworld.cpp):

```<code>#include <iostream>
using namespace std;

int main() {
    print_me();
    system("pause");
    return 0;
}
</code>```

And here is the header class (helloworld.h) :

```<code>#include <iostream>

void print_me() {
    std::cout << "Hello World\n";
}
</code>```

答:
You have not included helloworld.h in helloworld.cpp. The following code should work:

```<code>#include <iostream>
#include "helloworld.h"

using namespace std;

int main() {
     print_me();
     system("pause");
     return 0;
}
</code>```

One thing to remember is from your compiler's point of view,  there is no connection between the two files unless you specify it. The fact that both files have the same name does not have any significance for compiler.

Side note 1: Consider using include guards in your header files. For simple projects, it may not be obviously necessary but for larger projects, not using them can lead to annoying ambiguous compilation errors.

Side note 2: Implementing function bodies in header files is generally discouraged.

ContentLicense: CC BY-SA 3.0

Body:
All I'm trying to do is create a separate class to hold my Hello World function (this is for a class), but I am getting an "identifier is undefined" compiler error. What is the issue?

Here is my main function (helloworld.cpp):

#include <iostream>
using namespace std;

int main() {
    print_me();
    system("pause");
    return 0;
}

And here is the header class (helloworld.h) :

#include <iostream>

void print_me() {
    std::cout << "Hello World\n";
}

Body:
You have not included helloworld.h in helloworld.cpp. The following code should work:

#include <iostream>
#include "helloworld.h"

using namespace std;

int main() {
     print_me();
     system("pause");
     return 0;
}

One thing to remember is from your compiler's point of view,  there is no connection between the two files unless you specify it. The fact that both files have the same name does not have any significance for compiler.

Side note 1: Consider using include guards in your header files. For simple projects, it may not be obviously necessary but for larger projects, not using them can lead to annoying ambiguous compilation errors.

Side note 2: Implementing function bodies in header files is generally discouraged.


问:
Spring Boot + Spring Data JPA + H2:Error creating bean with name 'entityManagerFactory' defined in class path resource
I am new to Spring Boot and Maven and I am trying to run a simple project based from the Spring Data JPA guide but I am getting the following error. I have checked all over the forum but I couldn't find a solution that fit my problem. In the pom file posted, I already see these dependencies in the Effective POM tab in STS with the version numbers, which comes from what is in the  tag of the pom file posted so I am not sure why I still have to put them into the pom file I posted as well. Does anyone know what I am missing or doing wrong here?

I am getting the following:

```<code>    Error starting ApplicationContext. To display the auto-configuration    report re-run your application with 'debug' enabled.
2017-06-12 23:14:30.076 ERROR 14936 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at com.sample.Main.main(Main.java:27) [classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 33 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 46 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter.<init>(HibernateJpaVendorAdapter.java:64) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration.createJpaVendorAdapter(HibernateJpaAutoConfiguration.java:98) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:103) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$5a3bc59a.CGLIB$jpaVendorAdapter$4(<generated>) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$5a3bc59a$$FastClassBySpringCGLIB$$ec13a313.invoke(<generated>) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$5a3bc59a.jpaVendorAdapter(<generated>) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 47 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_45]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_45]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_45]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_45]
    ... 60 common frames omitted
</code>```

Application Start

```<code>package com.sample;

import java.util.Arrays;
import java.util.Collection;

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

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class Main {

  public static void main(String[] args) throws Exception {

        SpringApplication.run(Main.class, args);

    }

  @Bean
  CommandLineRunner runner(StudentRepository student){
      return args ->{
          Arrays.asList("John, Cathy, David, Jeff".split(","))
          .forEach(s -> student.save(new Student(s)));

          student.findAll().forEach(System.out::println);
          student.findByName("John").forEach(System.out::println);

      };
  }
}

interface StudentRepository extends JpaRepository<Student, Long>  {

    //select * from student where name = :name
    Collection<Student> findByName(String name);
}

//JPA Entity will be mapped to a table named Student.
@Entity
class Student {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    //for JPA, you don't use it directly
    protected Student() {

    }

    public Student(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }
}
</code>```

pom.xml

```<code>    <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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.spring.sample.projects</groupId>
  <artifactId>SpringBootSample</artifactId>
  <packaging>jar</packaging>
  <version>1.0.0-SNAPSHOT</version>
  <name>SpringBootSample</name>
  <url>http://maven.apache.org</url>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
   </parent>
   <properties>
    <java.version>1.8</java.version>
   </properties>
  <dependencies>
     <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
      </dependency>
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
      </dependency>
      <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
      </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringBootSample</finalName>

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

  <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>
</code>```

答:
I found the answer. I had to explicitly use an new dependency for hibernate-core for spring boot 1.5.4. The 4.2.x version works as well, but I wanted to go with the newer one.</p>

```<code><dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
  </dependency>
</code>```

Body:
I am new to Spring Boot and Maven and I am trying to run a simple project based from the Spring Data JPA guide but I am getting the following error. I have checked all over the forum but I couldn't find a solution that fit my problem. In the pom file posted, I already see these dependencies in the Effective POM tab in STS with the version numbers, which comes from what is in the  tag of the pom file posted so I am not sure why I still have to put them into the pom file I posted as well. Does anyone know what I am missing or doing wrong here?

I am getting the following:

    Error starting ApplicationContext. To display the auto-configuration    report re-run your application with 'debug' enabled.
2017-06-12 23:14:30.076 ERROR 14936 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at com.sample.Main.main(Main.java:27) [classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 33 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 46 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/hibernate/HibernateException
    at org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter.<init>(HibernateJpaVendorAdapter.java:64) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration.createJpaVendorAdapter(HibernateJpaAutoConfiguration.java:98) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:103) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$5a3bc59a.CGLIB$jpaVendorAdapter$4(<generated>) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$5a3bc59a$$FastClassBySpringCGLIB$$ec13a313.invoke(<generated>) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$5a3bc59a.jpaVendorAdapter(<generated>) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 47 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_45]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_45]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_45]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_45]
    ... 60 common frames omitted

Application Start

package com.sample;

import java.util.Arrays;
import java.util.Collection;

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

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class Main {

  public static void main(String[] args) throws Exception {

        SpringApplication.run(Main.class, args);

    }

  @Bean
  CommandLineRunner runner(StudentRepository student){
      return args ->{
          Arrays.asList("John, Cathy, David, Jeff".split(","))
          .forEach(s -> student.save(new Student(s)));

          student.findAll().forEach(System.out::println);
          student.findByName("John").forEach(System.out::println);

      };
  }
}

interface StudentRepository extends JpaRepository<Student, Long>  {

    //select * from student where name = :name
    Collection<Student> findByName(String name);
}

//JPA Entity will be mapped to a table named Student.
@Entity
class Student {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    //for JPA, you don't use it directly
    protected Student() {

    }

    public Student(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }
}

pom.xml

    <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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.spring.sample.projects</groupId>
  <artifactId>SpringBootSample</artifactId>
  <packaging>jar</packaging>
  <version>1.0.0-SNAPSHOT</version>
  <name>SpringBootSample</name>
  <url>http://maven.apache.org</url>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
   </parent>
   <properties>
    <java.version>1.8</java.version>
   </properties>
  <dependencies>
     <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
      </dependency>
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
      </dependency>
      <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
      </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringBootSample</finalName>

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

  <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

Body:
I found the answer. I had to explicitly use an new dependency for hibernate-core for spring boot 1.5.4. The 4.2.x version works as well, but I wanted to go with the newer one.

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
  </dependency>


问:
What construction can I use instead of Contains?
I have a list with ids:

```<code>var myList = new List<int>();
</code>```

I want to select all objects from db with ids from myList:

```<code>var objList= myContext.MyObjects.Where(t => myList.Contains(t.Id)).ToList();
</code>```

But when myList.Count > 8000 i get an error:

The query processor ran out of internal resources and could not
  produce a query plan.   This is a rare event and only expected for
  extremely complex queries or queries that reference a very large
  number of tables or partitions.   Please simplify the query. If you
  believe you have received this message in error, contact Customer
  Support Services for more information.

I think that it's because i used Contains(). What can I use instead of Contains?

答:
Why not try</p>

```<code>var objList= from obj in myContext.MyObjects
     join myId in myList on obj.Id equals myId
     select obj;
</code>```

Body:
I have a list with ids:

var myList = new List<int>();

I want to select all objects from db with ids from myList:

var objList= myContext.MyObjects.Where(t => myList.Contains(t.Id)).ToList();

But when myList.Count > 8000 i get an error:

The query processor ran out of internal resources and could not
  produce a query plan.   This is a rare event and only expected for
  extremely complex queries or queries that reference a very large
  number of tables or partitions.   Please simplify the query. If you
  believe you have received this message in error, contact Customer
  Support Services for more information.

I think that it's because i used Contains(). What can I use instead of Contains?

Body:
Why not try

var objList= from obj in myContext.MyObjects
     join myId in myList on obj.Id equals myId
     select obj;


问:
HTTP Error 401: Unauthorized
Again stucked with tweepy.

I got an app that uses tweepy oauth authentication and follows step by step the instructions from the tutorial:

http://joshthecoder.github.com/tweepy/docs/auth_tutorial.html#oauth-authentication

This app was working correctly, but now, is only returning the same exception in any user attempt to authenticate, even with new accounts.

I have spent a few hours on this and I can't get a solution.

Any idea?

```<code>HTTP Error 401: Unauthorized
Request Method: GET
Request URL: http://(hidden)/?oauth_token=FSL76eId7n64I1ACX1EKBHIV504xlZmQjJg8iO3Bc&oauth_verifier=KVjaxpzFn40JCXvk4r5cDNVbdILaiuF5szv6yBcpQo
Django Version: 1.2.1
Exception Type: TweepError
Exception Value: HTTP Error 401: Unauthorized

Exception Location: /(hidden)/tweepy/auth.py in get_access_token, line 126
Python Executable: /usr/local/bin/python
Python Version: 2.6.5
</code>```

答:
One guess may be the accounts are blocked try using cURL to figure out if you are blacklisted, in which case Twitter probably won't have notified you of this. Alternatively, try another module: http://dev.twitter.com/pages/oauth_libraries

for cURL do the following:

```<code>curl  -i -u  my_account:fuuu! http://api.twitter.com/1/account/rate_limit_status.json -v
</code>```

Where my_account is your Twitter account. Hope that helps.

ContentLicense: CC BY-SA 2.5

Title: HTTP Error 401: Unauthorized

Body:
Again stucked with tweepy.

I got an app that uses tweepy oauth authentication and follows step by step the instructions from the tutorial:

http://joshthecoder.github.com/tweepy/docs/auth_tutorial.html#oauth-authentication

This app was working correctly, but now, is only returning the same exception in any user attempt to authenticate, even with new accounts.

I have spent a few hours on this and I can't get a solution.

Any idea?

HTTP Error 401: Unauthorized
Request Method: GET
Request URL: http://(hidden)/?oauth_token=FSL76eId7n64I1ACX1EKBHIV504xlZmQjJg8iO3Bc&oauth_verifier=KVjaxpzFn40JCXvk4r5cDNVbdILaiuF5szv6yBcpQo
Django Version: 1.2.1
Exception Type: TweepError
Exception Value: HTTP Error 401: Unauthorized

Exception Location: /(hidden)/tweepy/auth.py in get_access_token, line 126
Python Executable: /usr/local/bin/python
Python Version: 2.6.5

Body:
One guess may be the accounts are blocked try using cURL to figure out if you are blacklisted, in which case Twitter probably won't have notified you of this. Alternatively, try another module: http://dev.twitter.com/pages/oauth_libraries

for cURL do the following:

curl  -i -u  my_account:fuuu! http://api.twitter.com/1/account/rate_limit_status.json -v

Where my_account is your Twitter account. Hope that helps.


问:
Angular 2 : Define global constants for api endpoints
I am  new in Angular2. I would like to have a single class or a configuration file having all my API endpoints (allowing parameters and such in the different routes) that I could inject in all my services. What's the best way to do so in Angular2. I mean, should I define an @Injectable class as you would do when defining a service (and then add it to my services'PROVIDERS).

The problem that I found is when I will deploy my api on a server in the client part I must change all endpoint called in string format so it will be wasted time if I have many endpoints to work with.

in this example I call a service with an endpoint in string format :

```<code>getData() {
    return this._http.get('http://localhost:8000/cartography')
      .map(function(res) {
        const jsonArray = res.json();
        const newJsonArr = [];
        for ( let i = 0; i < jsonArray.length; i++) {
          const object = {
            post_name : jsonArray[i].name,
            employment_name : jsonArray[i].employment.name,
            profession_name : jsonArray[i].employment.profession.name,
            family_name : jsonArray[i].employment.profession.family.name
          };
          newJsonArr.push(object);
        }
          return newJsonArr;
      });
  }
</code>```

so I'm looking for a way to define it as global var in a class or config file.
any help please ! thanks .

答:
I am wondering you are looking for something like interceptor or helper. And global variable.

1) You can define global string variables inside environment[.prod].ts file.

You can import those variables by

import { environment } from 'environments/environment';

this code.and use as below

environment.baseURL...;

2) Regarding to the header and body, also parameters of http request you can create new service extends from HTTP.

```<code>@Injectable()
export class HttpHelperService {

  constructor(
    private http: Http
  ) { }

  private generateReqOptions(isUrlEncoded = false, requiredAuth = false, customHeader?: Headers , customParam?: Object): RequestOptions {
...
  }

  get(url: string, query: Object, requiredAuth = false, headers?: Headers): Observable<any> {
...
  }

  post(url: string, body: any, isUrlEncoded = false, requiredAuth = false, headers?: Headers): Observable<any> {
...
  }

  private handleError (error: Response | any) {
    ...
  }
}
</code>```

You can add custom handling functions like this.

And make http request as below.

```<code>  constructor(
    private http: HttpHelperService
  ) { }

  getReasons() {
    return this.http.get(...)
      .map(x => x.json())
  }
</code>```

I hope this will help you.

Body:
I am  new in Angular2. I would like to have a single class or a configuration file having all my API endpoints (allowing parameters and such in the different routes) that I could inject in all my services. What's the best way to do so in Angular2. I mean, should I define an @Injectable class as you would do when defining a service (and then add it to my services'PROVIDERS).

The problem that I found is when I will deploy my api on a server in the client part I must change all endpoint called in string format so it will be wasted time if I have many endpoints to work with.

in this example I call a service with an endpoint in string format :

getData() {
    return this._http.get('http://localhost:8000/cartography')
      .map(function(res) {
        const jsonArray = res.json();
        const newJsonArr = [];
        for ( let i = 0; i < jsonArray.length; i++) {
          const object = {
            post_name : jsonArray[i].name,
            employment_name : jsonArray[i].employment.name,
            profession_name : jsonArray[i].employment.profession.name,
            family_name : jsonArray[i].employment.profession.family.name
          };
          newJsonArr.push(object);
        }
          return newJsonArr;
      });
  }

so I'm looking for a way to define it as global var in a class or config file.
any help please ! thanks .

Body:
I am wondering you are looking for something like interceptor or helper. And global variable.

1) You can define global string variables inside environment[.prod].ts file.

You can import those variables by

import { environment } from 'environments/environment';

this code.and use as below

environment.baseURL...;

2) Regarding to the header and body, also parameters of http request you can create new service extends from HTTP.

@Injectable()
export class HttpHelperService {

  constructor(
    private http: Http
  ) { }

  private generateReqOptions(isUrlEncoded = false, requiredAuth = false, customHeader?: Headers , customParam?: Object): RequestOptions {
...
  }

  get(url: string, query: Object, requiredAuth = false, headers?: Headers): Observable<any> {
...
  }

  post(url: string, body: any, isUrlEncoded = false, requiredAuth = false, headers?: Headers): Observable<any> {
...
  }

  private handleError (error: Response | any) {
    ...
  }
}

You can add custom handling functions like this.

And make http request as below.

  constructor(
    private http: HttpHelperService
  ) { }

  getReasons() {
    return this.http.get(...)
      .map(x => x.json())
  }

I hope this will help you.


问:
Is Rectangle A = Rectangle(3, 4); equivalent to Rectangle A(3,4);?
Below is my code:

```<code>#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
 public:
  Rectangle(int, int);
  int area() { return (width * height); }
};

Rectangle::Rectangle(int a, int b) {

  width = a;
  height = b;
}

int main() {
  Rectangle A(3, 4);
  Rectangle B = Rectange(3,4);
  return 0;
}
</code>```

I didn't define any copy constructors or assignment operator for Rectangle class.

Is it true that Rectangle B = Rectangle(3, 4); actually does three things in serial?

Allocate memory space for a temporary variable (let's use tmp to denote it) of Rectangle, call Rectangle::Rectangle(3, 4) to intialize it.

Allocate memory space for variable B, initialize it with the default constructor

(memberwise) Copy tmp to B with the assignment operator Rectangle& operator = (const Rectangle &)

Does that explanation make sense? I think I might understand wrongly because this process looks very clumsy and inefficient compared with Rectangle A(3, 4);.

Does anyone have ideas about this? Is it true that Rectangle A(3,4) is equivalent to Rectangle A = Rectangle(3, 4);? Thanks!

答:
Rectangle A(3, 4); always simply invokes the Rectangle(int, int) constructor, throughout all of the history of C++ having constructors. Simple. Boring.

Now for the fun part.

C++17

In the newest (as of this writing) edition of the standard, Rectangle B = Rectangle(3,4); immediately collapses down into Rectangle B(3,4); This happens regardless of what the nature of Rectangle's move or copy constructors is. This feature is commonly referred to as guaranteed copy elision, although it's important to stress that there is no copy and no move here. What happens is B is direct-initialized from (3,4).

pre-C++17

Before C++17, there is a temporary Rectangle constructed that a compiler may optimize away (and by may, I mean it will certainly, unless you tell it not to). But your ordering of events is not correct. It's important to note that no assignment happens here. We are not assigning to B. We are constructing B. Code of the form:

```<code>T var = expr;
</code>```

is copy-initialization, it is not copy-assignment. Hence, we do two things:

We construct a temporary Rectangle using the Rectangle(int, int) constructor

That temporary binds directly to the reference in the implicitly generated move (or copy, pre-C++11) constructor, which is then invoked - doing a member-wise move (or copy) from the temporary. (Or, more precisely, overload resolution selects the best Rectangle constructor given a prvalue of type Rectangle)

The temporary is destroyed at the statement.

If the move constructor is deleted (or, pre-C++11, the copy constructor is marked private), then trying to construct B in this way is ill-formed. If the special member functions are left alone (as they are in this example), the two declarations of A of B will certainly compile to the same code.

The form of initialization in B may look more familiar if you actually drop the type:

```<code>auto B = Rectangle(3,4);
</code>```

This is the so-called AAA (Almost Always Auto) style of declarations that Herb Sutter is a fan of. This does exactly the same thing as Rectangle B = Rectangle(3, 4), just with the leading step of first deducing the type of B as Rectangle.

Body:
Below is my code:

#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
 public:
  Rectangle(int, int);
  int area() { return (width * height); }
};

Rectangle::Rectangle(int a, int b) {

  width = a;
  height = b;
}

int main() {
  Rectangle A(3, 4);
  Rectangle B = Rectange(3,4);
  return 0;
}

I didn't define any copy constructors or assignment operator for Rectangle class.

Is it true that Rectangle B = Rectangle(3, 4); actually does three things in serial?

Allocate memory space for a temporary variable (let's use tmp to denote it) of Rectangle, call Rectangle::Rectangle(3, 4) to intialize it.

Allocate memory space for variable B, initialize it with the default constructor

(memberwise) Copy tmp to B with the assignment operator Rectangle& operator = (const Rectangle &)

Does that explanation make sense? I think I might understand wrongly because this process looks very clumsy and inefficient compared with Rectangle A(3, 4);.

Does anyone have ideas about this? Is it true that Rectangle A(3,4) is equivalent to Rectangle A = Rectangle(3, 4);? Thanks!

Body:
Rectangle A(3, 4); always simply invokes the Rectangle(int, int) constructor, throughout all of the history of C++ having constructors. Simple. Boring.

Now for the fun part.

C++17

In the newest (as of this writing) edition of the standard, Rectangle B = Rectangle(3,4); immediately collapses down into Rectangle B(3,4); This happens regardless of what the nature of Rectangle's move or copy constructors is. This feature is commonly referred to as guaranteed copy elision, although it's important to stress that there is no copy and no move here. What happens is B is direct-initialized from (3,4).

pre-C++17

Before C++17, there is a temporary Rectangle constructed that a compiler may optimize away (and by may, I mean it will certainly, unless you tell it not to). But your ordering of events is not correct. It's important to note that no assignment happens here. We are not assigning to B. We are constructing B. Code of the form:

T var = expr;

is copy-initialization, it is not copy-assignment. Hence, we do two things:

We construct a temporary Rectangle using the Rectangle(int, int) constructor

That temporary binds directly to the reference in the implicitly generated move (or copy, pre-C++11) constructor, which is then invoked - doing a member-wise move (or copy) from the temporary. (Or, more precisely, overload resolution selects the best Rectangle constructor given a prvalue of type Rectangle)

The temporary is destroyed at the statement.

If the move constructor is deleted (or, pre-C++11, the copy constructor is marked private), then trying to construct B in this way is ill-formed. If the special member functions are left alone (as they are in this example), the two declarations of A of B will certainly compile to the same code.

The form of initialization in B may look more familiar if you actually drop the type:

auto B = Rectangle(3,4);

This is the so-called AAA (Almost Always Auto) style of declarations that Herb Sutter is a fan of. This does exactly the same thing as Rectangle B = Rectangle(3, 4), just with the leading step of first deducing the type of B as Rectangle.


问:
ensure that current user can make changes only to his data django/python
I want that only current user can make changes only to his data in django

for example activate/desactivate content tha he created..

this my view function for activating a product :

```<code>def Activer(request, produit_id):
   produit = Produit.objects.get(pk=produit_id)
   produit.etat = "active"
   produit.save()
   return JsonResponse({'success':True})
</code>```

and this is my code in produit.html :

```<code>{% if produit.etat == "active" %}
</code>```

however this is accessible for all user ..

答:
It might be better to simply use update() rather than doing a select, update, save:

```<code>@login_required
def Activer(request, produit_id):
    count = Produit.objects.filter(pk=produit_id, user=request.user).update(etat='active')
    return JsonResponse({'success': count == 1}
</code>```

This has the advantage of avoiding a potential race condition that might occur in between loading the object from the database and subsequently saving it back.

Body:
I want that only current user can make changes only to his data in django

for example activate/desactivate content tha he created..

this my view function for activating a product :

def Activer(request, produit_id):
   produit = Produit.objects.get(pk=produit_id)
   produit.etat = "active"
   produit.save()
   return JsonResponse({'success':True})

and this is my code in produit.html :

{% if produit.etat == "active" %}

however this is accessible for all user ..

Body:
It might be better to simply use update() rather than doing a select, update, save:

@login_required
def Activer(request, produit_id):
    count = Produit.objects.filter(pk=produit_id, user=request.user).update(etat='active')
    return JsonResponse({'success': count == 1}

This has the advantage of avoiding a potential race condition that might occur in between loading the object from the database and subsequently saving it back.


问:
Preventing cheating for on-line arcade high score board
I'm going to be developing an online arcade for HTML5/Javascript games written in a to-be-released IDE.

The game will use Ajax requests to the server to record scores when people play these games.

I theoretically have complete control over the design of this, including the mechanics of the code that logs the high scores, game code, everything.

I know it's never impossible to hack client side games such as this or spoof high scores, but I want to make it difficult enough so that anyone competent enough wont be bothered enough to do it (wishful thinking).

I've read:

How can you prevent bogus high scores from appearing on a global high score list?

Which is a slightly different question as this is HTML/JS specific.

My initial idea is that the ajax request checks the source of the request is from the correct location, which is a simple and effective block for most hacking attempts.

答:
Here is one way that is both pretty simple (though not trivial) to implement and very hard to hack and not so simple to hack.

On the server side, have list of let's say 1000 items stored in either text file or database.

Each item will be unique GUID or other unique long string, let's call each item key.

Now, when you send AJAX request send one of those keys as well.. it can be random from the list or by incrementing index it doesn't matter.

Now comes the nice part: after one single "use" of each key (meaning the server got request with that key and responded to it), remove the key from the file/database. If the server get request with key that does not exist in the list, of course throw error or return "no hacking" string.

When the list becomes empty, recreate it with fresh unique keys.

This way the first request with the real key should succeed as usual, but if the user will try calling again to the same request exactly, it will fail. Guessing the keys is also very hard assuming those are long random values.

Like any other way, it's flawed due to depending on client side code that can be spoofed by those who know how. But as it's not common, it will be harder for the common folk to find how this works and hack it.


问:
Google Sheets - date auto populate when column in specific sheet is edited
Hey I need some help with Google Sheets
In sheet 1 "Inventory" I am trying to have the date auto populate in column 8 or I when data is entered in any cell in column 7 or G below row 3

this is what I have tried/as far as I have gotten

```<code>    function onEdit(e) {
  if (e.range.columnStart == 7 || e.range.rowStart < 4) return;
  e.source.getActiveSheet().getRange(e.range.rowStart, 9)
        .setValue(Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy"));
}
</code>```

Thank you for any help!!

答:
Ended up using this: </p>

```<code> function onEdit() {
 var s = SpreadsheetApp.getActiveSheet();
 if( s.getName() == "Inventory" ) { //checks that we're on the correct sheet
   var r = s.getActiveCell();
   if( r.getColumn() == 7 ) { //checks the column
   var nextCell = r.offset(0, +2);
      if( nextCell.getValue() === '' ) //is empty?
        nextCell.setNumberFormat("MMM dd/YY")
        nextCell.setValue(new Date());
   };
 };
}
</code>```

Body:
Hey I need some help with Google Sheets
In sheet 1 "Inventory" I am trying to have the date auto populate in column 8 or I when data is entered in any cell in column 7 or G below row 3

this is what I have tried/as far as I have gotten

    function onEdit(e) {
  if (e.range.columnStart == 7 || e.range.rowStart < 4) return;
  e.source.getActiveSheet().getRange(e.range.rowStart, 9)
        .setValue(Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy"));
}

Thank you for any help!!

Body:
Ended up using this:

 function onEdit() {
 var s = SpreadsheetApp.getActiveSheet();
 if( s.getName() == "Inventory" ) { //checks that we're on the correct sheet
   var r = s.getActiveCell();
   if( r.getColumn() == 7 ) { //checks the column
   var nextCell = r.offset(0, +2);
      if( nextCell.getValue() === '' ) //is empty?
        nextCell.setNumberFormat("MMM dd/YY")
        nextCell.setValue(new Date());
   };
 };
}


问:
Serialize an object directly to a JObject instead of to a string in json.net
How might one serialize an object directly to a JObject instance in JSON.Net? What is typically done is to convert the object directly to a json string like so:

```<code>string jsonSTRINGResult = JsonConvert.SerializeObject(someObj);
</code>```

One could then deserialize that back to a JObject as follows:

```<code>JObject jObj = JsonConvert.DeserializeObject<JObject>(jsonSTRINGResult);
</code>```

That seems to work, but it would seem like this way has a double performance hit (serialize and then deserialize). Does SerializeObject internally use a JObject that can be accessed somehow? Or is there some way to just serialize directly to a JObject?

答:
Please note that the JObject route suggested in Eser's accepted answer will work only for non-array CLR objects. It results in below exception if you try converting an Array object to JObject:

An unhandled exception of type 'System.InvalidCastException' occurred
in Newtonsoft.Json.dll

Additional information: Unable to cast object of type
'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.

So in case it is an array object, then you should use JArray instead as shown in the code snippet below:

```<code>using Newtonsoft.Json.Linq;

JArray jArray = JArray.FromObject(someArrayObject);
</code>```

Body:
How might one serialize an object directly to a JObject instance in JSON.Net? What is typically done is to convert the object directly to a json string like so:

string jsonSTRINGResult = JsonConvert.SerializeObject(someObj);

One could then deserialize that back to a JObject as follows:

JObject jObj = JsonConvert.DeserializeObject<JObject>(jsonSTRINGResult);

That seems to work, but it would seem like this way has a double performance hit (serialize and then deserialize). Does SerializeObject internally use a JObject that can be accessed somehow? Or is there some way to just serialize directly to a JObject?

Body:
Please note that the JObject route suggested in Eser's accepted answer will work only for non-array CLR objects. It results in below exception if you try converting an Array object to JObject:

An unhandled exception of type 'System.InvalidCastException' occurred
in Newtonsoft.Json.dll

Additional information: Unable to cast object of type
'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.

So in case it is an array object, then you should use JArray instead as shown in the code snippet below:

using Newtonsoft.Json.Linq;

JArray jArray = JArray.FromObject(someArrayObject);

ContentLicense: CC BY-SA 4.0


问:
path works from root only
I read through all I could find on the topic, but nothing worked for me. I run PHP 5.3.29.

I have this PHP code, that works from root, but not from folders:

```<code>  // Fetch latest poster
  $base_url = 'posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '
  <a href="/' . $show_file . '">
  <img src="' . $show_file . '" class="jpg" width="150" alt="latest poster" title="' . $show_name . '">
  </a>';
</code>```

I'd love to just add a slash to get root-relative paths, but that doesn't work in PHP.

This is the site with this issue:

http://flamencopeko.net (here there is no issue)

http://flamencopeko.net/disco_pages/sundays.php (this one has the issue)

答: I think where you want to start is <code>$_SERVER['DOCUMENT_ROOT']</code> </p>

Title: path works from root only

Body:
I read through all I could find on the topic, but nothing worked for me. I run PHP 5.3.29.

I have this PHP code, that works from root, but not from folders:

  // Fetch latest poster
  $base_url = 'posters';
  $newest_mtime = 0;
  if ($handle = opendir($base_url)) {
  while (false !== ($latestFile = readdir($handle))) {
      if (($latestFile != '.') && ($latestFile != '..')) {
         $mtime = filemtime("$base_url/$latestFile");
         if ($mtime > $newest_mtime) {
            $newest_mtime = $mtime;
            $show_file = "$base_url/$latestFile";
         }
      }
    }
  }
  // Show latest poster
  $show_name = basename(trim($show_file, ".jpg"));
  echo '

  ';

I'd love to just add a slash to get root-relative paths, but that doesn't work in PHP.

This is the site with this issue:

http://flamencopeko.net (here there is no issue)

http://flamencopeko.net/disco_pages/sundays.php (this one has the issue)

Body: I think where you want to start is $_SERVER['DOCUMENT_ROOT']


问:
AppCompatActivity vs AppCompatDelegate
Recently I discovered what is AppCompatDelegate so a natural question arises - is it worse than using AppCompatActivity or do they have their differences and what are they?</p>

答:
If your activity class is not extending AppCompatActivity but you still want to use some of its features then you can you AppCompatDelegate.

You can create Appcompatdelegate with following lines of code in your activity class:

```<code>private AppCompatDelegate getDelegate() {
    if (mDelegate == null) {
       mDelegate = AppCompatDelegate.create(this, null);
    }
    return mDelegate;
}
</code>```

Here is the example if you want to add Toolbar in your activity but your class is not extending AppCompatActivity.

https://medium.com/google-developer-experts/how-to-add-toolbar-to-an-activity-which-doesn-t-extend-appcompatactivity-a07c026717b3

Title: AppCompatActivity vs AppCompatDelegate

Body:
If your activity class is not extending AppCompatActivity but you still want to use some of its features then you can you AppCompatDelegate.

You can create Appcompatdelegate with following lines of code in your activity class:

private AppCompatDelegate getDelegate() {
    if (mDelegate == null) {
       mDelegate = AppCompatDelegate.create(this, null);
    }
    return mDelegate;
}

Here is the example if you want to add Toolbar in your activity but your class is not extending AppCompatActivity.

https://medium.com/google-developer-experts/how-to-add-toolbar-to-an-activity-which-doesn-t-extend-appcompatactivity-a07c026717b3


问:
Get the Vertex(Node) Object user clicked on in MSAGL
So, what is the way to retrieve the object that was under the mouse pointer when user clicked? I assume the gViewer must have some event to do that. In the tutorial i found this idea:

```<code>gViewer.SelectionChanged +=
        new EventHandler(gViewer_SelectionChanged);
</code>```

with gViewer_SelectionChanged being an event handler defined like this:

void gViewer_SelectionChanged(object sender, EventArgs e)

Although i added using statments for all 3 MSAGL dll's, i can't find the
Selection changedevent. Is there a special event for that, or am i looking the wrong way? Can it be that i need to handle some mouse event and get object based on it?

Sadly, there are only few MSAGL samples, no documentation and limited comments, so the more questions abount it here - the better.

答:
do you mean get the infomation of each object?</p>

```<code>viewer.Click += GraphNode_Click;
...
private void GraphNode_Click(object sender, EventArgs e)
{
    GViewer viewer = sender as GViewer;
    if (viewer.SelectedObject is Node)
    {
        Node node = viewer.SelectedObject as Node;
        //...do works here
    }
}
</code>```

Body:
So, what is the way to retrieve the object that was under the mouse pointer when user clicked? I assume the gViewer must have some event to do that. In the tutorial i found this idea:

gViewer.SelectionChanged +=
        new EventHandler(gViewer_SelectionChanged);

with gViewer_SelectionChanged being an event handler defined like this:

void gViewer_SelectionChanged(object sender, EventArgs e)

Although i added using statments for all 3 MSAGL dll's, i can't find the
Selection changedevent. Is there a special event for that, or am i looking the wrong way? Can it be that i need to handle some mouse event and get object based on it?

Sadly, there are only few MSAGL samples, no documentation and limited comments, so the more questions abount it here - the better.

Body:
do you mean get the infomation of each object?

viewer.Click += GraphNode_Click;
...
private void GraphNode_Click(object sender, EventArgs e)
{
    GViewer viewer = sender as GViewer;
    if (viewer.SelectedObject is Node)
    {
        Node node = viewer.SelectedObject as Node;
        //...do works here
    }
}


问:
I want to have buttons that will add text as plain text on another webpage
Basically what I want is to have a webpage that has some buttons. Btn1, Btn2, Btn3. When i click Btn1 I want to have some text writen to log.html . So ex. when i hit Btn1 i want "dd/mm/yy Did that and that" writen on that file.
Thank you.</p>

答:
```<code> <!DOCTYPE html>
<head>
<title>D</title>
<script>
function1(){
document.getElementById("sample1").innerHTML = "Added that";
};
</script>
</head>
<body>
<button onclick="function1()">AddSomethingBtn1</button>
<button type="button" onclick="function2()">AddSomethingBtn2</button>
<button type="button" onclick="function3()">AddSomethingBtn3</button>
<div id="sample1">ddd</div>
</body>
</code>```


问:
How to find the least common multiple of a range of numbers?
Given an array of two numbers, let them define the start and end of a range of numbers.  For example, [2,6] means the range 2,3,4,5,6. I want to write javascript code to find the least common multiple for the range.  My code below works for small ranges only, not something like [1,13] (which is the range 1,2,3,4,5,6,7,8,9,10,11,12,13), which causes a stack overflow.  How can I efficiently find the least common multiple of a range?

```<code>function leastCommonMultiple(arr) {
    var minn, max;
    if ( arr[0] > arr[1] ) {
        minn = arr[1];
        max = arr[0];
    } else {
        minn = arr[0];
        max = arr[1];
    }
    function repeatRecurse(min, max, scm) {
        if ( scm % min === 0 && min < max ) {
            return repeatRecurse(min+1, max, scm);
        } else if ( scm % min !== 0 && min < max ) {
            return repeatRecurse(minn, max, scm+max);
        }
        return scm;
    }
    return repeatRecurse(minn, max, max);
}
</code>```

答:
```<code>function smallestCommons(arr) {
  var sortedArr = arr.sort(); // sort array first
  var tempArr = []; // create an empty array to store the array range
  var a = sortedArr[0];
  var b = sortedArr[1];
  for(var i = a; i <= b; i++){
    tempArr.push(i);
  }
  // find the lcm of 2 nums using the Euclid's algorithm
  function gcd(a, b){
    while (b){
      var temp = b;
      b = a % b;
      a = temp;
    }
    return a;
  }

  function lcm(a, b){
    return Math.abs((a * b) / gcd(a, b));
  }
  var lcmRange = tempArr.reduce(lcm);

  return lcmRange;
}
</code>```

Body:
Given an array of two numbers, let them define the start and end of a range of numbers.  For example, [2,6] means the range 2,3,4,5,6. I want to write javascript code to find the least common multiple for the range.  My code below works for small ranges only, not something like [1,13] (which is the range 1,2,3,4,5,6,7,8,9,10,11,12,13), which causes a stack overflow.  How can I efficiently find the least common multiple of a range?

function leastCommonMultiple(arr) {
    var minn, max;
    if ( arr[0] > arr[1] ) {
        minn = arr[1];
        max = arr[0];
    } else {
        minn = arr[0];
        max = arr[1];
    }
    function repeatRecurse(min, max, scm) {
        if ( scm % min === 0 && min < max ) {
            return repeatRecurse(min+1, max, scm);
        } else if ( scm % min !== 0 && min < max ) {
            return repeatRecurse(minn, max, scm+max);
        }
        return scm;
    }
    return repeatRecurse(minn, max, max);
}


问:
Round image corners using intervention image and laravel 5.4
I need insert some images to another image using intervention image and laravel.

This is my main image:

And these are my images to insert to main image:

And finally this image after insert:

Well, I use this code to make this:

```<code>    $img        = Image::make(asset('images/cover.png' ) )->encode('jpg', 15);

    $token      = Session::get('_token');

    $imgWidth   = $img->width();
    $imgHeight  = $img->height();

    $coverImages = Storage::allFiles('public/' . $token . '/cover');

    $r1 = Image::make(asset('storage/' . $token . '/cover/r1.png') );
    $r2 = Image::make(asset('storage/' . $token . '/cover/r2.png') );

    $r1->resize(80, 180, function ($constraint){
        $constraint->aspectRatio();
    });

    $r2->resize(80, 180, function ($constraint){
        $constraint->aspectRatio();
    });

    $img->insert($r1, 'top-left', 190, 175);
    $img->insert($r2, 'top-left', 290, 175);

    $img->save( public_path("storage/{$token}/111111.png"));
</code>```

Now I need to round r1.png and r2.png corners to fit main image.

Do you know how can I do this?

Thanks in Advance

NOTE :

Thanks to @Pascal Meunier, but

I need to round r1.png corners by itself, because I have to save rounded image in another place again for some reasons...

答:
I have not try this myself, but it could be done using mask method from the Intervention class. With this you would need another image of a white rounded rectangle with a black background for the mask.

it should work like this:

```<code>$img        = Image::make(asset('images/cover.png' ) )->encode('jpg', 15);

$token      = Session::get('_token');

$imgWidth   = $img->width();
$imgHeight  = $img->height();

$coverImages = Storage::allFiles('public/' . $token . '/cover');

$r1 = Image::make(asset('storage/' . $token . '/cover/r1.png') );
$r2 = Image::make(asset('storage/' . $token . '/cover/r2.png') );

$r1->resize(80, 180, function ($constraint){
    $constraint->aspectRatio();
})->mask('public/mask.png');

$r2->resize(80, 180, function ($constraint){
    $constraint->aspectRatio();
})->mask('public/mask.png');

$img->insert($r1, 'top-left', 190, 175);
$img->insert($r2, 'top-left', 290, 175);

$img->save( public_path("storage/{$token}/111111.png"));
</code>```

Body:
I need insert some images to another image using intervention image and laravel.

This is my main image:

And these are my images to insert to main image:

And finally this image after insert:

Well, I use this code to make this:

    $img        = Image::make(asset('images/cover.png' ) )->encode('jpg', 15);

    $token      = Session::get('_token');

    $imgWidth   = $img->width();
    $imgHeight  = $img->height();

    $coverImages = Storage::allFiles('public/' . $token . '/cover');

    $r1 = Image::make(asset('storage/' . $token . '/cover/r1.png') );
    $r2 = Image::make(asset('storage/' . $token . '/cover/r2.png') );

    $r1->resize(80, 180, function ($constraint){
        $constraint->aspectRatio();
    });

    $r2->resize(80, 180, function ($constraint){
        $constraint->aspectRatio();
    });

    $img->insert($r1, 'top-left', 190, 175);
    $img->insert($r2, 'top-left', 290, 175);

    $img->save( public_path("storage/{$token}/111111.png"));

Now I need to round r1.png and r2.png corners to fit main image.

Do you know how can I do this?

Thanks in Advance

NOTE :

Thanks to @Pascal Meunier, but

I need to round r1.png corners by itself, because I have to save rounded image in another place again for some reasons...

Body:
I have not try this myself, but it could be done using mask method from the Intervention class. With this you would need another image of a white rounded rectangle with a black background for the mask.

it should work like this:

$img        = Image::make(asset('images/cover.png' ) )->encode('jpg', 15);

$token      = Session::get('_token');

$imgWidth   = $img->width();
$imgHeight  = $img->height();

$coverImages = Storage::allFiles('public/' . $token . '/cover');

$r1 = Image::make(asset('storage/' . $token . '/cover/r1.png') );
$r2 = Image::make(asset('storage/' . $token . '/cover/r2.png') );

$r1->resize(80, 180, function ($constraint){
    $constraint->aspectRatio();
})->mask('public/mask.png');

$r2->resize(80, 180, function ($constraint){
    $constraint->aspectRatio();
})->mask('public/mask.png');

$img->insert($r1, 'top-left', 190, 175);
$img->insert($r2, 'top-left', 290, 175);

$img->save( public_path("storage/{$token}/111111.png"));


问:
How can I get the frame of a UIBarButtonItem?
I'm trying to get the frame of a UIBarButtonItem, which just inherits from UIBarItem/NSObject.</p>

答:
Here's a way to do this without having to resort to undocumented behaviour or assumptions.

Instead of using a UIBarButtonSystemItem, use a UIBarButtonItem with a custom view. You can get the image from the UIBarButtonSystemItem using a technique like this one:

Use UIBarButtonItem icon in UIButton


问:
Monitor Kafka using Opensource tools
Any Opensource tool to monitor confluent Kafka? Most of the opensource tools available are specific to Apache Kafka but not for Confluent Kafka.

we want to monitor atleast the connectors, streams and cluster health

答:
The Kafka that is distributed in the Confluent Platform is Apache Kafka. There really is no such thing as "Confluent Kafka". Any tools that work with the latest version of Apache Kafka (including Kafka Connect and Kafka Streams) will work with the same versions of Kafka included with Confluent Open Source.

Confluent 3.3 includes Apache Kafka 0.11

Confluent 3.2 includes Apache Kafka 0.10.2

Confluent 3.1 includes Apache Kafka 0.10.1

Confluent 3.0 includes Apache Kafka 0.10.0

Confluent 2.0 includes Apache Kafka 0.9

Confluent 1.0 includes Apache Kafka 0.8.2

Note: Confluent Enterprise includes its own monitoring and management GUI called Control Center. Control Center is a separate process so the Apache Kafka is still the same as the open source version.

Title: Monitor Kafka using Opensource tools