问:
Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
I am developing an application with Hibernate and I get an Exception when I connect with database. The exception is:

```<code>Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
</code>```

My mapping file is:

```<code><hibernate-mapping>
<class name="com.cartif.database.SetPoint" table="SetPoint">
    <id name="iSetPointId" column="setpointid" type="java.lang.Integer">
        <generator class="sequence">
            <param name="sequence">s_setpoint</param>
        </generator>
    </id>
    <property column="sensorType" generated="never" lazy="false" name="sSensortype" type="java.lang.String"/>
    <property column="value" generated="never" lazy="false" name="dValue" type="java.lang.Double"/>
    <property column="relationship" generated="never" lazy="false" name="sRelation" type="java.lang.String"/>
    <property column="deviceid" generated="never" lazy="false" name="iDeviceId" type="java.lang.Integer"/>
</class>
</hibernate-mapping>
</code>```

And the class with getters/setters which are not included:

```<code>public class SetPoint {
    private int iSetPointId;
    private String sSensorType;
    private double dValue;
    private String sRelationship;
    private int iDeviceId;
}
</code>```

I have javassist.jar included into classpath. I do not know what is the problem. Someone would help me please.

Thanks!

I found when the error is launched. If I include properties in mapping file exception is thrown. If I only declare id of table, the exception is not thrown. What is the possible cause?

The complete stacktrace is:

```<code>162980 [btpool0-2 - /Gateway/zigbeedriver/app] ERROR org.hibernate.proxy.pojo.BasicLazyInitializer  - Javassist Enhancement failed: com.cartif.database.ApplicationField
java.lang.RuntimeException: by java.lang.NoClassDefFoundError:   javassist/util/proxy/ProxyObject
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:174)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.getProxyFactory(JavassistLazyInitializer.java:162)
at org.hibernate.proxy.pojo.javassist.JavassistProxyFactory.postInstantiate(JavassistProxyFactory.java:65)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:185)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:167)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
at sun.reflect.GeneratedConstructorAccessor12.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:105)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:133)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:322)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:485)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:286)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at com.db.manager.DatabaseManager.createSession(DatabaseManager.java:74)
at com.db.manager.DatabaseManager.loadObject(DatabaseManager.java:95)
at com.cartif.database.User.loadUser(User.java:53)
at com.cartif.database.User.checkUser(User.java:57)
at com.cartif.zigbee.ZigbeeDriverImpl.checkUser(ZigbeeDriverImpl.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.doInvoke(ServiceInvoker.java:58)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.invoke(ServiceInvoker.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invokeUnprivileged(ServiceTCCLInterceptor.java:56)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invoke(ServiceTCCLInterceptor.java:39)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.osgi.service.importer.support.LocalBundleContextAdvice.invoke(LocalBundleContextAdvice.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy21.checkUser(Unknown Source)
at main.com.cartif.app.server.AppServiceImpl.getUser(AppServiceImpl.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at main.com.cartif.app.server.AppServiceImpl.service(AppServiceImpl.java:33)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
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:320)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:842)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:450)
Caused by: javassist.CannotCompileException: by java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:167)
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:170)
... 72 more
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:159)
... 73 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.ProxyObject
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 81 more
163012 [btpool0-2 - /Gateway/zigbeedriver/app] WARN   org.hibernate.tuple.entity.PojoEntityTuplizer  - could not create proxy factory for:com.cartif.database.ApplicationField
org.hibernate.HibernateException: Javassist Enhancement failed: com.cartif.database.ApplicationField
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.getProxyFactory(JavassistLazyInitializer.java:169)
at org.hibernate.proxy.pojo.javassist.JavassistProxyFactory.postInstantiate(JavassistProxyFactory.java:65)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:185)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:167)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
at sun.reflect.GeneratedConstructorAccessor12.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:105)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:133)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:322)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:485)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:286)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at com.db.manager.DatabaseManager.createSession(DatabaseManager.java:74)
at com.db.manager.DatabaseManager.loadObject(DatabaseManager.java:95)
at com.cartif.database.User.loadUser(User.java:53)
at com.cartif.database.User.checkUser(User.java:57)
at com.cartif.zigbee.ZigbeeDriverImpl.checkUser(ZigbeeDriverImpl.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.doInvoke(ServiceInvoker.java:58)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.invoke(ServiceInvoker.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invokeUnprivileged(ServiceTCCLInterceptor.java:56)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invoke(ServiceTCCLInterceptor.java:39)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.osgi.service.importer.support.LocalBundleContextAdvice.invoke(LocalBundleContextAdvice.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy21.checkUser(Unknown Source)
at main.com.cartif.app.server.AppServiceImpl.getUser(AppServiceImpl.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at main.com.cartif.app.server.AppServiceImpl.service(AppServiceImpl.java:33)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
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:320)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:842)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:450)
Caused by: java.lang.RuntimeException: by java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:174)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.getProxyFactory(JavassistLazyInitializer.java:162)
... 71 more
Caused by: javassist.CannotCompileException: by java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:167)
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:170)
... 72 more
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:159)
... 73 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.ProxyObject
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 81 more
</code>```

答:
I had the same exception and I was excluding javassist because of its issue with powermock. Then I was adding it again as below but it was not working:

```<code><dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
   <exclusions>
      <exclusion>
         <groupId>org.javassist</groupId>
         <artifactId>javassist</artifactId>
      </exclusion>
   </exclusions>
</dependency>

<dependency>
   <groupId>org.javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.20.0-GA</version>
   <scope>test</scope>
</dependency>
</code>```

Finally I found out that I have to remove <scope>test</scope> from javassist dependency. Hope it helps someone.

ContentLicense: CC BY-SA 4.0

Body:
I am developing an application with Hibernate and I get an Exception when I connect with database. The exception is:

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

My mapping file is:

<hibernate-mapping>
<class name="com.cartif.database.SetPoint" table="SetPoint">
    <id name="iSetPointId" column="setpointid" type="java.lang.Integer">
        <generator class="sequence">
            <param name="sequence">s_setpoint</param>
        </generator>
    </id>
    <property column="sensorType" generated="never" lazy="false" name="sSensortype" type="java.lang.String"/>
    <property column="value" generated="never" lazy="false" name="dValue" type="java.lang.Double"/>
    <property column="relationship" generated="never" lazy="false" name="sRelation" type="java.lang.String"/>
    <property column="deviceid" generated="never" lazy="false" name="iDeviceId" type="java.lang.Integer"/>
