问:
Help needed with Database update with JSF, JPA 2.0, hibernate
I am using  JPA 2.0 and hibernate to save some data in a data base and to update them in a later time. Data is entered through a JSF 2.0 web based UI.it gives me a following exception and cant figure out what the reason is. I am new to all these so really need some help.

Thanks in advance and I've posted the code and the exception below.

```<code>int i=em.createQuery("UPDATE UserGroup g SET g.groupName = 'CrazyTest' WHERE g.id="+order.getId()).executeUpdate();
</code>```

```16:19:00.359 (31473614@qtp-21250902-2) WARN  - o.h.util.JDBCExceptionReporter: SQL Error: -3401, SQLState: 22001
16:19:00.359 (31473614@qtp-21250902-2) ERROR - o.h.util.JDBCExceptionReporter: data exception: string data, right truncation
16:19:00.375 (31473614@qtp-21250902-2) ERROR - o.h.e.d.AbstractFlushingEventListener: Could not synchronize database state with session
org.hibernate.exception.DataException: could not update:
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]```

Full Stack trace is copied below

```16:19:00.359 (31473614@qtp-21250902-2) WARN  - o.h.util.JDBCExceptionReporter: SQL Error: -3401, SQLState: 22001
16:19:00.359 (31473614@qtp-21250902-2) ERROR - o.h.util.JDBCExceptionReporter: data exception: string data, right truncation
16:19:00.375 (31473614@qtp-21250902-2) ERROR - o.h.e.d.AbstractFlushingEventListener: Could not synchronize database state with session
org.hibernate.exception.DataException: could not update: [Order#3]
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2596) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2478) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2805) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:114) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:180) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:64) [hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1175) [hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:1273) [hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:117) [hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.ejb.QueryImpl.internalExecuteUpdate(QueryImpl.java:183) [hibernate-entitymanager-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:99) [hibernate-entitymanager-3.5.1-Final.jar:3.5.1-Final]
 at com.digia.sesath.web.service.ProfileService.findGroup(ProfileService.java:51) [classes/:na]
 at com.digia.sesath.web.service.ProfileService$$FastClassByCGLIB$$492d6578.invoke() [cglib-2.2.jar:na]
 at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) [cglib-2.2.jar:na]
 at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:692) [spring-aop-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) [spring-aop-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) [spring-tx-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625) [spring-aop-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at com.digia.sesath.web.service.ProfileService$$EnhancerByCGLIB$$932e77e4.findGroup() [cglib-2.2.jar:na]
 at com.digia.sesath.web.component.permissionManager.GroupUpdateBean.updateGroupDetails(GroupUpdateBean.java:56) [classes/:na]
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_18]
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_18]
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_18]
 at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_18]
 at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:737) [el-api-2.2.jar:na]
 at javax.el.BeanELResolver.invoke(BeanELResolver.java:467) [el-api-2.2.jar:na]
 at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246) [el-api-2.2.jar:na]
 at com.sun.el.parser.AstValue.invoke(AstValue.java:228) [el-impl-2.2.jar:na]
 at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297) [el-impl-2.2.jar:na]
 at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:98) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) [jetty-6.1.24.jar:6.1.24]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:109) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) [spring-web-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [spring-web-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) [jetty-6.1.24.jar:6.1.24]
 at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113) [spring-orm-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) [spring-web-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.Server.handle(Server.java:326) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) [jetty-util-6.1.24.jar:6.1.24]
Caused by: java.sql.SQLException: data exception: string data, right truncation
 at org.hsqldb.jdbc.Util.sqlException(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) ~[commons-dbcp-1.4.jar:1.4]
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) ~[commons-dbcp-1.4.jar:1.4]
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2578) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 ... 91 common frames omitted
Caused by: org.hsqldb.HsqlException: data exception: string data, right truncation
 at org.hsqldb.error.Error.error(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.error.Error.error(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.types.BinaryType.castOrConvertToType(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.types.BinaryType.convertToType(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.StatementDML.getUpdatedData(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.StatementDML.executeUpdateStatement(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.StatementDML.getResult(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.StatementDMQL.execute(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.Session.executeCompiledStatement(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.Session.execute(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 ... 96 common frames omitted
30.11.2010 16:19:00 com.sun.faces.application.ActionListenerImpl processAction
SEVERE: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: [Order#3]
javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: [Order#3]
 at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
 at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
 at javax.faces.component.UICommand.broadcast(UICommand.java:315)
 at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
 at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
 at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
 at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
 at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343)
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:109)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
 at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
 at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
 at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
 at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
 at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
 at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
 at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
 at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
 at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
 at org.mortbay.jetty.Server.handle(Server.java:326)
 at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
 at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)
 at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
 at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
 at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
 at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
 at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: [com.digia.sesath.web.domain.Group#3]
 at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
 at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
 at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1245)
 at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:108)
 at com.digia.sesath.web.service.ProfileService.findGroup(ProfileService.java:51)
 at com.digia.sesath.web.service.ProfileService$$FastClassByCGLIB$$492d6578.invoke()
 at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
 at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:692)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625)
 at com.digia.sesath.web.service.ProfileService$$EnhancerByCGLIB$$932e77e4.findGroup()
 at com.digia.sesath.web.component.permissionManager.GroupUpdateBean.updateGroupDetails(GroupUpdateBean.java:56)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:737)
 at javax.el.BeanELResolver.invoke(BeanELResolver.java:467)
 at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246)
 at com.sun.el.parser.AstValue.invoke(AstValue.java:228)
 at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
 at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:98)
 at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
 ... 57 more
Caused by: org.hibernate.exception.DataException: could not update: [com.digia.sesath.web.domain.Group#3]
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2596)
 at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2478)
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2805)
 at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:114)
 at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260)
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:180)
 at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
 at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:64)
 at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1175)
 at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:1273)
 at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:117)
 at org.hibernate.ejb.QueryImpl.internalExecuteUpdate(QueryImpl.java:183)
 at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:99)
 ... 78 more
Caused by: java.sql.SQLException: data exception: string data, right truncation
 at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
 at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
 at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2578)
 ... 91 more
Caused by: org.hsqldb.HsqlException: data exception: string data, right truncation
 at org.hsqldb.error.Error.error(Unknown Source)
 at org.hsqldb.error.Error.error(Unknown Source)
 at org.hsqldb.types.BinaryType.castOrConvertToType(Unknown Source)
 at org.hsqldb.types.BinaryType.convertToType(Unknown Source)
 at org.hsqldb.StatementDML.getUpdatedData(Unknown Source)
 at org.hsqldb.StatementDML.executeUpdateStatement(Unknown Source)
 at org.hsqldb.StatementDML.getResult(Unknown Source)
 at org.hsqldb.StatementDMQL.execute(Unknown Source)
 at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
 at org.hsqldb.Session.execute(Unknown Source)
 ... 96 more
30.11.2010 16:19:00 com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{groupUpdateBean.updateGroupDetails()}: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: []
javax.faces.FacesException: #{groupUpdateBean.updateGroupDetails()}: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: [Order#3]
 at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
 at javax.faces.component.UICommand.broadcast(UICommand.java:315)
 at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
 at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
 at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
 at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
 at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343)
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at ```

答:
It seems that either your database column is "varchar" or your java property is a String. Verify that both are integers.

Also, avoid concatenating raw parameter values into your SQLs. It makes you vulnerable to SQL Injections[1]. For this, use the prepared statements, or, in case of Hibernate, you can use the Query object. Like this:

```<code>Query query = em.createQuery("UPDATE UserGroup g SET g.groupName = 'CrazyTest' WHERE g.id= :id"
int i= query.setParameter("id",order.getId()).executeUpdate();
</code>```

1 - http://www.owasp.org/index.php/SQL_Injection

Body:
I am using  JPA 2.0 and hibernate to save some data in a data base and to update them in a later time. Data is entered through a JSF 2.0 web based UI.it gives me a following exception and cant figure out what the reason is. I am new to all these so really need some help.

Thanks in advance and I've posted the code and the exception below.

int i=em.createQuery("UPDATE UserGroup g SET g.groupName = 'CrazyTest' WHERE g.id="+order.getId()).executeUpdate();

16:19:00.359 (31473614@qtp-21250902-2) WARN  - o.h.util.JDBCExceptionReporter: SQL Error: -3401, SQLState: 22001
16:19:00.359 (31473614@qtp-21250902-2) ERROR - o.h.util.JDBCExceptionReporter: data exception: string data, right truncation
16:19:00.375 (31473614@qtp-21250902-2) ERROR - o.h.e.d.AbstractFlushingEventListener: Could not synchronize database state with session
org.hibernate.exception.DataException: could not update:
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]

Full Stack trace is copied below

16:19:00.359 (31473614@qtp-21250902-2) WARN  - o.h.util.JDBCExceptionReporter: SQL Error: -3401, SQLState: 22001
16:19:00.359 (31473614@qtp-21250902-2) ERROR - o.h.util.JDBCExceptionReporter: data exception: string data, right truncation
16:19:00.375 (31473614@qtp-21250902-2) ERROR - o.h.e.d.AbstractFlushingEventListener: Could not synchronize database state with session
org.hibernate.exception.DataException: could not update: [Order#3]
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2596) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2478) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2805) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:114) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:180) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:64) [hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1175) [hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:1273) [hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:117) [hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.ejb.QueryImpl.internalExecuteUpdate(QueryImpl.java:183) [hibernate-entitymanager-3.5.1-Final.jar:3.5.1-Final]
 at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:99) [hibernate-entitymanager-3.5.1-Final.jar:3.5.1-Final]
 at com.digia.sesath.web.service.ProfileService.findGroup(ProfileService.java:51) [classes/:na]
 at com.digia.sesath.web.service.ProfileService$$FastClassByCGLIB$$492d6578.invoke() [cglib-2.2.jar:na]
 at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) [cglib-2.2.jar:na]
 at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:692) [spring-aop-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) [spring-aop-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) [spring-tx-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625) [spring-aop-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at com.digia.sesath.web.service.ProfileService$$EnhancerByCGLIB$$932e77e4.findGroup() [cglib-2.2.jar:na]
 at com.digia.sesath.web.component.permissionManager.GroupUpdateBean.updateGroupDetails(GroupUpdateBean.java:56) [classes/:na]
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_18]
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_18]
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_18]
 at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_18]
 at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:737) [el-api-2.2.jar:na]
 at javax.el.BeanELResolver.invoke(BeanELResolver.java:467) [el-api-2.2.jar:na]
 at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246) [el-api-2.2.jar:na]
 at com.sun.el.parser.AstValue.invoke(AstValue.java:228) [el-impl-2.2.jar:na]
 at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297) [el-impl-2.2.jar:na]
 at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:98) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.0.2.jar:2.0.2-FCS]
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312) [jsf-api-2.0.jar:2.0.2-SNAPSHOT]
 at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) [jetty-6.1.24.jar:6.1.24]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:109) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149) [spring-security-web-3.0.2.RELEASE.jar:na]
 at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) [spring-web-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [spring-web-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) [jetty-6.1.24.jar:6.1.24]
 at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113) [spring-orm-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) [spring-web-3.0.2.RELEASE.jar:3.0.2.RELEASE]
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.Server.handle(Server.java:326) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410) [jetty-6.1.24.jar:6.1.24]
 at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) [jetty-util-6.1.24.jar:6.1.24]
Caused by: java.sql.SQLException: data exception: string data, right truncation
 at org.hsqldb.jdbc.Util.sqlException(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) ~[commons-dbcp-1.4.jar:1.4]
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) ~[commons-dbcp-1.4.jar:1.4]
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2578) ~[hibernate-core-3.5.1-Final.jar:3.5.1-Final]
 ... 91 common frames omitted