</class>
</hibernate-mapping>

And the class with getters/setters which are not included:

public class SetPoint {
    private int iSetPointId;
    private String sSensorType;
    private double dValue;
    private String sRelationship;
    private int iDeviceId;
}

I have javassist.jar included into classpath. I do not know what is the problem. Someone would help me please.

Thanks!

I found when the error is launched. If I include properties in mapping file exception is thrown. If I only declare id of table, the exception is not thrown. What is the possible cause?

The complete stacktrace is:

162980 [btpool0-2 - /Gateway/zigbeedriver/app] ERROR org.hibernate.proxy.pojo.BasicLazyInitializer  - Javassist Enhancement failed: com.cartif.database.ApplicationField
java.lang.RuntimeException: by java.lang.NoClassDefFoundError:   javassist/util/proxy/ProxyObject
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:174)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.getProxyFactory(JavassistLazyInitializer.java:162)
at org.hibernate.proxy.pojo.javassist.JavassistProxyFactory.postInstantiate(JavassistProxyFactory.java:65)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:185)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:167)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
at sun.reflect.GeneratedConstructorAccessor12.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:105)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:133)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:322)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:485)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:286)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at com.db.manager.DatabaseManager.createSession(DatabaseManager.java:74)
at com.db.manager.DatabaseManager.loadObject(DatabaseManager.java:95)
at com.cartif.database.User.loadUser(User.java:53)
at com.cartif.database.User.checkUser(User.java:57)
at com.cartif.zigbee.ZigbeeDriverImpl.checkUser(ZigbeeDriverImpl.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.doInvoke(ServiceInvoker.java:58)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.invoke(ServiceInvoker.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invokeUnprivileged(ServiceTCCLInterceptor.java:56)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invoke(ServiceTCCLInterceptor.java:39)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.osgi.service.importer.support.LocalBundleContextAdvice.invoke(LocalBundleContextAdvice.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy21.checkUser(Unknown Source)
at main.com.cartif.app.server.AppServiceImpl.getUser(AppServiceImpl.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at main.com.cartif.app.server.AppServiceImpl.service(AppServiceImpl.java:33)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
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:320)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:842)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:450)
Caused by: javassist.CannotCompileException: by java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:167)
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:170)
... 72 more
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:159)
... 73 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.ProxyObject
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 81 more
163012 [btpool0-2 - /Gateway/zigbeedriver/app] WARN   org.hibernate.tuple.entity.PojoEntityTuplizer  - could not create proxy factory for:com.cartif.database.ApplicationField
org.hibernate.HibernateException: Javassist Enhancement failed: com.cartif.database.ApplicationField
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.getProxyFactory(JavassistLazyInitializer.java:169)
at org.hibernate.proxy.pojo.javassist.JavassistProxyFactory.postInstantiate(JavassistProxyFactory.java:65)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:185)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:167)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
at sun.reflect.GeneratedConstructorAccessor12.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:105)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:133)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:322)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:485)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:286)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at com.db.manager.DatabaseManager.createSession(DatabaseManager.java:74)
at com.db.manager.DatabaseManager.loadObject(DatabaseManager.java:95)
at com.cartif.database.User.loadUser(User.java:53)
at com.cartif.database.User.checkUser(User.java:57)
at com.cartif.zigbee.ZigbeeDriverImpl.checkUser(ZigbeeDriverImpl.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.doInvoke(ServiceInvoker.java:58)
at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.invoke(ServiceInvoker.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invokeUnprivileged(ServiceTCCLInterceptor.java:56)
at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invoke(ServiceTCCLInterceptor.java:39)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.osgi.service.importer.support.LocalBundleContextAdvice.invoke(LocalBundleContextAdvice.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy21.checkUser(Unknown Source)
at main.com.cartif.app.server.AppServiceImpl.getUser(AppServiceImpl.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at main.com.cartif.app.server.AppServiceImpl.service(AppServiceImpl.java:33)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
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:320)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:842)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:450)
Caused by: java.lang.RuntimeException: by java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:174)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.getProxyFactory(JavassistLazyInitializer.java:162)
... 71 more
Caused by: javassist.CannotCompileException: by java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:167)
at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:170)
... 72 more
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/ProxyObject
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:159)
... 73 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.ProxyObject
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:506)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:422)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:410)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 81 more

Body:
I had the same exception and I was excluding javassist because of its issue with powermock. Then I was adding it again as below but it was not working:

<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
   <exclusions>
      <exclusion>
         <groupId>org.javassist</groupId>
         <artifactId>javassist</artifactId>
      </exclusion>
   </exclusions>
</dependency>

<dependency>
   <groupId>org.javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.20.0-GA</version>
   <scope>test</scope>
</dependency>

Finally I found out that I have to remove <scope>test</scope> from javassist dependency. Hope it helps someone.


来源: stackexchange

问:
PHP MySQL Query Where x = $variable from function
Why is this not working:

```<code>function listOrderComments ($factnr){
global $connection;

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
</code>```

When I echo $factnr I get "123" back.

When I uncommented //$factnr = 123; my function is working.

Looked everywhere for a solution. check the type $factnr is (string).

答:
Use it correctly over "doted" concat. Following will just work fine:

```<code>$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
</code>```

UPDATE:

here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.

```<code>function listOrderComments ($factnr){
global $connection;

if (!is_int($factnr)) return -1

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Why is this not working:

function listOrderComments ($factnr){
global $connection;

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);

When I echo $factnr I get "123" back.

When I uncommented //$factnr = 123; my function is working.

Looked everywhere for a solution. check the type $factnr is (string).

Body:
Use it correctly over "doted" concat. Following will just work fine:

$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;

UPDATE:

here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.

function listOrderComments ($factnr){
global $connection;

if (!is_int($factnr)) return -1

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);


问:
add an image inside a primeNG's DialogModal?
I'm trying to display an image inside a primeNG's DialogModal.

How can I do it?

Html part :

```<code><p-dialog header="Détails de la page" [(visible)]="displayDialog"
 [responsive]="true" showEffect="fade" [modal]="true" width="1000"