Caused by: org.hsqldb.HsqlException: data exception: string data, right truncation
 at org.hsqldb.error.Error.error(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.error.Error.error(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.types.BinaryType.castOrConvertToType(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.types.BinaryType.convertToType(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.StatementDML.getUpdatedData(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.StatementDML.executeUpdateStatement(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.StatementDML.getResult(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.StatementDMQL.execute(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.Session.executeCompiledStatement(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 at org.hsqldb.Session.execute(Unknown Source) ~[hsqldb-2.0.0.jar:2.0.0]
 ... 96 common frames omitted
30.11.2010 16:19:00 com.sun.faces.application.ActionListenerImpl processAction
SEVERE: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: [Order#3]
javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: [Order#3]
 at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
 at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
 at javax.faces.component.UICommand.broadcast(UICommand.java:315)
 at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
 at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
 at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
 at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
 at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343)
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:109)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
 at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
 at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
 at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
 at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
 at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
 at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
 at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
 at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
 at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
 at org.mortbay.jetty.Server.handle(Server.java:326)
 at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
 at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)
 at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
 at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
 at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
 at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
 at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: [com.digia.sesath.web.domain.Group#3]
 at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
 at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
 at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1245)
 at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:108)
 at com.digia.sesath.web.service.ProfileService.findGroup(ProfileService.java:51)
 at com.digia.sesath.web.service.ProfileService$$FastClassByCGLIB$$492d6578.invoke()
 at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
 at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:692)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625)
 at com.digia.sesath.web.service.ProfileService$$EnhancerByCGLIB$$932e77e4.findGroup()
 at com.digia.sesath.web.component.permissionManager.GroupUpdateBean.updateGroupDetails(GroupUpdateBean.java:56)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:737)
 at javax.el.BeanELResolver.invoke(BeanELResolver.java:467)
 at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246)
 at com.sun.el.parser.AstValue.invoke(AstValue.java:228)
 at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
 at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:98)
 at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
 ... 57 more
Caused by: org.hibernate.exception.DataException: could not update: [com.digia.sesath.web.domain.Group#3]
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2596)
 at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2478)
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2805)
 at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:114)
 at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260)
 at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:180)
 at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
 at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:64)
 at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1175)
 at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:1273)
 at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:117)
 at org.hibernate.ejb.QueryImpl.internalExecuteUpdate(QueryImpl.java:183)
 at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:99)
 ... 78 more
Caused by: java.sql.SQLException: data exception: string data, right truncation
 at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
 at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
 at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
 at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2578)
 ... 91 more
Caused by: org.hsqldb.HsqlException: data exception: string data, right truncation
 at org.hsqldb.error.Error.error(Unknown Source)
 at org.hsqldb.error.Error.error(Unknown Source)
 at org.hsqldb.types.BinaryType.castOrConvertToType(Unknown Source)
 at org.hsqldb.types.BinaryType.convertToType(Unknown Source)
 at org.hsqldb.StatementDML.getUpdatedData(Unknown Source)
 at org.hsqldb.StatementDML.executeUpdateStatement(Unknown Source)
 at org.hsqldb.StatementDML.getResult(Unknown Source)
 at org.hsqldb.StatementDMQL.execute(Unknown Source)
 at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
 at org.hsqldb.Session.execute(Unknown Source)
 ... 96 more
30.11.2010 16:19:00 com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{groupUpdateBean.updateGroupDetails()}: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: []
javax.faces.FacesException: #{groupUpdateBean.updateGroupDetails()}: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not update: [Order#3]
 at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
 at javax.faces.component.UICommand.broadcast(UICommand.java:315)
 at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
 at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
 at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
 at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
 at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343)
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
 at

Body:
It seems that either your database column is "varchar" or your java property is a String. Verify that both are integers.

Also, avoid concatenating raw parameter values into your SQLs. It makes you vulnerable to SQL Injections[1]. For this, use the prepared statements, or, in case of Hibernate, you can use the Query object. Like this:

Query query = em.createQuery("UPDATE UserGroup g SET g.groupName = 'CrazyTest' WHERE g.id= :id"
int i= query.setParameter("id",order.getId()).executeUpdate();

1 - http://www.owasp.org/index.php/SQL_Injection


来源: stackexchange

问:
Best way to disable entire form on PHP condition?
I have a site (like many). I want to show but disable a particular form based on whether they are logged in or not. The way I show if the user is logged in is via a cookie set by PHP. What I'm wondering is the best way to disable all the elements in the form when the user is not logged in.

The solution I have at the moment is to get PHP to echo some JavaScript (jQuery to be precise) to the page:

```
$("#form_name").children("input, textarea").attr("disabled", "disabled");
```

Is this the right way to go, or is there a better way to be doing things?

答:
If the user does not have javascript enabled then of course this answer is: this is not a good idea.

Second just using disabled inputs is also a bad idea, a malicious user can tweak your page and easily reenable.

That said all is fine as long as you ensure that the fields that you want disabled are not accepted on the server side post.

ContentLicense: CC BY-SA 2.5

Body:
I have a site (like many). I want to show but disable a particular form based on whether they are logged in or not. The way I show if the user is logged in is via a cookie set by PHP. What I'm wondering is the best way to disable all the elements in the form when the user is not logged in.

The solution I have at the moment is to get PHP to echo some JavaScript (jQuery to be precise) to the page:

$("#form_name").children("input, textarea").attr("disabled", "disabled");

Is this the right way to go, or is there a better way to be doing things?


问:
Sample some elements from a data set in R
I have a data set which is imported from excel file. The name of that is "Stocks". I want to sample 4 elements from column 3 to 7.
but when I write this command:

sample(Stocks[,3:7], 4, replace = FALSE)

it gives me 4 sample rows, not 4 elements.

答:
If we want to sample 4 elements in total, then convert data.frame to a vector by unlisting and then sample 4 elements out of the vector

```<code>sample(unlist(Stocks[,3:7]), 4, replace = FALSE)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If we want to sample 4 elements in total, then convert data.frame to a vector by unlisting and then sample 4 elements out of the vector

sample(unlist(Stocks[,3:7]), 4, replace = FALSE)


问:
Issues with adding figtext to bottom of subplots
I'm trying to add a series of footnotes using plt.figtext to a set of subplots, and cannot get them all to show up when I print out to file using either the plt.savefig() command, or %matplotlib notebook save to file option.

The list of footnotes is pretty long and looks like (when rendered to screen, which works fine):

However, when I print to file they get cut off:

I set my figure size for the subplot to plt.figure(figsize=(7,10))
and used plt.tight_layout() to format the subplots so that the axes didn't mash up with the titles.

I have been trying for the life of me to find a way to extend the size of the output to account for the footnotes AND the subplots, but have had absolutely no luck. This does not seem like an unreasonable use case, by any stretch of the imagination.

EDIT

The text is generated after each subplot is created, along the lines of:

```<code>plt.legend(loc=6, fontsize=10)
#plt.legend(bbox_to_anchor=(1.0, 1), loc=2, borderaxespad=0.)
plt.xlim(0, 45)
plt.ylim(2.5, 5.5)
plt.xlabel('Distance (km)', alpha=.75)
plt.ylabel('Pace (min/km)', alpha=.75)
plt.title('Top 4 Male Finishers and SA 2016 Twin Cities Marathon Timed$^1$ Splits$^2$')
plt.figtext(0.814, 0.01, '1 Provided by mtecResults', horizontalalignment='right', fontsize=6)
plt.figtext(0.88, 0.0, '2 Mean time per unit distance between two points', horizontalalignment='right', fontsize=6)
plt.figtext(0.845, -0.01, '3 SA Finished 670 out of 4716 Males', horizontalalignment='right', fontsize=6)
plt.figtext(0.845, -0.02, '4 SA Finished 754 out of 4756 Males', horizontalalignment='right', fontsize=6)
</code>```

答:
There are of course a multitude of options how to make sure some text label is acutally within the figure when saving.

1. the bbox_inches argument

You may choose not to use plt.tight_layout(), because this ignores text added as a text label. You can then use the bbox_inches argument to plt.savefig:

```<code>plt.savefig("output.png", bbox_inches = "tight")
</code>```

This method increases the figure size until all text is included.

Placing the text would best be done using verticalalignment ="top" and placing the test close to y=0 in figure coordinates. Example:

```<code>import matplotlib.pyplot as plt
plt.gca()

text = """1 Provided by mtecResults
2 Mean time per unit distance between two points
3 SA Finished 670 out of 4716 Males
4 SA Finished 754 out of 4756 Males"""

plt.figtext(0.05,0.00, text, fontsize=8, va="top", ha="left")

plt.savefig(__file__+".png", bbox_inches = "tight")
plt.show()
</code>```

2. Add margin to figure.

You may use plt.subplots_adjust(bottom=0.4) to make more space around the axes, which can then be filled with the text. For the other dimensions use arguments top, left, right, depending on where the text sits.

This option requires the text to be positionned within the figure. It will not change the figure size, but reduce the size of the axes.

Placing the text would best be done using verticalalignment ="bottom" and placing the test close to but above y=0 in figure coordinates. Example:

```<code>import matplotlib.pyplot as plt

plt.gca()
plt.subplots_adjust(bottom=0.2)

text = """1 Provided by mtecResults
2 Mean time per unit distance between two points
3 SA Finished 670 out of 4716 Males
4 SA Finished 754 out of 4756 Males"""

plt.figtext(0.05,0.01, text, fontsize=8, va="bottom", ha="left")

plt.savefig(__file__+"2.png")
plt.show()
</code>```

Body:
I'm trying to add a series of footnotes using plt.figtext to a set of subplots, and cannot get them all to show up when I print out to file using either the plt.savefig() command, or %matplotlib notebook save to file option.

The list of footnotes is pretty long and looks like (when rendered to screen, which works fine):

However, when I print to file they get cut off:

I set my figure size for the subplot to plt.figure(figsize=(7,10))
and used plt.tight_layout() to format the subplots so that the axes didn't mash up with the titles.

I have been trying for the life of me to find a way to extend the size of the output to account for the footnotes AND the subplots, but have had absolutely no luck. This does not seem like an unreasonable use case, by any stretch of the imagination.

EDIT

The text is generated after each subplot is created, along the lines of:

plt.legend(loc=6, fontsize=10)
#plt.legend(bbox_to_anchor=(1.0, 1), loc=2, borderaxespad=0.)
plt.xlim(0, 45)
plt.ylim(2.5, 5.5)
plt.xlabel('Distance (km)', alpha=.75)
plt.ylabel('Pace (min/km)', alpha=.75)
plt.title('Top 4 Male Finishers and SA 2016 Twin Cities Marathon Timed$^1$ Splits$^2$')
plt.figtext(0.814, 0.01, '1 Provided by mtecResults', horizontalalignment='right', fontsize=6)
plt.figtext(0.88, 0.0, '2 Mean time per unit distance between two points', horizontalalignment='right', fontsize=6)
plt.figtext(0.845, -0.01, '3 SA Finished 670 out of 4716 Males', horizontalalignment='right', fontsize=6)
plt.figtext(0.845, -0.02, '4 SA Finished 754 out of 4756 Males', horizontalalignment='right', fontsize=6)

Body:
There are of course a multitude of options how to make sure some text label is acutally within the figure when saving.

1. the bbox_inches argument

You may choose not to use plt.tight_layout(), because this ignores text added as a text label. You can then use the bbox_inches argument to plt.savefig:

plt.savefig("output.png", bbox_inches = "tight")

This method increases the figure size until all text is included.

Placing the text would best be done using verticalalignment ="top" and placing the test close to y=0 in figure coordinates. Example:

import matplotlib.pyplot as plt
plt.gca()

text = """1 Provided by mtecResults
2 Mean time per unit distance between two points
3 SA Finished 670 out of 4716 Males
4 SA Finished 754 out of 4756 Males"""

plt.figtext(0.05,0.00, text, fontsize=8, va="top", ha="left")

plt.savefig(__file__+".png", bbox_inches = "tight")
plt.show()

2. Add margin to figure.

You may use plt.subplots_adjust(bottom=0.4) to make more space around the axes, which can then be filled with the text. For the other dimensions use arguments top, left, right, depending on where the text sits.

This option requires the text to be positionned within the figure. It will not change the figure size, but reduce the size of the axes.

Placing the text would best be done using verticalalignment ="bottom" and placing the test close to but above y=0 in figure coordinates. Example:

import matplotlib.pyplot as plt

plt.gca()
plt.subplots_adjust(bottom=0.2)

text = """1 Provided by mtecResults
2 Mean time per unit distance between two points
3 SA Finished 670 out of 4716 Males
4 SA Finished 754 out of 4756 Males"""

plt.figtext(0.05,0.01, text, fontsize=8, va="bottom", ha="left")

plt.savefig(__file__+"2.png")
plt.show()


问:
Reconnect stomp when disconnected
I am using the following code to create/subscribe to a topic and handle the messages. Sometimes the connection gets lost and the error says:

```<code>Whoops! The connection was lost...
</code>```

I would like to know if there is a way to reconnect it. Is it possible in the error callback or define the whole code in a method and call it recursively in error callback ?

```<code> $(document).ready(function () {
  ........
  ...............
      try {
            var socket = new SockJS("${createLink(uri: '/stomp')}");
            var client = Stomp.over(socket);
            client.connect({}, function () {
            client.subscribe("/topic/${userInstance?.username}",
            function (message) {
           ............
           ....................

              });
            });
        } catch (error) {
            console.log("ERROR: " + error.toString());
        }
   });
</code>```

答:
This is what I am using in a Polymer element:</p>

```<code>ready: function() {
    this.connectWs();
},
connectWs: function() {
    this.socket = new WebSocket(this.socketUrl);
    this.stompClient = Stomp.over(this.socket);
    this.stompClient.debug = null;
    this.stompClient.connect({},
        function(frame) {
            // Connection OK
        }.bind(this),
        function(e) {
            console.error(e, "Reconnecting WS", this.socketUrl);
            window.setTimeout(function() {
                this.connectWs();
            }.bind(this), 2500);
        }.bind(this)
    );
},
</code>```

Title: Reconnect stomp when disconnected

Body:
I am using the following code to create/subscribe to a topic and handle the messages. Sometimes the connection gets lost and the error says:

Whoops! The connection was lost...

I would like to know if there is a way to reconnect it. Is it possible in the error callback or define the whole code in a method and call it recursively in error callback ?

 $(document).ready(function () {
  ........
  ...............
      try {
            var socket = new SockJS("${createLink(uri: '/stomp')}");
            var client = Stomp.over(socket);
            client.connect({}, function () {
            client.subscribe("/topic/${userInstance?.username}",
            function (message) {
           ............
           ....................

              });
            });
        } catch (error) {
            console.log("ERROR: " + error.toString());
        }
   });

Body:
This is what I am using in a Polymer element:

ready: function() {
    this.connectWs();
},
connectWs: function() {
    this.socket = new WebSocket(this.socketUrl);
    this.stompClient = Stomp.over(this.socket);
    this.stompClient.debug = null;
    this.stompClient.connect({},
        function(frame) {
            // Connection OK
        }.bind(this),
        function(e) {
            console.error(e, "Reconnecting WS", this.socketUrl);
            window.setTimeout(function() {
                this.connectWs();
            }.bind(this), 2500);
        }.bind(this)
    );
},


问:
Only read the last character in a .txt file
I am creating a program using processing that read txt file and send the result to the arduino.
I can get it to send string and keep update, but as soon as I try to just send the last char it won't work... Can anyone help me with this? Basically I need to read the last char from a txt file and send it as char through serial to arduino, python or processing both will work!

*Here is my code [ Processing ]

```<code>import processing.serial.*;
import java.io.*;

int mySwitch=0;
int counter=0;
String [] subtext;
Serial myPort;

void setup(){
   //Create a switch that will control the frequency of text file reads.
   //When mySwitch=1, the program is setup to read the text file.
   //This is turned off when mySwitch = 0
   mySwitch=1;

   //Open the serial port for communication with the Arduino
   //Make sure the COM port is correct
   myPort = new Serial(this, "COM4", 9600);
   myPort.bufferUntil('\n');
}

void draw() {
   if (mySwitch>0){
       /*The readData function can be found later in the code. This is the call to read a CSV file on the computer hard-drive. */
       readData("G:/Personal/control.txt");

       /*The following switch prevents continuous reading of the text file, until   we are ready to read the file again. */
       mySwitch=0;
   }

   /*Only send new data. This IF statement will allow new data to be sent to the arduino. */
   if(counter<subtext.length){
       /* Write the next number to the Serial port and send it to the Arduino There will be a delay of half a second before the command is sent to turn the LED off : myPort.write('0'); */
       myPort.write(subtext[counter]);
       delay(500);
       myPort.write('0');
       delay(100);

       //Increment the counter so that the next number is sent to the arduino.
       counter++;
   } else{
       //If the text file has run out of numbers, then read the text file again in 5 seconds.
       delay(5000);
       mySwitch=1;
   }
}

/* The following function will read from a CSV or TXT file */
void readData(String myFileName){

 File file=new File(myFileName);
 BufferedReader br=null;

 try{
   br=new BufferedReader(new FileReader(file));
   String text=null;

   /* keep reading each line until you get to the end of the file */
 while((text=br.readLine())!=null){
   * Spilt each line up into bits and pieces using a comma as a separator */

   subtext = splitTokens(text,",");
 }
 }catch(FileNotFoundException e){
     e.printStackTrace();
 }catch(IOException e){
     e.printStackTrace();
 }finally{
     try {
        if (br != null){
           br.close();
        }
     } catch (IOException e) {
     e.printStackTrace();
   }
 }
</code>```

And this is the data that i am dealing with

[19:54:57] [Server thread/INFO]: [@] b

[19:54:57] [Server thread/INFO]: [@] a

[19:54:57] [Server thread/INFO]: [@] b

[19:54:57] [Server thread/INFO]: [@] a

[19:54:58] [Server thread/INFO]: [@] b

[19:54:58] [Server thread/INFO]: [@] a

[19:54:59] [Server thread/INFO]: [@] b

[20:30:23] [Server thread/INFO]: [@] a

[20:30:24] [Server thread/INFO]: [@] b

[21:07:34] [Server thread/INFO]: [@] a

[21:07:35] [Server thread/INFO]: [@] b

The only value that I really care is a / b

And this file will consistently update in this format

答:
Simplest thing I could come up with:

```<code>s="".join(list(open(rfile_directory)))
pos=s[-1:]
</code>```

steps:

opened the file

converted it into list

Joined the list to str form

The got the last character!

Now, if the character is wanted in int form, simply:

```<code>pos=int(s[-1:])
</code>```

Body:
I am creating a program using processing that read txt file and send the result to the arduino.
I can get it to send string and keep update, but as soon as I try to just send the last char it won't work... Can anyone help me with this? Basically I need to read the last char from a txt file and send it as char through serial to arduino, python or processing both will work!

*Here is my code [ Processing ]

import processing.serial.*;
import java.io.*;

int mySwitch=0;
int counter=0;
String [] subtext;
Serial myPort;

void setup(){
   //Create a switch that will control the frequency of text file reads.
   //When mySwitch=1, the program is setup to read the text file.
   //This is turned off when mySwitch = 0
   mySwitch=1;

   //Open the serial port for communication with the Arduino
   //Make sure the COM port is correct
   myPort = new Serial(this, "COM4", 9600);
   myPort.bufferUntil('\n');
}

void draw() {
   if (mySwitch>0){
       /*The readData function can be found later in the code. This is the call to read a CSV file on the computer hard-drive. */
       readData("G:/Personal/control.txt");

       /*The following switch prevents continuous reading of the text file, until   we are ready to read the file again. */
       mySwitch=0;
   }

   /*Only send new data. This IF statement will allow new data to be sent to the arduino. */
   if(counter<subtext.length){
       /* Write the next number to the Serial port and send it to the Arduino There will be a delay of half a second before the command is sent to turn the LED off : myPort.write('0'); */
       myPort.write(subtext[counter]);
       delay(500);
       myPort.write('0');
       delay(100);

       //Increment the counter so that the next number is sent to the arduino.
       counter++;
   } else{
       //If the text file has run out of numbers, then read the text file again in 5 seconds.
       delay(5000);
       mySwitch=1;
   }
}

/* The following function will read from a CSV or TXT file */
void readData(String myFileName){

 File file=new File(myFileName);
 BufferedReader br=null;

 try{
   br=new BufferedReader(new FileReader(file));
   String text=null;

   /* keep reading each line until you get to the end of the file */
 while((text=br.readLine())!=null){
   * Spilt each line up into bits and pieces using a comma as a separator */

   subtext = splitTokens(text,",");
 }
 }catch(FileNotFoundException e){
     e.printStackTrace();
 }catch(IOException e){
     e.printStackTrace();
 }finally{
     try {
        if (br != null){
           br.close();
        }
     } catch (IOException e) {
     e.printStackTrace();
   }
 }

And this is the data that i am dealing with

[19:54:57] [Server thread/INFO]: [@] b

[19:54:57] [Server thread/INFO]: [@] a

[19:54:57] [Server thread/INFO]: [@] b

[19:54:57] [Server thread/INFO]: [@] a

[19:54:58] [Server thread/INFO]: [@] b

[19:54:58] [Server thread/INFO]: [@] a

[19:54:59] [Server thread/INFO]: [@] b

[20:30:23] [Server thread/INFO]: [@] a

[20:30:24] [Server thread/INFO]: [@] b

[21:07:34] [Server thread/INFO]: [@] a

[21:07:35] [Server thread/INFO]: [@] b

The only value that I really care is a / b

And this file will consistently update in this format

Body:
Simplest thing I could come up with:

s="".join(list(open(rfile_directory)))
pos=s[-1:]

steps:

opened the file

converted it into list

Joined the list to str form

The got the last character!

Now, if the character is wanted in int form, simply:

pos=int(s[-1:])


问:
Firebase signup with user, email and password
After leaving Parse and moving to Firebase I faced a problem that it's only possible to signup with email and password, how can I make Firebase store the username as well?  </p>

答:
```<code>func handleRegister(email:String, password:String, username:String) {

    //Create User
    FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, err) in

        if err != nil {
            print(err!.localizedDescription)
            return
        }

        //Success! User Created!

        if let userID = user?.uid {

            //Create User Profile
            let databaseRef = FIRDatabase.database().reference()
            let usersRef = databaseRef.child("Users").child(userID)

            let usernameValue = ["username":username]

            usersRef.updateChildValues(usernameValue, withCompletionBlock: { (err, ref) in

                if err != nil {
                    print(err!.localizedDescription)
                    return
                }

                //Profile created and updated!
                //You can use perform segue or present controller to go to another controller...
            })

        }

    })

}
</code>```


问:
How would I get a ListView from ListActivty INSIDE a class that extends on TabActivity?
Newbie here, bear with me..

I have a class that extends TabActivity. One of my tabs currently contains one long string composed of some records i got from my sqlite table. Now i'm following a tutorial and the next step is to move away from the string and create something a bit more appropriate for the records, a listView. However it says i'll need to change my class to extend ListActivity but i've already extended TabActivity (not part of the tutorial)and i don't really have the knowledge yet to know where to go from here.

I figure if my tabs content was set with intents to separate classes I wouldn't have a problem but it's important to me that both the tabs and their content are constructed in the same class because i will want to be doing a lot between them later. But maybe there is no way i can avoid creating a separate class? If so could i still point both of my tabs towards the same class? for the same reason as above. But then how would i get them still displaying different content?

I sure there's an obvious solution but i don't have enough programming experience to have a clue what it is, I've been googling a while now but i'm not really sure what to look for so if somebody could point me in the right direction i'd really appreciate it.

Hope I'm talking sense, Here's a link to see the class i'm working on:

Codeviewer.org , my Budget.java

答:
You don't mess with the TabActivity as this Activity just manages all of your tabs. You just set the new ListActivity as the content of the tab you want to display it in.

Check out the Android Hello Tab View tutorial as it shows you how to assign an Activity to a tab which is just what you need.


问:
uwp deferred loading of image sources
A UWP app, a collection of view models is instantiated and populated in the page's constructor. Each item has a property called ImageSource of type BitmapImage, initialized to a new BitmapImage(). The view has a Grid View bound to the collection. In the view, a DataTemplate is defined for the items of the collection. The DataTemplate, in particular, shows an image whose source is bound to the item's property ImageSource. The DataTemplate also handles events of Image, so it displays a placeholder while the image is still loading.
The page's Loaded event triggers the download of all image source:

```<code>        private async void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            foreach (ImageViewModel imageViewModel in this.imageViewModels)
            {
                IRandomAccessStream randomAccessStream = await SlowImageSourceProvider.GetRandomAccessStream(imageViewModel.Id);
                await imageViewModel.ImageSource.SetSourceAsync(randomAccessStream);
            }
        }