(onAfterHide)="onDialogHide()">
   <div class="ui-grid ui-grid-responsive ui-fluid" *ngIf="selectedPage"
     style="font-size:16px;text-align:center;padding:20px">
       <div class="ui-grid-row">
         <div class="ui-grid-col-12" style="text-align:center">
        {{selectedPage.pageId}}
             <img  src={{selectedPage.url}} width="45%" height="85% />
         </div>
       </div>
  </div>
</p-dialog>
</code>```

The result is :

答:
You seem to forget quotation marks in your html. Also, use object binding [] instead of interpolation {{}}

Change

to

Body:
I'm trying to display an image inside a primeNG's DialogModal.

How can I do it?

Html part :

        {{selectedPage.pageId}}

The result is :

Body:
You seem to forget quotation marks in your html. Also, use object binding [] instead of interpolation {{}}

Change

<img  src={{selectedPage.url}} width="45%" height="85% />

to

<img [src]="selectedPage.url" width="45%" height="85%" />


问:
How to get Up Navigation behavior exactly like back button pressed
How can I get the Up Navigation button to behave like the back button? When I press the back button all my previous activities remain as the were prior.
When I press the up button my activities return to initial state. I tried hooking up onBackPressed(); to case R.id.home on my onOptionsItemSelected but it still behaves differently.

Visual:
Back Button Behavior-
https://www.flickr.com/photos/151974643@N07/35702817566/in/dateposted-public/ Up Button Behavior - https://www.flickr.com/photos/151974643@N07/35702812926/in/dateposted-public/
Any help would be appreciated. Thank you!

答:
You can do it several ways, put this code in onCreate() method of your activity

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        YOUR_ACTIVITY.this.onBackPressed();
    }
});
</code>```

Hope it helps.

Body:
You can do it several ways, put this code in onCreate() method of your activity

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        YOUR_ACTIVITY.this.onBackPressed();
    }
});

Hope it helps.


问:
How to change results in Access query?
I have a table, we'll call it users.

```<code>id username type
</code>```

The type field is a two character type, so each user either has US, MO, AD.  Not sure why the original developer did this, but I cannot change this method, unfortunately.

```<code>1 mike US
2 Tim AD
3 mark MO
</code>```

Instead of returning US, AD... etc types in Access, I'd like the query to replace the US with USER, replace MO with MODERATOR, and replace AD with ADMIN.

Is this possible?

Kind of like SELECT * FROM USERS and then if statements within Access (if US, then USER).  Not sure how to proceed?

答:
You can create a table for the US to USER, MO to MODERATOR etc mappings and use it in a join.

A lot easier to maintain, extend (i.e. different languages) than hard-coding with the drawback that you need to maintain your mapping table.

ContentLicense: CC BY-SA 2.5

Title: How to change results in Access query?

Body:
I have a table, we'll call it users.

id username type

The type field is a two character type, so each user either has US, MO, AD.  Not sure why the original developer did this, but I cannot change this method, unfortunately.

1 mike US
2 Tim AD
3 mark MO

Instead of returning US, AD... etc types in Access, I'd like the query to replace the US with USER, replace MO with MODERATOR, and replace AD with ADMIN.

Is this possible?

Kind of like SELECT * FROM USERS and then if statements within Access (if US, then USER).  Not sure how to proceed?


问:
Full Text Search through specific column using django postgres's builtin full text search
I'd like to use full text search on my database and choose which columns to search through. Is there a way to search through a specific column (like only fruits) when I only I have one search_vector field in my Food model that contains all the columns (fruits, vegetables, dairy). I'd also like to search through all the columns so that's why I combined all the search vectors.

I am using Django 1.11

Here's my model:

```<code>class Food(models.Model):
    fruits = models.CharField(max_length=50)
    vegetables = models.CharField(max_length=50)
    dairy = models.CharField(max_length=50)
    search_vector = SearchVectorField(null=True)
</code>```

Here's how I store the vectors:

```<code>vector= SearchVector('fruits', weight='A') + \
        SearchVector('vegetables', weight='B') + \
        SearchVector('dairy', weight='C') + \
Food.objects.annotate(document=vector).values_list('document', flat=True)

for f in Food.objects.annotate(document=vector):
    f.search_vector = f.document
    f.save(update_fields=['search_vector'])
</code>```

Here's how I search:

```<code>search_result = Food.objects\
    .annotate(rank=SearchRank(F('search_vector'), "apple"))\
    .filter(search_vector="apple")\
</code>```

Is there an easy way of only searching in fruit column in the search_vector that I set up, or would I have to set up a separate search vector for each column?

答:
Was able to accomplish this by simply filtering </p>

```<code>result = Food.objects.filter(**{fruits + "__search": "apple"})
</code>```

Body:
I'd like to use full text search on my database and choose which columns to search through. Is there a way to search through a specific column (like only fruits) when I only I have one search_vector field in my Food model that contains all the columns (fruits, vegetables, dairy). I'd also like to search through all the columns so that's why I combined all the search vectors.

I am using Django 1.11

Here's my model:

class Food(models.Model):
    fruits = models.CharField(max_length=50)
    vegetables = models.CharField(max_length=50)
    dairy = models.CharField(max_length=50)
    search_vector = SearchVectorField(null=True)

Here's how I store the vectors:

vector= SearchVector('fruits', weight='A') + \
        SearchVector('vegetables', weight='B') + \
        SearchVector('dairy', weight='C') + \
Food.objects.annotate(document=vector).values_list('document', flat=True)

for f in Food.objects.annotate(document=vector):
    f.search_vector = f.document
    f.save(update_fields=['search_vector'])

Here's how I search:

search_result = Food.objects\
    .annotate(rank=SearchRank(F('search_vector'), "apple"))\
    .filter(search_vector="apple")\

Is there an easy way of only searching in fruit column in the search_vector that I set up, or would I have to set up a separate search vector for each column?

Body:
Was able to accomplish this by simply filtering

result = Food.objects.filter(**{fruits + "__search": "apple"})


问:
Python: Extract parts of a string somehow got pushed down to a new line
I use this code to extract the part after the final "/" of an html. I want to have that partition right after the link itself, separated by a comma. However, in the output file, the partition always got pushed down to a new line, not continuously attached to the associated link line. </p>

```<code> with open('links_parts.txt', mode='wt') as outfile:
   for link in file_to_set('links.txt'):
     path_parts = link.rpartition('/')[2]
     outfile.write(link + ','+ path_parts + '\n')
</code>```

答:
That's because link is a line and therefore has a trailing new line character which you need to strip using str.rstrip:

```<code>for link in file_to_set('links.txt'):
    link = link.rstrip()
    path_parts = link.rpartition('/')[2]
    outfile.write(link + ',' + path_parts + '\n')
</code>```

Body:
I use this code to extract the part after the final "/" of an html. I want to have that partition right after the link itself, separated by a comma. However, in the output file, the partition always got pushed down to a new line, not continuously attached to the associated link line.

 with open('links_parts.txt', mode='wt') as outfile:
   for link in file_to_set('links.txt'):
     path_parts = link.rpartition('/')[2]
     outfile.write(link + ','+ path_parts + '\n')

Body:
That's because link is a line and therefore has a trailing new line character which you need to strip using str.rstrip:

for link in file_to_set('links.txt'):
    link = link.rstrip()
    path_parts = link.rpartition('/')[2]
    outfile.write(link + ',' + path_parts + '\n')


问:
How can I check if a user, that has been pass in parameters to bash script, really exists?
I have simple bash script, that shows information about user

```<code>#!/bin/bash

grep home /etc/passwd | grep $1
</code>```

If I pass to script incorrect name, for example, ./script_find_users.sh bbbbbbbbbbbbb

the script gives nothing in output, but I want at least some simple message

```<code>echo "User does't exists"
</code>```

答:
Check the return status:</p>

```<code>#!/bin/bash

if ! grep home /etc/passwd | grep -- "$1"; then
  echo User "$1" does not have an entry in /etc/passwd >&2
fi
</code>```

Body:
I have simple bash script, that shows information about user

#!/bin/bash

grep home /etc/passwd | grep $1

If I pass to script incorrect name, for example, ./script_find_users.sh bbbbbbbbbbbbb

the script gives nothing in output, but I want at least some simple message

echo "User does't exists"

Body:
Check the return status:

#!/bin/bash

if ! grep home /etc/passwd | grep -- "$1"; then
  echo User "$1" does not have an entry in /etc/passwd >&2
fi


问:
How can i loop webm videos without delay?
Hi all, i want to run a webm-video in browser from desktop (from pc). Now i have looped the webm with this .js-file that i found:

```<code>// ==UserScript==
// @name        Webm Looper
// @namespace   com.whatisthisimnotgoodwithcomputers.webmlooper
// @author      WhatIsThisImNotGoodWithComputers
// @description A userscript which automatically enables looping on Webm videos in your browser.
// @include       *.webm
// @run-at      document-start
// @version     1.0
// @grant       none
// ==/UserScript==

var vids = document.getElementsByTagName("video");
for (i = 0; i < vids.length; i++)
 vids[i].setAttribute("loop", "true");
</code>```

in Greasemonkey. It works, but there is a small delay in the repeat/loop. It shall look like if i run a gif
in browser. Now i have looked for a solution and have found something in the forum:

Issue setting currentTime in HTML5 video

But it doesn't work in Greasemonkey. This is my code in Greasemonkey:

```<code>// ==UserScript==
// @name        Loop
// @namespace   Loop
// @version     1
// @include *.webm
// @run-at      document-start
// @grant       none
// ==/UserScript==

var vids = document.getElementsByTagName("video");
vids.play();
vids.addEventListener('canplay', function() {
 this.currentTime = 5;
});
</code>```

The webm stops after first run.

The javascript-setting shows that video.play(); is not a function and the same at addeventlistener.

Maybe you can help me with this problem. What can i improve? Do i have to install something other or change?

Unfortunately I'm only a newbie in the programming.

Thanks in advance!

Regards

答:
what you need to do is track the currentTime attribute (you can use the timeupdate event for that) and when it gets close to the end (the duration attribute) you can reset it back to the start

In the sample below it uses the loadedmetadata event to know when the duration is available for the script, and starts the video playing and attaches a listener to timeupdate that then tracks the currentTime

```<code><html>
<head>
<title>Video Looper Page</title>
</head>
<body>

<video id="video" muted preload="metadata" controls>
    <source src="video.mp4" type="video/mp4" />
</video>

<script>
video = document.getElementById("video")
video.addEventListener("loadedmetadata",init)

function init() {
    video.removeEventListener("loadedmetadata",init)
    video.play()
    video.addEventListener('timeupdate',
        funcloop=function(){
            if (video.currentTime >= (video.duration - 1)) {
                video.currentTime = 1;
                video.play()
            }
        }, false);
    }
</script>

</body>
</html>
</code>```

Second version which demonstrates use of setInterval to control the loop. Allows for smaller test interval

```<code><html>
<head>
<title>Video Looper Page</title>
</head>
<body>

<video id="video" muted preload="metadata" controls>
    <source src="video.mp4" type="video/mp4" />
</video>

<script>
video = document.getElementById("video")
video.addEventListener("loadedmetadata",init)

function init() {
    video.removeEventListener("loadedmetadata",init)
    video.play()
    t = setInterval(looper, 100);
}

function looper() {
    console.log(video.currentTime);
    if (video.currentTime >= (video.duration - 0.1)) {
        video.currentTime = 0.2;
        video.play()
    }
}

</script>
</body>
</html>
</code>```

Body:
Hi all, i want to run a webm-video in browser from desktop (from pc). Now i have looped the webm with this .js-file that i found:

// ==UserScript==
// @name        Webm Looper
// @namespace   com.whatisthisimnotgoodwithcomputers.webmlooper
// @author      WhatIsThisImNotGoodWithComputers
// @description A userscript which automatically enables looping on Webm videos in your browser.
// @include       *.webm
// @run-at      document-start
// @version     1.0
// @grant       none
// ==/UserScript==

var vids = document.getElementsByTagName("video");
for (i = 0; i < vids.length; i++)
 vids[i].setAttribute("loop", "true");

in Greasemonkey. It works, but there is a small delay in the repeat/loop. It shall look like if i run a gif
in browser. Now i have looked for a solution and have found something in the forum:

Issue setting currentTime in HTML5 video

But it doesn't work in Greasemonkey. This is my code in Greasemonkey:

// ==UserScript==
// @name        Loop
// @namespace   Loop
// @version     1
// @include *.webm
// @run-at      document-start
// @grant       none
// ==/UserScript==

var vids = document.getElementsByTagName("video");
vids.play();
vids.addEventListener('canplay', function() {
 this.currentTime = 5;
});

The webm stops after first run.