</code>```

In this code, an instance of IRandomAccessStream is retrieved from a slow provider, like an HttpClient listening on a slow network.

The Image.Source on the view are bound to the imageViewModel.ImageSource of the code above. In such a way, each image needs to wait for the previous one to end its downloading, before starting to download its own source.

How is it possible to make all images to start downloading at once, without them to wait for the others?

The only idea I had was to create a lazy implementation of IRandomAccessStream, but I wander if there is a better way of doing it.

Thanks!

答:
The images will only download one at a time because the foreach will not start another iteration until both await statements complete. To request all images download concurrently and wait for them to complete asynchronously try the following:

```<code>private async void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
    var setImageTasks = this.imageViewModels.Select(async imageViewModel => {
        var randomAccessStream = await SlowImageSourceProvider.GetRandomAccessStream(imageViewModel.Id);
        await imageViewModel.ImageSource.SetSourceAsync(randomAccessStream);
    }).ToArray();
    await Task.WhenAll(setImageTasks);
}
</code>```

Title: uwp deferred loading of image sources

Body:
A UWP app, a collection of view models is instantiated and populated in the page's constructor. Each item has a property called ImageSource of type BitmapImage, initialized to a new BitmapImage(). The view has a Grid View bound to the collection. In the view, a DataTemplate is defined for the items of the collection. The DataTemplate, in particular, shows an image whose source is bound to the item's property ImageSource. The DataTemplate also handles events of Image, so it displays a placeholder while the image is still loading.
The page's Loaded event triggers the download of all image source:

        private async void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            foreach (ImageViewModel imageViewModel in this.imageViewModels)
            {
                IRandomAccessStream randomAccessStream = await SlowImageSourceProvider.GetRandomAccessStream(imageViewModel.Id);
                await imageViewModel.ImageSource.SetSourceAsync(randomAccessStream);
            }
        }

In this code, an instance of IRandomAccessStream is retrieved from a slow provider, like an HttpClient listening on a slow network.

The Image.Source on the view are bound to the imageViewModel.ImageSource of the code above. In such a way, each image needs to wait for the previous one to end its downloading, before starting to download its own source.

How is it possible to make all images to start downloading at once, without them to wait for the others?

The only idea I had was to create a lazy implementation of IRandomAccessStream, but I wander if there is a better way of doing it.

Thanks!

Body:
The images will only download one at a time because the foreach will not start another iteration until both await statements complete. To request all images download concurrently and wait for them to complete asynchronously try the following:

private async void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
    var setImageTasks = this.imageViewModels.Select(async imageViewModel => {
        var randomAccessStream = await SlowImageSourceProvider.GetRandomAccessStream(imageViewModel.Id);
        await imageViewModel.ImageSource.SetSourceAsync(randomAccessStream);
    }).ToArray();
    await Task.WhenAll(setImageTasks);
}


问:
Relative image paths in html displayed by webkit
I'm using webkit.WebView in Python to display html generated from Markdown. I can display an image from a local file by generating an img tag with an absolute src path, but a realtive path doesn't work. The html with the relative path displays the image OK in Firefox. Is this a known problem with webkit and if so is there a soultion?</p>

答:
Answering my own question .... I realised I was using the WebView's load_string function, rather than writing the html to a file and loading that. This means that there is no html file as a base uri to load the image relative to.

The designers have obviously thought of this and provided a base_uri parameter, which I had just set to "File://". Changing this to a path which makes sense in conjunction with the relative path to the image file fixes the problem.

Hope this will be useful to someone who may have the same problem.


问:
Using OpenCV with Tkinter
I'm writing a program that needs to display a video stream in a Tkinter window. Since there will also be buttons for performing various functions, I'm using grid to organize where everything goes.

The following code, modified from Show webcam sequence TkInter, works fine on my Raspberry Pi:

```<code>import Tkinter as tk
import cv2
from PIL import Image, ImageTk

width, height = 800, 600
cap = cv2.VideoCapture(0)

root = tk.Tk()
lmain = tk.Label(root)
lmain.pack()

def show_frame():
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_frame)

show_frame()
root.mainloop()
</code>```

However, combining it with Tkinter doesn't work. (In what follows, I've tried commenting out Display 1, Display 2, and neither.)

```<code>import numpy as np
import cv2
import Tkinter as tk
import Image, ImageTk

#Set up GUI
window = tk.Tk()  #Makes main window
window.wm_title("Digital Microscope")
window.config(background="#FFFFFF")

#Graphics window
imageFrame = tk.Frame(window, width=600, height=500)
imageFrame.grid(row=0, column=0, padx=10, pady=2)

#Capture video frames
lmain = tk.Label(imageFrame)
cap = cv2.VideoCapture(0)
def show_frame():
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_frame)

tk.Label(imageFrame, image=show_frame()).grid(row=0, column=0, padx=10, pady=2)  #Display 1

#Slider window (slider controls stage position)
sliderFrame = tk.Frame(window, width=600, height=100)
sliderFrame.grid(row = 600, column=0, padx=10, pady=2)

show_frame()  #Display 2
window.mainloop()  #Starts GUI
</code>```

How can I get the video to display in imageFrame?

答:
Try this code:

```<code>from PIL import Image, ImageTk
import Tkinter as tk
import argparse
import datetime
import cv2
import os