The javascript-setting shows that video.play(); is not a function and the same at addeventlistener.

Maybe you can help me with this problem. What can i improve? Do i have to install something other or change?

Unfortunately I'm only a newbie in the programming.

Thanks in advance!

Regards

Body:
what you need to do is track the currentTime attribute (you can use the timeupdate event for that) and when it gets close to the end (the duration attribute) you can reset it back to the start

In the sample below it uses the loadedmetadata event to know when the duration is available for the script, and starts the video playing and attaches a listener to timeupdate that then tracks the currentTime

<html>
<head>
<title>Video Looper Page</title>
</head>
<body>

<video id="video" muted preload="metadata" controls>
    <source src="video.mp4" type="video/mp4" />
</video>

<script>
video = document.getElementById("video")
video.addEventListener("loadedmetadata",init)

function init() {
    video.removeEventListener("loadedmetadata",init)
    video.play()
    video.addEventListener('timeupdate',
        funcloop=function(){
            if (video.currentTime >= (video.duration - 1)) {
                video.currentTime = 1;
                video.play()
            }
        }, false);
    }
</script>

</body>
</html>

Second version which demonstrates use of setInterval to control the loop. Allows for smaller test interval

<html>
<head>
<title>Video Looper Page</title>
</head>
<body>

<video id="video" muted preload="metadata" controls>
    <source src="video.mp4" type="video/mp4" />
</video>

<script>
video = document.getElementById("video")
video.addEventListener("loadedmetadata",init)

function init() {
    video.removeEventListener("loadedmetadata",init)
    video.play()
    t = setInterval(looper, 100);
}

function looper() {
    console.log(video.currentTime);
    if (video.currentTime >= (video.duration - 0.1)) {
        video.currentTime = 0.2;
        video.play()
    }
}

</script>
</body>
</html>


问:
Applescript to make new folder
I Want to make a new Folder command in apple script

Why dosent this script work?

```<code>tell application "Finder"
activate
end tell
tell application "System Events"
tell process "Finder"
    tell menu bar 1
        tell menu bar item "File"
            tell menu "File"
                click menu item "New folder"
            end tell
        end tell
    end tell
end tell
end tell
</code>```

答:
You can do it more directly with AppleScript:</p>

```<code>tell application "Finder"
    set p to path to desktop -- Or whatever path you want
    make new folder at p with properties {name:"New Folder"}
end tell
</code>```

Title: Applescript to make new folder

Body:
I Want to make a new Folder command in apple script

Why dosent this script work?

tell application "Finder"
activate
end tell
tell application "System Events"
tell process "Finder"
    tell menu bar 1
        tell menu bar item "File"
            tell menu "File"
                click menu item "New folder"
            end tell
        end tell
    end tell
end tell
end tell

Body:
You can do it more directly with AppleScript:

tell application "Finder"
    set p to path to desktop -- Or whatever path you want
    make new folder at p with properties {name:"New Folder"}
end tell


问:
Turn SELECT into DELETE mysql php
I am having a heck of a time turn this SELECT statement into a DELETE.

```<code>$query  = "
SELECT n.thread_id
     , n.status
     , n.status_tooltip_text
  FROM newmessages n
     , oldmessages o
 WHERE n.thread_id = o.thread_id
   AND n.status_tooltip_text = o.status_tooltip_text
";
</code>```

The end result I am trying to achieve is to delete from newmessages where the status tooltip text is the same as the status tooltip in oldmessages.

The select I have above works, but when I turn the select into a delete it says database query failed.  The columns in the two tables have identical column definitions.

答:
This is how I got it to work:</p>

```<code>$query  = "DELETE FROM newmessages where thread_id in ";
                $query .= "(SELECT thread_id FROM oldmessages ";
                $query .= "WHERE oldmessages.thread_id=newmessages.thread_id ";
                $query .= "AND oldmessages.status_tooltip_text=newmessages.status_tooltip_text ";
                $query .= "AND oldmessages.status=newmessages.status)";
</code>```

Title: Turn SELECT into DELETE mysql php

Body:
I am having a heck of a time turn this SELECT statement into a DELETE.

$query  = "
SELECT n.thread_id
     , n.status
     , n.status_tooltip_text
  FROM newmessages n
     , oldmessages o
 WHERE n.thread_id = o.thread_id
   AND n.status_tooltip_text = o.status_tooltip_text
";

The end result I am trying to achieve is to delete from newmessages where the status tooltip text is the same as the status tooltip in oldmessages.

The select I have above works, but when I turn the select into a delete it says database query failed.  The columns in the two tables have identical column definitions.

Body:
This is how I got it to work:

$query  = "DELETE FROM newmessages where thread_id in ";
                $query .= "(SELECT thread_id FROM oldmessages ";
                $query .= "WHERE oldmessages.thread_id=newmessages.thread_id ";
                $query .= "AND oldmessages.status_tooltip_text=newmessages.status_tooltip_text ";
                $query .= "AND oldmessages.status=newmessages.status)";


问:
How to install Nokogiri using Chef
I have chef-solo version 12.6

In my recipe I have this code:

```<code>ruby_block "Parse the XML File " do
    block do
        require 'nokogiri'
    end
end
</code>```

But I am getting this exception:

```<code>LoadError
---------
cannot load such file -- nokogiri
</code>```

I used the omnibus chef installer and I cannot upgrade to the latest chef-solo.

How do I get Nokogiri to load?

答: Unfortunately we didn't start including Nokogiri in the installers until Chef 12.7.</p>

Title: How to install Nokogiri using Chef

Body:
I have chef-solo version 12.6

In my recipe I have this code:

ruby_block "Parse the XML File " do
    block do
        require 'nokogiri'
    end
end

But I am getting this exception:

LoadError
---------
cannot load such file -- nokogiri

I used the omnibus chef installer and I cannot upgrade to the latest chef-solo.

How do I get Nokogiri to load?


问:
With command-line jgit, how to checkout a single file back to its git version?
For example jgit diff returns 1 changed file, I want to revert it back to the versioned version. In normal git I would just

```<code>$ git checkout path_to_file
</code>```

I tried

```<code>$ jgit checkout origin/master -- path_to_file
</code>```

but nothing changes, no error, no nothing and the file remains

UPDATE

I tried:

$ jgit checkout origin/master -- path_to_file - no change

$ jgit checkout -- path_to_file - no change