class Application:
    def __init__(self, output_path = "./"):
        """ Initialize application which uses OpenCV + Tkinter. It displays
            a video stream in a Tkinter window and stores current snapshot on disk """
        self.vs = cv2.VideoCapture(0) # capture video frames, 0 is your default video camera
        self.output_path = output_path  # store output path
        self.current_image = None  # current image from the camera

        self.root = tk.Tk()  # initialize root window
        self.root.title("PyImageSearch PhotoBooth")  # set window title
        # self.destructor function gets fired when the window is closed
        self.root.protocol('WM_DELETE_WINDOW', self.destructor)

        self.panel = tk.Label(self.root)  # initialize image panel
        self.panel.pack(padx=10, pady=10)

        # create a button, that when pressed, will take the current frame and save it to file
        btn = tk.Button(self.root, text="Snapshot!", command=self.take_snapshot)
        btn.pack(fill="both", expand=True, padx=10, pady=10)

        # start a self.video_loop that constantly pools the video sensor
        # for the most recently read frame
        self.video_loop()

    def video_loop(self):
        """ Get frame from the video stream and show it in Tkinter """
        ok, frame = self.vs.read()  # read frame from video stream
        if ok:  # frame captured without any errors
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)  # convert colors from BGR to RGBA
            self.current_image = Image.fromarray(cv2image)  # convert image for PIL
            imgtk = ImageTk.PhotoImage(image=self.current_image)  # convert image for tkinter
            self.panel.imgtk = imgtk  # anchor imgtk so it does not be deleted by garbage-collector
            self.panel.config(image=imgtk)  # show the image
        self.root.after(30, self.video_loop)  # call the same function after 30 milliseconds

    def take_snapshot(self):
        """ Take snapshot and save it to the file """
        ts = datetime.datetime.now() # grab the current timestamp
        filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S"))  # construct filename
        p = os.path.join(self.output_path, filename)  # construct output path
        self.current_image.save(p, "JPEG")  # save image as jpeg file
        print("[INFO] saved {}".format(filename))

    def destructor(self):
        """ Destroy the root object and release all resources """
        print("[INFO] closing...")
        self.root.destroy()
        self.vs.release()  # release web camera
        cv2.destroyAllWindows()  # it is not mandatory in this application

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", default="./",
    help="path to output directory to store snapshots (default: current folder")