$ jgit checkout path_to_file - error: error: pathspec path_to_file' did not match any file(s) known to git.

$ jgit clean - wants to clean untracked files, not untracked changes

$ jgit checkout -f origin/some_other_branch; $ jgit checkout -f origin/master - hoping that this would squash the changes, but then simply the 2nd command fails because "changes would be overwritten"

...and many more things I don't remember any more ofc :)

答:
Actually I just tried, and jgit checkout -- path_to_file works for me:

```<code>~/Development/Eclipse/jgit (master)

$ org.eclipse.jgit.pgm/target/jgit --version
jgit version 4.9.0-SNAPSHOT

$ org.eclipse.jgit.pgm/target/jgit status
On branch master

$ echo "dummy" > pom.xml

$ org.eclipse.jgit.pgm/target/jgit status
On branch master
Changes not staged for commit:

        modified:   pom.xml

$ org.eclipse.jgit.pgm/target/jgit checkout -- pom.xml

$ org.eclipse.jgit.pgm/target/jgit status
On branch master
</code>```

Body:
For example jgit diff returns 1 changed file, I want to revert it back to the versioned version. In normal git I would just

$ git checkout path_to_file

I tried

$ jgit checkout origin/master -- path_to_file

but nothing changes, no error, no nothing and the file remains

UPDATE

I tried:

$ jgit checkout origin/master -- path_to_file - no change

$ jgit checkout -- path_to_file - no change

$ jgit checkout path_to_file - error: error: pathspec path_to_file' did not match any file(s) known to git.

$ jgit clean - wants to clean untracked files, not untracked changes

$ jgit checkout -f origin/some_other_branch; $ jgit checkout -f origin/master - hoping that this would squash the changes, but then simply the 2nd command fails because "changes would be overwritten"

...and many more things I don't remember any more ofc :)

Body:
Actually I just tried, and jgit checkout -- path_to_file works for me:

~/Development/Eclipse/jgit (master)

$ org.eclipse.jgit.pgm/target/jgit --version
jgit version 4.9.0-SNAPSHOT

$ org.eclipse.jgit.pgm/target/jgit status
On branch master

$ echo "dummy" > pom.xml

$ org.eclipse.jgit.pgm/target/jgit status
On branch master
Changes not staged for commit:

        modified:   pom.xml

$ org.eclipse.jgit.pgm/target/jgit checkout -- pom.xml

$ org.eclipse.jgit.pgm/target/jgit status
On branch master


问:
How to check if the dictionary has only one key with value "1"
I have a dictionary with 2 keys. Only one key can have value 1. If both keys have value 1, it should give the error message.

Here is the working code which I tried, but want to know if there is any way to optimize the same?

```<code>>>> trmode_data = {'continuous': 1, 'fixed': 1}

>>> new = []
>>> for k, v in trmode_data.items():
...  if v == 1:
...   new.append(k)

>>> if len(new) > 1:
...  print "unexpected"
...
unexpected
</code>```

Whichever key has value 1, that key is to be used further. So basically above code is needed to verify that the dictionary has expected values for the keys or not.

答:
Given your statement:

Whichever key has value 1, that key is to be used further.

It sounds like you want to continue using your dictionary, just w/o the dup key(s) with the value of 1.  (And I'm going to assume you want uniqueness for all values, not just 1.)

You can achive this by inverting the dictionary.  Example:

```<code>x = {'a':1, 'b':1, 'c':2}

x_ = {v:k for k,v in x.items()}
x = {v:k for k,v in x_.items()}

print x
</code>```

Run:

```<code>$ python test2.py
{'c': 2, 'b': 1}
</code>```

BTW, you almost certainty want to use an OrderedDict when reading in from wherever you're reading from, otherwise which key "wins" will be effectively random.  But with some sort of ordered dictionary implementation, the last will always win, which is what you specified.

Good luck!

Body:
I have a dictionary with 2 keys. Only one key can have value 1. If both keys have value 1, it should give the error message.

Here is the working code which I tried, but want to know if there is any way to optimize the same?

>>> trmode_data = {'continuous': 1, 'fixed': 1}

>>> new = []
>>> for k, v in trmode_data.items():
...  if v == 1:
...   new.append(k)

>>> if len(new) > 1:
...  print "unexpected"
...
unexpected

Whichever key has value 1, that key is to be used further. So basically above code is needed to verify that the dictionary has expected values for the keys or not.

Body:
Given your statement:

Whichever key has value 1, that key is to be used further.

It sounds like you want to continue using your dictionary, just w/o the dup key(s) with the value of 1.  (And I'm going to assume you want uniqueness for all values, not just 1.)

You can achive this by inverting the dictionary.  Example:

x = {'a':1, 'b':1, 'c':2}

x_ = {v:k for k,v in x.items()}
x = {v:k for k,v in x_.items()}

print x

Run:

$ python test2.py
{'c': 2, 'b': 1}

BTW, you almost certainty want to use an OrderedDict when reading in from wherever you're reading from, otherwise which key "wins" will be effectively random.  But with some sort of ordered dictionary implementation, the last will always win, which is what you specified.

Good luck!


问:
How to establish serial connection in PyQT5
I am new to python. I am developing a GUI in Qt using python 3.6 (pyqt5). I have a connect button that establishes serial connection with the device. Now the GUI has other buttons as well. But they should only work if the connect button has been pressed and a serial connection has been established. At all other times it should post a message 'Device not connected'. Here's a part of the code:

```<code>import serial, time
import sys
import PyQt5
from PyQt5.QtWidgets import *
import mainwindow_auto
class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        #define gui actions here
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.constat=0

        self.plus_y_button.clicked.connect(self.moveplusy)
        self.connect_button.clicked.connect(self.connect_printer)

    def connect_printer(self):

        port=str(self.port_sel_box.currentText())
        baudrate=str(self.baud_sel_box.currentText())

        try:
            ser = serial.Serial(port, baudrate)
            self.log_box.append('Connecting to printer....\nPort selected :'+self.port_sel_box.currentText()+'\nBaud Rate :'+self.baud_sel_box.currentText())

        except serial.serialutil.SerialException:
            self.log_box.append('No device available....Please connect a device')
    def moveplusy(self):
       if(ser.isOpen()==true):

           print('moving Y by +1')
           self.log_box.append('moving Y by +1')
       else:
           print('No device available')
</code>```

this is only a part of the code,I have not included all the widgets in the code, but only the relevant parts.When I run the code the gui window opens, but when i press the plus_y_button python crashes.One way would be to make the serial connection in the constructor function, but I want the serial connection to take place only when I press the connect_button. This is a screenshot of what happens when I press the plus_y_button:

Any idea as on how to solve it?

答:
In the function "connect_printer" you locally define the variable "ser" which then gets destroyed when the function is finished. In order to use "ser" in the function "moveplusy" you need to define it as a member of the class (e.g. self.ser). Additionally, "True" should be capitalized in the function.</p>

```<code>import serial, time
import sys
import PyQt5
from PyQt5.QtWidgets import *
import mainwindow_auto
class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        #define gui actions here
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.constat=0

        self.plus_y_button.clicked.connect(self.moveplusy)
        self.connect_button.clicked.connect(self.connect_printer)

    def connect_printer(self):

        port=str(self.port_sel_box.currentText())
        baudrate=str(self.baud_sel_box.currentText())

        try:
            self.ser = serial.Serial(port, baudrate)
            self.log_box.append('Connecting to printer....\nPort selected :'+self.port_sel_box.currentText()+'\nBaud Rate :'+self.baud_sel_box.currentText())

        except serial.serialutil.SerialException:
            self.log_box.append('No device available....Please connect a device')
    def moveplusy(self):
       if self.ser.isOpen():

           print('moving Y by +1')
           self.log_box.append('moving Y by +1')
       else:
           print('No device available')
</code>```

Body:
I am new to python. I am developing a GUI in Qt using python 3.6 (pyqt5). I have a connect button that establishes serial connection with the device. Now the GUI has other buttons as well. But they should only work if the connect button has been pressed and a serial connection has been established. At all other times it should post a message 'Device not connected'. Here's a part of the code:

import serial, time
import sys
import PyQt5
from PyQt5.QtWidgets import *
import mainwindow_auto
class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        #define gui actions here
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.constat=0

        self.plus_y_button.clicked.connect(self.moveplusy)
        self.connect_button.clicked.connect(self.connect_printer)

    def connect_printer(self):

        port=str(self.port_sel_box.currentText())
        baudrate=str(self.baud_sel_box.currentText())

        try:
            ser = serial.Serial(port, baudrate)
            self.log_box.append('Connecting to printer....\nPort selected :'+self.port_sel_box.currentText()+'\nBaud Rate :'+self.baud_sel_box.currentText())

        except serial.serialutil.SerialException:
            self.log_box.append('No device available....Please connect a device')
    def moveplusy(self):
       if(ser.isOpen()==true):

           print('moving Y by +1')
           self.log_box.append('moving Y by +1')
       else:
           print('No device available')

this is only a part of the code,I have not included all the widgets in the code, but only the relevant parts.When I run the code the gui window opens, but when i press the plus_y_button python crashes.One way would be to make the serial connection in the constructor function, but I want the serial connection to take place only when I press the connect_button. This is a screenshot of what happens when I press the plus_y_button:

Any idea as on how to solve it?

Body:
In the function "connect_printer" you locally define the variable "ser" which then gets destroyed when the function is finished. In order to use "ser" in the function "moveplusy" you need to define it as a member of the class (e.g. self.ser). Additionally, "True" should be capitalized in the function.

import serial, time
import sys
import PyQt5
from PyQt5.QtWidgets import *
import mainwindow_auto
class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        #define gui actions here
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.constat=0

        self.plus_y_button.clicked.connect(self.moveplusy)
        self.connect_button.clicked.connect(self.connect_printer)

    def connect_printer(self):

        port=str(self.port_sel_box.currentText())
        baudrate=str(self.baud_sel_box.currentText())

        try:
            self.ser = serial.Serial(port, baudrate)
            self.log_box.append('Connecting to printer....\nPort selected :'+self.port_sel_box.currentText()+'\nBaud Rate :'+self.baud_sel_box.currentText())

        except serial.serialutil.SerialException:
            self.log_box.append('No device available....Please connect a device')
    def moveplusy(self):
       if self.ser.isOpen():

           print('moving Y by +1')
           self.log_box.append('moving Y by +1')
       else:
           print('No device available')


问:
Azure B2C Oauth: Could not establish trust relationship for the SSL/TLS secure channel
I'm following the tutorial from https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-reference-oauth-code/

I'm unable to continue with the Oauth token aquisition part after signing in and redirecting to the OAuthCallback

here's where I invoke it

```<code>    public async static Task<AdAcessToken> ExchangeCodeForAccessToken(string userId, string conversationId, string code, string AdOauthCallback)
    {
        var uri = new Uri("https://login.microsoftonline.com/baad.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_sign-in");

        var formdata = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "authorization_code"),
            new KeyValuePair<string, string>("client_id", Constants.ADClientId),
            new KeyValuePair<string, string>("scope", "openid offline_access"),
            new KeyValuePair<string, string>("code", code),
            new KeyValuePair<string, string>("redirect_uri", AdOauthCallback)
        });

        var data = new
        {
            grant_type = "authorization_code",
            client_id = Constants.ADClientId,
            scope = "openid offline_access",
            code = code,
            redirect_uri = AdOauthCallback
        };

        return await AdPostRequest<AdAcessToken>(uri,data);
    }
</code>```

Here's my method

```<code>    private static async Task<T> AdPostRequest<T>(Uri uri, Object data)
    {
        string json;

        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://login.microsoftonline.com/");
            client.DefaultRequestHeaders.Host = "microsoftonline.com";
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            var returned = await client.PostAsJsonAsync(uri, data).ConfigureAwait(false);    //SSL ERROR IM STUCK HERE!!!!
            json = returned.Content.ReadAsStringAsync().Result;
        }

        try
        {
            var result = JsonConvert.DeserializeObject<T>(json);
            return result;
        }
        catch (JsonException ex)
        {
            throw new ArgumentException("Unable to deserialize the AD response.", ex);
        }
    }
</code>```

here's the error output

```<code>This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>An error occurred while sending the request.</ExceptionMessage>
<ExceptionType>System.Net.Http.HttpRequestException</ExceptionType>
<StackTrace>
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult() at VSTF_RD_Bot.AdHelpers.<AdPostRequest>d__7`1.MoveNext() in C:\Users\bob\Development\BotFrameworkSample-master\Bot\VSTF_RD_Bot\AdHelpers.cs:line 130 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at VSTF_RD_Bot.AdHelpers.<ExchangeCodeForAccessToken>d__2.MoveNext() in C:\Users\bob\Development\BotFrameworkSample-master\Bot\VSTF_RD_Bot\AdHelpers.cs:line 73 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at VSTF_RD_Bot.Controllers.OAuthCallbackController.<OAuthCallback>d__0.MoveNext() in C:\Users\bob\Development\BotFrameworkSample-master\Bot\VSTF_RD_Bot\Controllers\OAuthCallbackController.cs:line 34 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
</ExceptionMessage>
<ExceptionType>System.Net.WebException</ExceptionType>
<StackTrace>
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The remote certificate is invalid according to the validation procedure.
</ExceptionMessage>
<ExceptionType>
System.Security.Authentication.AuthenticationException
</ExceptionType>
<StackTrace>
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult) at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
</StackTrace>
</InnerException>
</InnerException>
</Error>
</code>```

Please advise. I've even done the Powershell step but doesn't seem to be working.

```<code>Step 5: Trust the IIS Express SSL certificate

Since the web API is SSL protected, the client of the API (the web app) will refuse the SSL connection to the web API unless it trusts the API's SSL certificate. Use the following steps in Windows Powershell to trust the IIS Express SSL certificate. You only need to do this once. If you fail to do this step, calls to the TodoListService will always throw an unhandled exception where the inner exception message is:

"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

To configure your computer to trust the IIS Express SSL certificate, begin by opening a Windows Powershell command window as Administrator.

Query your personal certificate store to find the thumbprint of the certificate for CN=localhost:

PS C:\windows\system32> dir Cert:\LocalMachine\My

    Directory: Microsoft.PowerShell.Security\Certificate::LocalMachine\My
</code>```

I am unable to continue. How can I resolve this issue, there doesn't seem to be any updates on the documentation, have I missed something?

答:
Are you debugging your application with Chrome?
If so, try this:
1) Debug with any IE or Firefox
2) When the browser displays the Not Secure warning message, click Advanced.
3) Once in Advanced, search for View Certificate
4) Once you find View Certificate, save it to disk.
5) Stop debugging and start again, but this time with Chrome
6) When the Not Secure warning appears, go to settings of Chrome, Advanced, Manage Certificates
7) Import the saved certificate using the defaults.

This is basically a way of registering a self-signed certificate. There are other ways of doing it so the system will trust on it, but this is what I did here and it worked fine.
Hope it helps.

Body:
I'm following the tutorial from https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-reference-oauth-code/

I'm unable to continue with the Oauth token aquisition part after signing in and redirecting to the OAuthCallback

here's where I invoke it

    public async static Task<AdAcessToken> ExchangeCodeForAccessToken(string userId, string conversationId, string code, string AdOauthCallback)
    {
        var uri = new Uri("https://login.microsoftonline.com/baad.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_sign-in");

        var formdata = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "authorization_code"),
            new KeyValuePair<string, string>("client_id", Constants.ADClientId),
            new KeyValuePair<string, string>("scope", "openid offline_access"),
            new KeyValuePair<string, string>("code", code),
            new KeyValuePair<string, string>("redirect_uri", AdOauthCallback)
        });

        var data = new
        {
            grant_type = "authorization_code",
            client_id = Constants.ADClientId,
            scope = "openid offline_access",
            code = code,
            redirect_uri = AdOauthCallback
        };

        return await AdPostRequest<AdAcessToken>(uri,data);
    }

Here's my method

    private static async Task<T> AdPostRequest<T>(Uri uri, Object data)
    {
        string json;

        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://login.microsoftonline.com/");
            client.DefaultRequestHeaders.Host = "microsoftonline.com";
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            var returned = await client.PostAsJsonAsync(uri, data).ConfigureAwait(false);    //SSL ERROR IM STUCK HERE!!!!
            json = returned.Content.ReadAsStringAsync().Result;
        }

        try
        {
            var result = JsonConvert.DeserializeObject<T>(json);
            return result;
        }
        catch (JsonException ex)
        {
            throw new ArgumentException("Unable to deserialize the AD response.", ex);
        }
    }

here's the error output

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>An error occurred while sending the request.</ExceptionMessage>
<ExceptionType>System.Net.Http.HttpRequestException</ExceptionType>
<StackTrace>
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult() at VSTF_RD_Bot.AdHelpers.<AdPostRequest>d__7`1.MoveNext() in C:\Users\bob\Development\BotFrameworkSample-master\Bot\VSTF_RD_Bot\AdHelpers.cs:line 130 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at VSTF_RD_Bot.AdHelpers.<ExchangeCodeForAccessToken>d__2.MoveNext() in C:\Users\bob\Development\BotFrameworkSample-master\Bot\VSTF_RD_Bot\AdHelpers.cs:line 73 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at VSTF_RD_Bot.Controllers.OAuthCallbackController.<OAuthCallback>d__0.MoveNext() in C:\Users\bob\Development\BotFrameworkSample-master\Bot\VSTF_RD_Bot\Controllers\OAuthCallbackController.cs:line 34 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
</ExceptionMessage>
<ExceptionType>System.Net.WebException</ExceptionType>
<StackTrace>
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The remote certificate is invalid according to the validation procedure.
</ExceptionMessage>
<ExceptionType>
System.Security.Authentication.AuthenticationException
</ExceptionType>
<StackTrace>
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult) at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
</StackTrace>
</InnerException>
</InnerException>
</Error>

Please advise. I've even done the Powershell step but doesn't seem to be working.

Step 5: Trust the IIS Express SSL certificate

Since the web API is SSL protected, the client of the API (the web app) will refuse the SSL connection to the web API unless it trusts the API's SSL certificate. Use the following steps in Windows Powershell to trust the IIS Express SSL certificate. You only need to do this once. If you fail to do this step, calls to the TodoListService will always throw an unhandled exception where the inner exception message is:

"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

To configure your computer to trust the IIS Express SSL certificate, begin by opening a Windows Powershell command window as Administrator.

Query your personal certificate store to find the thumbprint of the certificate for CN=localhost:

PS C:\windows\system32> dir Cert:\LocalMachine\My

    Directory: Microsoft.PowerShell.Security\Certificate::LocalMachine\My

I am unable to continue. How can I resolve this issue, there doesn't seem to be any updates on the documentation, have I missed something?