args = vars(ap.parse_args())

# start the app
print("[INFO] starting...")
pba = Application(args["output"])
pba.root.mainloop()
</code>```

Title: Using OpenCV with Tkinter

Body:
I'm writing a program that needs to display a video stream in a Tkinter window. Since there will also be buttons for performing various functions, I'm using grid to organize where everything goes.

The following code, modified from Show webcam sequence TkInter, works fine on my Raspberry Pi:

import Tkinter as tk
import cv2
from PIL import Image, ImageTk

width, height = 800, 600
cap = cv2.VideoCapture(0)

root = tk.Tk()
lmain = tk.Label(root)
lmain.pack()

def show_frame():
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_frame)

show_frame()
root.mainloop()

However, combining it with Tkinter doesn't work. (In what follows, I've tried commenting out Display 1, Display 2, and neither.)

import numpy as np
import cv2
import Tkinter as tk
import Image, ImageTk

#Set up GUI
window = tk.Tk()  #Makes main window
window.wm_title("Digital Microscope")
window.config(background="#FFFFFF")

#Graphics window
imageFrame = tk.Frame(window, width=600, height=500)
imageFrame.grid(row=0, column=0, padx=10, pady=2)

#Capture video frames
lmain = tk.Label(imageFrame)
cap = cv2.VideoCapture(0)
def show_frame():
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_frame)

tk.Label(imageFrame, image=show_frame()).grid(row=0, column=0, padx=10, pady=2)  #Display 1

#Slider window (slider controls stage position)
sliderFrame = tk.Frame(window, width=600, height=100)
sliderFrame.grid(row = 600, column=0, padx=10, pady=2)

show_frame()  #Display 2
window.mainloop()  #Starts GUI

How can I get the video to display in imageFrame?

Body:
Try this code:

from PIL import Image, ImageTk
import Tkinter as tk
import argparse
import datetime
import cv2
import os

class Application:
    def __init__(self, output_path = "./"):
        """ Initialize application which uses OpenCV + Tkinter. It displays
            a video stream in a Tkinter window and stores current snapshot on disk """
        self.vs = cv2.VideoCapture(0) # capture video frames, 0 is your default video camera
        self.output_path = output_path  # store output path
        self.current_image = None  # current image from the camera

        self.root = tk.Tk()  # initialize root window
        self.root.title("PyImageSearch PhotoBooth")  # set window title
        # self.destructor function gets fired when the window is closed
        self.root.protocol('WM_DELETE_WINDOW', self.destructor)

        self.panel = tk.Label(self.root)  # initialize image panel
        self.panel.pack(padx=10, pady=10)

        # create a button, that when pressed, will take the current frame and save it to file
        btn = tk.Button(self.root, text="Snapshot!", command=self.take_snapshot)
        btn.pack(fill="both", expand=True, padx=10, pady=10)

        # start a self.video_loop that constantly pools the video sensor
        # for the most recently read frame
        self.video_loop()

    def video_loop(self):
        """ Get frame from the video stream and show it in Tkinter """
        ok, frame = self.vs.read()  # read frame from video stream
        if ok:  # frame captured without any errors
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)  # convert colors from BGR to RGBA
            self.current_image = Image.fromarray(cv2image)  # convert image for PIL
            imgtk = ImageTk.PhotoImage(image=self.current_image)  # convert image for tkinter
            self.panel.imgtk = imgtk  # anchor imgtk so it does not be deleted by garbage-collector
            self.panel.config(image=imgtk)  # show the image
        self.root.after(30, self.video_loop)  # call the same function after 30 milliseconds

    def take_snapshot(self):
        """ Take snapshot and save it to the file """
        ts = datetime.datetime.now() # grab the current timestamp
        filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S"))  # construct filename
        p = os.path.join(self.output_path, filename)  # construct output path
        self.current_image.save(p, "JPEG")  # save image as jpeg file
        print("[INFO] saved {}".format(filename))

    def destructor(self):
        """ Destroy the root object and release all resources """
        print("[INFO] closing...")
        self.root.destroy()
        self.vs.release()  # release web camera
        cv2.destroyAllWindows()  # it is not mandatory in this application

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", default="./",
    help="path to output directory to store snapshots (default: current folder")
args = vars(ap.parse_args())

# start the app
print("[INFO] starting...")
pba = Application(args["output"])
pba.root.mainloop()

ContentLicense: CC BY-SA 4.0