问:
How to fix the org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@779de014 is closed issue
I am trying to create or update user with Hibernate 5 and it throws following exception:
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@779de014 is closed

I'm using the following technologies:

Spring 4

Hibernate 5

Maven

Eclipse

This is my UserDaoImpl.Java:

```<code>package com.fasttrack.users.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.fasttrack.users.model.User;

@Repository
@Transactional
public class UserDaoImpl extends AbstractDao implements UserDao
{
    @Autowired
    private SessionFactory sessionFactory;
    public boolean saveUser(User user)
    {
         Session session=sessionFactory.getCurrentSession();
          try
          {
             session.persist(user);
             return true;
          }

          catch (Exception e)
          {

            e.printStackTrace();
            return false;
        }

          finally
          {
              session.close();
           }

    }

    @SuppressWarnings("unchecked")
    public List<User> getUsers()
    {
         List<User> users;
         Session session=sessionFactory.getCurrentSession();
          try
          {
              users=(List<User>) session.createQuery("FROM USER");
              return users;
          }

          catch (Exception e)
          {
            e.printStackTrace();
        }

          finally {
              session.close();
           }
        return null;
    }

    public User getUser(String id)
    {
         User user;
         Session session=sessionFactory.getCurrentSession();
          try
          {
              user=(User)session.get(User.class,id);
              return user;
          }

          catch (Exception e)
          {
            e.printStackTrace();
            return null;
        }

          finally
          {
              session.close();
           }

    }

    public boolean updateUser(User user)
    {
        Session session = sessionFactory.getCurrentSession();
        try
            {
                session.saveOrUpdate(user);
                return true;
            }

        catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }

        finally
            {
                session.close();
            }
    }

    public boolean deleteUserById(String id)
    {
        User user = new User();
        user.setId(id);

        Session session = sessionFactory.getCurrentSession();
        try
            {
                session.delete(user);
                return true;
            }

        catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }

        finally
            {
                session.close();
            }
    }

}
</code>```

This is my TestUserDao.java:

```<code>import com.fasttrack.users.dao.UserDao;
import com.fasttrack.users.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/Hibernate-test.xml")

public class TestUserDao
{
    @Autowired(required=true)
    public UserDao userDao;

    @Test
    public void testSaveUser()
    {
        User user=new User();
        user.setFirstName("TestUser1");
        boolean result=userDao.saveUser(user);
    }
}
</code>```

Error Message:

Mar 01, 2017 1:14:52 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
Mar 01, 2017 1:14:52 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@6be46e8f, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3567135c, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@327471b5, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4157f54e, org.springframework.test.context.transaction.TransactionalTestExecutionListener@90f6bfd, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@47f6473]
Mar 01, 2017 1:14:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Hibernate-test.xml]
Mar 01, 2017 1:14:53 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@2a5ca609: startup date [Wed Mar 01 13:14:53 EST 2017]; root of context hierarchy
Mar 01, 2017 1:14:53 PM org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
INFO: Loading properties file from class path resource [database.properties]
Mar 01, 2017 1:14:53 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Mar 01, 2017 1:14:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.6.Final}
Mar 01, 2017 1:14:53 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 01, 2017 1:14:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 01, 2017 1:14:54 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 01, 2017 1:14:54 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Mar 01, 2017 1:14:54 PM org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource@130d63be] of Hibernate SessionFactory for HibernateTransactionManager
Generated Id: USER0
Mar 01, 2017 1:14:55 PM org.springframework.orm.hibernate5.HibernateTransactionManager doRollbackOnCommitException
SEVERE: Commit exception overridden by rollback exception
java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@6b410923 is closed
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:128)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:79)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:221)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:582)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy31.saveUser(Unknown Source)
    at TestUserDao.testSaveUser(TestUserDao.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
```

<p>Hibernate xml file:</p>

```<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
                            http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <context:property-placeholder location="classpath:database.properties" />
      <context:component-scan  base-package="com.timelee.*" />

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

     <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}"/>

    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan">
            <list>
                <value>com.timelee.timesheet.model</value>
                <value>com.timelee.users.model</value>
                <value>com.timelee.*</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"  class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

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

</beans>
```

答:
As explained in the Spring Framework User Guide, in a @Transactional block, you don't need to manually manage the Hibernate Session since the TransactionInterceptor does that for you.

So, instead of:

```<code>@SuppressWarnings("unchecked")
public List<User> getUsers() {
    List<User> users;
    Session session=sessionFactory.getCurrentSession();
    try
    {
        users=(List<User>) session.createQuery("FROM USER");
        return users;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally {
      session.close();
    }
    return null;
}
</code>```

you should do this:

```<code>@SuppressWarnings("unchecked")
public List<User> getUsers() {
    try {
        return sessionFactory.getCurrentSession()
        .createQuery("FROM USER")
        .getResultList();
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
</code>```

Aside from removing the session.close call, there were more issues that I fixed in your example:

You were not calling getResultList() on the Hibernate Query which, instead, you cast to  List<User>

Calling e..printStackTrace(); is bad. You should use a Logger framework instead. In this case, it's better to propagate the exception further instead of hiding it under the carpet.

Why would you return null when you expect a List? If there is no result, and empty List is a much better alternative. In your example, when you got an exception, you'd return null which it's indistinguishable from the case when you'd get an empty result set.

Body:
I am trying to create or update user with Hibernate 5 and it throws following exception:
    org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@779de014 is closed

I'm using the following technologies:

Spring 4

Hibernate 5

Maven

Eclipse

This is my UserDaoImpl.Java:

package com.fasttrack.users.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.fasttrack.users.model.User;

@Repository
@Transactional
public class UserDaoImpl extends AbstractDao implements UserDao
{
    @Autowired
    private SessionFactory sessionFactory;
    public boolean saveUser(User user)
    {
         Session session=sessionFactory.getCurrentSession();
          try
          {
             session.persist(user);
             return true;
          }

          catch (Exception e)
          {

            e.printStackTrace();
            return false;
        }

          finally
          {
              session.close();
           }

    }

    @SuppressWarnings("unchecked")
    public List<User> getUsers()
    {
         List<User> users;
         Session session=sessionFactory.getCurrentSession();
          try
          {
              users=(List<User>) session.createQuery("FROM USER");
              return users;
          }

          catch (Exception e)
          {
            e.printStackTrace();
        }

          finally {
              session.close();
           }
        return null;
    }

    public User getUser(String id)
    {
         User user;
         Session session=sessionFactory.getCurrentSession();
          try
          {
              user=(User)session.get(User.class,id);
              return user;
          }

          catch (Exception e)
          {
            e.printStackTrace();
            return null;
        }

          finally
          {
              session.close();
           }

    }

    public boolean updateUser(User user)
    {
        Session session = sessionFactory.getCurrentSession();
        try
            {
                session.saveOrUpdate(user);
                return true;
            }

        catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }

        finally
            {
                session.close();
            }
    }

    public boolean deleteUserById(String id)
    {
        User user = new User();
        user.setId(id);

        Session session = sessionFactory.getCurrentSession();
        try
            {
                session.delete(user);
                return true;
            }

        catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }

        finally
            {
                session.close();
            }
    }

}

This is my TestUserDao.java:

import com.fasttrack.users.dao.UserDao;
import com.fasttrack.users.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/Hibernate-test.xml")

public class TestUserDao
{
    @Autowired(required=true)
    public UserDao userDao;

    @Test
    public void testSaveUser()
    {
        User user=new User();
        user.setFirstName("TestUser1");
        boolean result=userDao.saveUser(user);
    }
}

Error Message:

Mar 01, 2017 1:14:52 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
Mar 01, 2017 1:14:52 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@6be46e8f, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3567135c, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@327471b5, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4157f54e, org.springframework.test.context.transaction.TransactionalTestExecutionListener@90f6bfd, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@47f6473]
Mar 01, 2017 1:14:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Hibernate-test.xml]
Mar 01, 2017 1:14:53 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@2a5ca609: startup date [Wed Mar 01 13:14:53 EST 2017]; root of context hierarchy
Mar 01, 2017 1:14:53 PM org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
INFO: Loading properties file from class path resource [database.properties]
Mar 01, 2017 1:14:53 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Mar 01, 2017 1:14:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.6.Final}
Mar 01, 2017 1:14:53 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 01, 2017 1:14:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 01, 2017 1:14:54 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 01, 2017 1:14:54 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Mar 01, 2017 1:14:54 PM org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource@130d63be] of Hibernate SessionFactory for HibernateTransactionManager
Generated Id: USER0
Mar 01, 2017 1:14:55 PM org.springframework.orm.hibernate5.HibernateTransactionManager doRollbackOnCommitException
SEVERE: Commit exception overridden by rollback exception
java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@6b410923 is closed
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:128)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:79)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:221)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:582)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy31.saveUser(Unknown Source)
    at TestUserDao.testSaveUser(TestUserDao.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Hibernate xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
                            http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <context:property-placeholder location="classpath:database.properties" />
      <context:component-scan  base-package="com.timelee.*" />

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

     <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}"/>

    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan">
            <list>
                <value>com.timelee.timesheet.model</value>
                <value>com.timelee.users.model</value>
                <value>com.timelee.*</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"  class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

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

</beans>

Body:
As explained in the Spring Framework User Guide, in a @Transactional block, you don't need to manually manage the Hibernate Session since the TransactionInterceptor does that for you.

So, instead of:

@SuppressWarnings("unchecked")
public List<User> getUsers() {
    List<User> users;
    Session session=sessionFactory.getCurrentSession();
    try
    {
        users=(List<User>) session.createQuery("FROM USER");
        return users;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally {
      session.close();
    }
    return null;
}

you should do this:

@SuppressWarnings("unchecked")
public List<User> getUsers() {
    try {
        return sessionFactory.getCurrentSession()
        .createQuery("FROM USER")
        .getResultList();
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Aside from removing the session.close call, there were more issues that I fixed in your example:

You were not calling getResultList() on the Hibernate Query which, instead, you cast to  List<User>

Calling e..printStackTrace(); is bad. You should use a Logger framework instead. In this case, it's better to propagate the exception further instead of hiding it under the carpet.

Why would you return null when you expect a List? If there is no result, and empty List is a much better alternative. In your example, when you got an exception, you'd return null which it's indistinguishable from the case when you'd get an empty result set.


来源: stackexchange

问:
Using C# Socket class and losing formatting in a Word file
I am using that code, which will print a document using a network printer:

```<code> Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 socket.NoDelay = true;

 IPAddress ip = IPAddress.Parse(ip);
 IPEndPoint ipEndPoint = new IPEndPoint(ip, someport);
 socket.Connect(ipEndPoint);

 socket.Send(_byteArray);
 socket.Close();
</code>```

That code works, but I am losing the formats in my Word document.

Where does the Byte-Array come from?

I am using the Syncfusion-library(relevant code snippet):

```<code>... someMethod(){

WordDocument word = new WordDocument();
//... some code
word.Save(myMemoryStream, FormatType.Docx);
_byteArray=myMemoryStream.ToArray(); //Comment on Syncfusion-library: "Writes the stream contents to a byte array, regardless of the System.IO.MemoryStream.Position"

word.Close();
}
</code>```

What can I do here ?

答:
I suspect that, you might not be installed the fonts (which are used in the Word document) in your production environment. If so, kindly install all the used fonts in your production environment to resolve the reported issue.

If you aren't modify any of Word document content, then you can try the below code.

```<code> // Open Word document using FileStream.
FileStream fileStream = new FileStream("input.docx", FileMode.Open);
// Copy file stream to MemoryStream.
MemoryStream memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream);
// Gets byte array from memory stream of file.
byte[] temp = memoryStream.ToArray();
</code>```

If you’re facing the same issue means, then the used fonts in the input document might not be installed in your production environment so, install all the used fonts to resolve the issue.

If you’re not facing the reported issue in this approach, then kindly share your codes along with input and resultant Word document from your end to validate further.

ContentLicense: CC BY-SA 3.0

Body:
I am using that code, which will print a document using a network printer:

 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 socket.NoDelay = true;

 IPAddress ip = IPAddress.Parse(ip);
 IPEndPoint ipEndPoint = new IPEndPoint(ip, someport);
 socket.Connect(ipEndPoint);

 socket.Send(_byteArray);
 socket.Close();

That code works, but I am losing the formats in my Word document.

Where does the Byte-Array come from?

I am using the Syncfusion-library(relevant code snippet):

... someMethod(){

WordDocument word = new WordDocument();
//... some code
word.Save(myMemoryStream, FormatType.Docx);
_byteArray=myMemoryStream.ToArray(); //Comment on Syncfusion-library: "Writes the stream contents to a byte array, regardless of the System.IO.MemoryStream.Position"

word.Close();
}

What can I do here ?

Body:
I suspect that, you might not be installed the fonts (which are used in the Word document) in your production environment. If so, kindly install all the used fonts in your production environment to resolve the reported issue.

If you aren't modify any of Word document content, then you can try the below code.

 // Open Word document using FileStream.
FileStream fileStream = new FileStream("input.docx", FileMode.Open);
// Copy file stream to MemoryStream.
MemoryStream memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream);
// Gets byte array from memory stream of file.
byte[] temp = memoryStream.ToArray();

If you’re facing the same issue means, then the used fonts in the input document might not be installed in your production environment so, install all the used fonts to resolve the issue.

If you’re not facing the reported issue in this approach, then kindly share your codes along with input and resultant Word document from your end to validate further.


问:
Unexpected nil for UINavigationItem under unit tests
I try to test my UIViewController when I set the title:

```<code>var sut: FloorPlanVC!

override func setUp() {

    let storyboard = UIStoryboard(name: “FloorPlan”, bundle: nil)
    sut = storyboard.instantiateInitialViewController() as! FloorPlanVC
    _ = sut.view
}

func testSetTitle() {
    sut.title = “Title” //1
    XCTAssertEqual(sut.navigationItem.title, “Title”) //2
}
</code>```

Outputs 1 on console:

```<code>po sut.title //Title
po sut.navigationItem.title //Title
</code>```

Outputs 2 on console:

```<code>po sut.title //Title
po sut.navigationItem.title //nil
</code>```

答:
The issue that you are facing right now is similar to what some people asked with this question:

Changing navigation title programmatically

Your problem is in a test environment but I think you can relate to it.
I personally see the issue of the whole set-up being in the test environment leading to you getting unexpected behavior. Check out the answers in the link I gave you, try out which one will work and also let me know.
I was going to just copy them all but no point, you can click the link.

Body:
I try to test my UIViewController when I set the title:

var sut: FloorPlanVC!

override func setUp() {

    let storyboard = UIStoryboard(name: “FloorPlan”, bundle: nil)
    sut = storyboard.instantiateInitialViewController() as! FloorPlanVC
    _ = sut.view
}

func testSetTitle() {
    sut.title = “Title” //1
    XCTAssertEqual(sut.navigationItem.title, “Title”) //2
}

Outputs 1 on console:

po sut.title //Title
po sut.navigationItem.title //Title

Outputs 2 on console:

po sut.title //Title
po sut.navigationItem.title //nil


问:
How to add file size next to the files name?
I'm trying to export all files according to their extensions and add the size next to them.

```<code>import glob2
ext = raw_input("extension:")
ext = "*." + ext
print glob2.glob(ext)
</code>```

How can I add the file size to the list?

答:
Use os.stat() to find out file metadata (size, date created, etc). It's not clear to me what you mean by next to them so this code produces a list of tuples, [(filename,filesize), ... ].

```<code>import glob2
import os
ext = raw_input("extension:")
ext = "*." + ext
filenames = glob2.glob(ext)
filenames_with_sizes = [(filename, os.stat(filename).st_size) for filename in filenames]
print filenames_with_sizes
</code>```

If you want a pretty list that is nice to print but not amenable to computation then you can do

```<code>filenames_with_sizes = ["%-40.40s %d" % (filename, os.stat(filename).st_size) for filename in filenames]
</code>```

Body:
I'm trying to export all files according to their extensions and add the size next to them.

import glob2
ext = raw_input("extension:")
ext = "*." + ext
print glob2.glob(ext)

How can I add the file size to the list?

Body:
Use os.stat() to find out file metadata (size, date created, etc). It's not clear to me what you mean by next to them so this code produces a list of tuples, [(filename,filesize), ... ].

import glob2
import os
ext = raw_input("extension:")
ext = "*." + ext
filenames = glob2.glob(ext)
filenames_with_sizes = [(filename, os.stat(filename).st_size) for filename in filenames]
print filenames_with_sizes

If you want a pretty list that is nice to print but not amenable to computation then you can do

filenames_with_sizes = ["%-40.40s %d" % (filename, os.stat(filename).st_size) for filename in filenames]


问:
Python pandas dataframe and excel: Add cell background color
Currently I save my dataframe like this

```<code>writer = ExcelWriter('test.xlsx')
test_df.to_excel(writer,'Sheet1')
writer.save()
</code>```

And resulted excel file looks like this

```<code>cus  1  abc 2 jbd 3 lkl ...
1   col  v  v  v  v  v ...
2    v   v col v  v  v ...
3    v   v  v  v col v ...
</code>```

What I need is that, when cus value == header value, that cell should have a green background. In example above, all cells with value 'col' should be set green background. How can I do this?

答:
There is a new feature in Pandas 0.20.0 - Excel output for styled DataFrames:

```<code>styled = (df.style
            .applymap(lambda v: 'background-color: %s' % 'green' if v=='col' else ''))
styled.to_excel('d:/temp/styled.xlsx', engine='openpyxl')
</code>```

Result:

Body:
Currently I save my dataframe like this

writer = ExcelWriter('test.xlsx')
test_df.to_excel(writer,'Sheet1')
writer.save()

And resulted excel file looks like this

cus  1  abc 2 jbd 3 lkl ...
1   col  v  v  v  v  v ...
2    v   v col v  v  v ...
3    v   v  v  v col v ...

What I need is that, when cus value == header value, that cell should have a green background. In example above, all cells with value 'col' should be set green background. How can I do this?

Body:
There is a new feature in Pandas 0.20.0 - Excel output for styled DataFrames:

styled = (df.style
            .applymap(lambda v: 'background-color: %s' % 'green' if v=='col' else ''))
styled.to_excel('d:/temp/styled.xlsx', engine='openpyxl')

Result:


问:
getting junk characters in firefox where as working fine in IE
I have used the below piece of code to get the output on the browser using printwriter.

```<code>String b= new String(a.getBytes("UTF-16LE"),"UTF-8");
</code>```

The output is fine with IE but in firefox i get

<�h�3�>�C�o�m�m�e�n�t�s�<�/�h�3�>� �<�t�a�b�l�e�>�<�t�r� �b�g�c�o�l�o�r�=�'�#�E�7�E�7�E�F�'�>�<�t�d�>�P�o�s�t�e�d� �O�n�:� �1�2�-�1�3�-�2�0�1�0� �1�0�:�3�8�:�2�4� �,� �B�y�:

This is the sample output of the problem facing.

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "w3.org/TR/html4/loose.dtd">;
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
      CONTENT="no-cache">
  </head>
  <body>
    <form name="form" method="post">
    <%
    String theString = null;
    PrintWriter pw = null;
    String cmntbox = "";
    ServletOutputStream outStream = null;
    try {
      Connection con = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null;
      String sql = null;
      InputStream sImage;
      con = DBConnection.getConnection();
      sql = SELECT statement
      pstmt = con.prepareStatement(sql);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        byte bytearray[] = new byte[1048576];
        String newLine = System.getProperty("line.separator");
        sImage = rs.getBinaryStream(1);
        StringWriter writer = new StringWriter();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        pw =response.getWriter();
        IOUtils.copy(sImage, writer);
        theString = writer.toString();
        pw.write(theString);
        pw.flush();
        cmntbox = Utility.getCommentPage(id,prcs_area);
        String comment = new String(cmntbox.getBytes("UTF-16LE"),"UTF-8");
        pw.write(comment);
        pw.flush();
        pw.close();
      }
</code>```

答:
I think your problem is that firefox doesn't know you are trying to display unicode. Have you tried putting in a proper doctype and content type?

The content type should be  < meta http-equiv="Content-Type" content="text/html; charset=utf-8" >

Similar issue - http://www.webdeveloper.com/forum/showpost.php?s=7981302b7ad7c59bb2b79ff03b462e45&p=680562&postcount=6

OwnerDisplayName: pras

ContentLicense: CC BY-SA 2.5

Body:
I have used the below piece of code to get the output on the browser using printwriter.

String b= new String(a.getBytes("UTF-16LE"),"UTF-8");

The output is fine with IE but in firefox i get

<�h�3�>�C�o�m�m�e�n�t�s�<�/�h�3�>� �<�t�a�b�l�e�>�<�t�r� �b�g�c�o�l�o�r�=�'�#�E�7�E�7�E�F�'�>�<�t�d�>�P�o�s�t�e�d� �O�n�:� �1�2�-�1�3�-�2�0�1�0� �1�0�:�3�8�:�2�4� �,� �B�y�:

This is the sample output of the problem facing.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "w3.org/TR/html4/loose.dtd">;

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
      CONTENT="no-cache">

    <form name="form" method="post">
    <%
    String theString = null;
    PrintWriter pw = null;
    String cmntbox = "";
    ServletOutputStream outStream = null;
    try {
      Connection con = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null;
      String sql = null;
      InputStream sImage;
      con = DBConnection.getConnection();
      sql = SELECT statement
      pstmt = con.prepareStatement(sql);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        byte bytearray[] = new byte[1048576];
        String newLine = System.getProperty("line.separator");
        sImage = rs.getBinaryStream(1);
        StringWriter writer = new StringWriter();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        pw =response.getWriter();
        IOUtils.copy(sImage, writer);
        theString = writer.toString();
        pw.write(theString);
        pw.flush();
        cmntbox = Utility.getCommentPage(id,prcs_area);
        String comment = new String(cmntbox.getBytes("UTF-16LE"),"UTF-8");
        pw.write(comment);
        pw.flush();
        pw.close();
      }

OwnerDisplayName: pulkitsinha


问:
Error when using v-model on file input
I have a file input and I need to clear it after file is uploaded. I tried setting null value to v-model, but it generated the following error

File inputs are read only. Use a v-on:change listener instead.

My code is

```<code><input id="fileupload" type="file" v-model="file" multiple v-on:change="uploadFile" ref="fileInput" />
</code>```

How can I clear the file input in vue.js after upload so that I can upload the same file multiple times continuously

答:
Solved it using the ref attribute,</p>

```<code>this.$refs.fileInput.value = null;
</code>```

Title: Error when using v-model on file input

Body:
I have a file input and I need to clear it after file is uploaded. I tried setting null value to v-model, but it generated the following error

File inputs are read only. Use a v-on:change listener instead.

My code is

<input id="fileupload" type="file" v-model="file" multiple v-on:change="uploadFile" ref="fileInput" />

How can I clear the file input in vue.js after upload so that I can upload the same file multiple times continuously

Body:
Solved it using the ref attribute,

this.$refs.fileInput.value = null;


问:
TypeError: $(...).on is not a function in jQuery
I trying to fetch data from database when corresponds to the value of the drop down selected,now i am getting an error:

```<code>TypeError: $(...).on is not a function

$("#country").on("change", function() {
</code>```

My code:

```<code><htm>
<head>
<script src="js/jquery 1.7.js"></script>

   <script>
$(function() {  //  document.ready
    $("#country").on("change", function() {
        $.ajax({
            url: "country.php",
            type: "POST",
            data: {
                country: $(this).val()
            },
            success: function(data) {
                $("#results").html(data);
            }
        });
    });
});

</script>
</head>

<body>
<div>
<form name="welcomeDiv1" id="welcomeDiv1">
<tr class="unsortable" >

<select name="country" id="country" >
   <option value="">Select Country</option>
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'priceflag';

$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
$sql=mysql_query("SELECT DISTINCT `country` FROM 9xx");
while($row=mysql_fetch_assoc($sql))
{

            print' <option id="country" name="country" value="'.$row['country'].'" >'.$row['country'].' </option>';

   }
   ?>
</select>
 </tr>
 </form>
</div>
<div id="results"></div>
</body>
</html>
</code>```

can anyone guide me how to fix this error

答:
Sometimes the error occur because of different version of jquery ,if you are using multiple jquery files in your application then you can use jQuery.noConflict()
function to get the appropriate Output.
Hope this Helps.</p>

Body:
I trying to fetch data from database when corresponds to the value of the drop down selected,now i am getting an error:

TypeError: $(...).on is not a function

$("#country").on("change", function() {

My code:

<htm>

<form name="welcomeDiv1" id="welcomeDiv1">

<select name="country" id="country" >
   <option value="">Select Country</option>
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'priceflag';

$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
$sql=mysql_query("SELECT DISTINCT `country` FROM 9xx");
while($row=mysql_fetch_assoc($sql))
{

            print' <option id="country" name="country" value="'.$row['country'].'" >'.$row['country'].' </option>';

   }
   ?>
</select>

 </form>

can anyone guide me how to fix this error


问:
Local Storage on page refresh returns empty value
Local storage returns an empty string after page refresh on woocomerce not sure why code below returns an empty value when there should be the value stored inside:

```<code>$(document).ready(function() {
  $(window).keyup(saveSettings);
  if (window.localStorage) {
    loadSettings();
  }
});

function loadSettings() {
  $('#billing_first_name').val(localStorage.bfn);
  $('#billing_last_name').val(localStorage.bln);
  $('#billing_company').val(localStorage.cn);
  $('#billing_phone').val(localStorage.phone);
  $('#billing_email').val(localStorage.ea);
}

function saveSettings() {
  localStorage.bfn = $('#billing_first_name').val();
  localStorage.bln = $('#billing_last_name').val();
  localStorage.cn = $('#billing_company').val();
  localStorage.phone = $('#billing_phone').val();
  localStorage.ea = $('#billing_email').val();

}
</code>```

Anytips are helpful thanks in advance.

答:
You're using it wrong, this is how you set and retreive items:

```<code>localStorage.setItem('name', 'value');
var value = localStorage.getItem('name');
console.log(value); //value
</code>```

So in your case, e.g.:

```<code>localStorage.setItem('bfn', $('#billing_first_name').val()); //Set value
$('#billing_first_name').val(localStorage.getItem('bfn')); //Get value
</code>```

Body:
Local storage returns an empty string after page refresh on woocomerce not sure why code below returns an empty value when there should be the value stored inside:

$(document).ready(function() {
  $(window).keyup(saveSettings);
  if (window.localStorage) {
    loadSettings();
  }
});

function loadSettings() {
  $('#billing_first_name').val(localStorage.bfn);
  $('#billing_last_name').val(localStorage.bln);
  $('#billing_company').val(localStorage.cn);
  $('#billing_phone').val(localStorage.phone);
  $('#billing_email').val(localStorage.ea);
}

function saveSettings() {
  localStorage.bfn = $('#billing_first_name').val();
  localStorage.bln = $('#billing_last_name').val();
  localStorage.cn = $('#billing_company').val();
  localStorage.phone = $('#billing_phone').val();
  localStorage.ea = $('#billing_email').val();

}

Anytips are helpful thanks in advance.

Body:
You're using it wrong, this is how you set and retreive items:

localStorage.setItem('name', 'value');
var value = localStorage.getItem('name');
console.log(value); //value

So in your case, e.g.:

localStorage.setItem('bfn', $('#billing_first_name').val()); //Set value
$('#billing_first_name').val(localStorage.getItem('bfn')); //Get value


问:
git p4 sync changelist interval
My goal is to sync the repository from p4 using an interval of changelists so that the first changelist version of the repository would be considered as an initial commit.
So I used the following command:

```<code>git p4 clone //path-to-project@cl1,cl2
</code>```

where cl1 and cl2 are numbers of mentioned changelists.

And when it finished, the files, that were created before the cl1 were not in the HEAD.

The problem, as I see it, is that before syncing changes in the given range, p4 task does not sync to cl1 version of the repo, and applies commits to the empty repository.

Is it a bug or my misunderstanding of how git p4 should work? And how should I do this correctly?

UPD: The reason I need changelist interval is that there is a problem with the p4 database and I can't checkout changelists before one point in the past. And I would like to migrate to git with all accessible history.

答:
My goal is to sync the repository from p4 using an interval of changelists so that the first changelist version of the repository would be considered as an initial commit.

When you first clone your repository with git-p4, the change you clone from is already treated as the initial commit.  That is,

```<code>git p4 clone //path-to-project@cl1
</code>```

by itself should do what you want.

It's unclear why you're trying to use a revision range (cl1,cl2) since your problem description doesn't mention cl2 at all.

Title: git p4 sync changelist interval

Body:
My goal is to sync the repository from p4 using an interval of changelists so that the first changelist version of the repository would be considered as an initial commit.
So I used the following command:

git p4 clone //path-to-project@cl1,cl2

where cl1 and cl2 are numbers of mentioned changelists.

And when it finished, the files, that were created before the cl1 were not in the HEAD.

The problem, as I see it, is that before syncing changes in the given range, p4 task does not sync to cl1 version of the repo, and applies commits to the empty repository.

Is it a bug or my misunderstanding of how git p4 should work? And how should I do this correctly?

UPD: The reason I need changelist interval is that there is a problem with the p4 database and I can't checkout changelists before one point in the past. And I would like to migrate to git with all accessible history.

Body:
My goal is to sync the repository from p4 using an interval of changelists so that the first changelist version of the repository would be considered as an initial commit.

When you first clone your repository with git-p4, the change you clone from is already treated as the initial commit.  That is,

git p4 clone //path-to-project@cl1

by itself should do what you want.

It's unclear why you're trying to use a revision range (cl1,cl2) since your problem description doesn't mention cl2 at all.


问:
Smarter way to create this responsive css grid
I'm getting crazy with a grid. For my website I have a modular grid with a fixed size, 3 x 2. In this grid I can distribute, without space and with a 1 px margin between every element, some blocks.

I can have 5 types of block:

huge, a 3 x 2 block

big-square, a 2 x 2 block

horizontal, a 2 x 1 block

vertical, a 1 x 2 block

square, 1 x 1 block.

In this image I show some variants, and un the right the "tablet" version.

I have to generate the grid using code so I don't want to create X fixed templates to fill, I want a single template that adapt itself.
Now I'm using float and some class for every variant.

For Example for first cover variant

```<code><section class="cover variant-1">
  <div class="cover-block horizontal" id="block-1">
    <img alt="image" src="https://via.placeholder.com/900x350" />
  </div>
  <div class="cover-block small" id="block-2">
    <img alt="image" src="https://via.placeholder.com/450x350" />
  </div>
  <div class="cover-block square" id="block-3">
    <img alt="image" src="https://via.placeholder.com/450x350" />
  </div>
 <div class="cover-block horizontal" id="block-4">
    <img alt="image" src="https://via.placeholder.com/900x350" />
  </div>
</section>
</code>```

And for the second cover variant

```<code><section class="cover variant-2">
  <div class="cover-block big-square" id="block-1">
    <img alt="image" src="https://via.placeholder.com/900x700" />
  </div>
  <div class="cover-block vertical" id="block-2">
    <img alt="image" src="https://via.placeholder.com/450x700" />
  </div>
</section>
</code>```

The CSS is

```<code>.cover {
  float: none;
  max-width: 1350px;
  max-height: 700px;
  margin: 0;
}
.cover .cover-block {
  float: left;
  position: relative;
  border: 0px solid #fff;
}
.cover .cover-block img {
  width: 100%;
  height: 100%;
}
.cover .cover-block.huge {
  width: 1350px;
  height: 700px;
}
.cover .cover-block.vertical {
  width: 450px;
  height: 700px;
}
.cover .cover-block.horizontal {
  width: 900px;
  height: 350px;
}
.cover .cover-block.big-square {
  width: 900px;
  height: 700px;
}
.cover .cover-block.square {
  width: 450px;
  height: 350px;
}
.cover .variant-1 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-2 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-4 {
  border-width: 1px 1px 0 0;
}
.cover .variant-1 #block-5 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-2 #block-3 {
  border-width: 1px 1px 0 0;
}
.cover .variant-2 #block-4 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-5 {
  display: none;
}
</code>```

Whit the floats I have to define an ID for every block to handle the 1 pixel space just in one direction, and I have also a lot of media queries to have this grid responsive.

Is there a smarter way to design my grid, maybe using flexbox?

Here is the Codepen

答:
The CSS Grid Layout Module would be the perfect tool to produce these layouts.

From the opening lines of the spec:

Grid Layout is a new layout model for CSS that has powerful abilities
  to control the sizing and positioning of boxes and their contents.
  Unlike Flexible Box Layout, which is single-axis–oriented, Grid Layout
  is optimized for 2-dimensional layouts: those in which alignment of
  content is desired in both dimensions.

Basically, the relevant code boils down to this:

```<code>.container {
  display: grid; /* 1 */
  grid-template-columns: repeat(3, 80px); /* 2 */
  grid-template-rows: repeat(2, 80px); /* 2 */
  margin: 20px;
}
</code>```

1) Make the container element a grid container

2) Set the grid with 3 columns and 2 rows with a given length (here 80px).

Then for each 'block' variation - just set how much each block spans with the grid-column and grid-row properties.

For example:

horizontal, a 2 x 1 block

becomes:

```<code>.horizontal {
  grid-column: span 2;
  grid-row: span 1;
}
</code>```

Note that by default a grid item will span one column and one row - so the 'square' block doesn't need to be defined.

.container {
  display: grid;
  grid-template-columns: repeat(3, 80px);
  grid-template-rows: repeat(2, 80px);
  margin: 20px;
}
@media (max-width: 1200px) {
  .container.supports-tablet {
    grid-template-columns: repeat(2, 80px);
    grid-template-rows: repeat(3, 80px);
  }
  .container.supports-tablet:after {
    content: "tablet view!!!";
    color: red;
  }
}
.container div {
  border: 1px solid blue;
  margin-left: -1px;
  margin-bottom: -1px;
}
.huge {
  grid-column: span 3;
  grid-row: span 2;

}
.big-square {
  grid-column: span 2;
  grid-row: span 2;
}

.horizontal {
  grid-column: span 2;
  grid-row: span 1;
}
.vertical {
  grid-column: span 1;
  grid-row: span 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container supports-tablet">
  <div class="horizontal">horizontal</div>
  <div>square</div>
  <div>square</div>
  <div class="horizontal">horizontal</div>
</div>

<div class="container">
  <div class="big-square">big-square</div>
  <div class="vertical">vertical</div>
</div>
<div class="container">
  <div class="vertical">vertical</div>
  <div class="horizontal">horizontal</div>
  <div class="horizontal">horizontal</div>
</div>
<div class="container">
  <div class="horizontal">horizontal</div>
  <div class="vertical">vertical</div>
  <div>square</div>
  <div>square</div>
</div>

<div class="container">
  <div class="huge">huge</div>
</div>

<div class="container">
  <div class="vertical">vertical</div>
  <div>square</div>
  <div class="vertical">vertical</div>
  <div>square</div>
</div></code>```

Codepen demo

NB:

To make the above layouts responsive (for tablet etc) you would have to decide how the overall grid will change to support that layout.

Notice that in the one example image with tablet view - the grid switches from being 3 X 2 to 2 X 3 - this can easily be done with a media query which redefines the grid with 2 columns and 3 rows.

Browser Support - Caniuse

Currently supported by Chrome (Blink), Safari and Firefox, with partial support from IE and Edge

Body:
I'm getting crazy with a grid. For my website I have a modular grid with a fixed size, 3 x 2. In this grid I can distribute, without space and with a 1 px margin between every element, some blocks.

I can have 5 types of block:

huge, a 3 x 2 block

big-square, a 2 x 2 block

horizontal, a 2 x 1 block

vertical, a 1 x 2 block

square, 1 x 1 block.

In this image I show some variants, and un the right the "tablet" version.

I have to generate the grid using code so I don't want to create X fixed templates to fill, I want a single template that adapt itself.
Now I'm using float and some class for every variant.

For Example for first cover variant

And for the second cover variant

The CSS is

.cover {
  float: none;
  max-width: 1350px;
  max-height: 700px;
  margin: 0;
}
.cover .cover-block {
  float: left;
  position: relative;
  border: 0px solid #fff;
}
.cover .cover-block img {
  width: 100%;
  height: 100%;
}
.cover .cover-block.huge {
  width: 1350px;
  height: 700px;
}
.cover .cover-block.vertical {
  width: 450px;
  height: 700px;
}
.cover .cover-block.horizontal {
  width: 900px;
  height: 350px;
}
.cover .cover-block.big-square {
  width: 900px;
  height: 700px;
}
.cover .cover-block.square {
  width: 450px;
  height: 350px;
}
.cover .variant-1 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-2 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-4 {
  border-width: 1px 1px 0 0;
}
.cover .variant-1 #block-5 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-2 #block-3 {
  border-width: 1px 1px 0 0;
}
.cover .variant-2 #block-4 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-5 {
  display: none;
}

Whit the floats I have to define an ID for every block to handle the 1 pixel space just in one direction, and I have also a lot of media queries to have this grid responsive.

Is there a smarter way to design my grid, maybe using flexbox?

Here is the Codepen

Body:
The CSS Grid Layout Module would be the perfect tool to produce these layouts.

From the opening lines of the spec:

Grid Layout is a new layout model for CSS that has powerful abilities
  to control the sizing and positioning of boxes and their contents.
  Unlike Flexible Box Layout, which is single-axis–oriented, Grid Layout
  is optimized for 2-dimensional layouts: those in which alignment of
  content is desired in both dimensions.

Basically, the relevant code boils down to this:

.container {
  display: grid; /* 1 */
  grid-template-columns: repeat(3, 80px); /* 2 */
  grid-template-rows: repeat(2, 80px); /* 2 */
  margin: 20px;
}

1) Make the container element a grid container

2) Set the grid with 3 columns and 2 rows with a given length (here 80px).

Then for each 'block' variation - just set how much each block spans with the grid-column and grid-row properties.

For example:

horizontal, a 2 x 1 block

becomes:

.horizontal {
  grid-column: span 2;
  grid-row: span 1;
}

Note that by default a grid item will span one column and one row - so the 'square' block doesn't need to be defined.

.container {
  display: grid;
  grid-template-columns: repeat(3, 80px);
  grid-template-rows: repeat(2, 80px);
  margin: 20px;
}
@media (max-width: 1200px) {
  .container.supports-tablet {
    grid-template-columns: repeat(2, 80px);
    grid-template-rows: repeat(3, 80px);
  }
  .container.supports-tablet:after {
    content: "tablet view!!!";
    color: red;
  }
}
.container div {
  border: 1px solid blue;
  margin-left: -1px;
  margin-bottom: -1px;
}
.huge {
  grid-column: span 3;
  grid-row: span 2;

}
.big-square {
  grid-column: span 2;
  grid-row: span 2;
}

.horizontal {
  grid-column: span 2;
  grid-row: span 1;
}
.vertical {
  grid-column: span 1;
  grid-row: span 2;
}

<div class="container supports-tablet">
  <div class="horizontal">horizontal</div>
  <div>square</div>
  <div>square</div>
  <div class="horizontal">horizontal</div>
</div>

<div class="container">
  <div class="big-square">big-square</div>
  <div class="vertical">vertical</div>
</div>
<div class="container">
  <div class="vertical">vertical</div>
  <div class="horizontal">horizontal</div>
  <div class="horizontal">horizontal</div>
</div>
<div class="container">
  <div class="horizontal">horizontal</div>
  <div class="vertical">vertical</div>
  <div>square</div>
  <div>square</div>
</div>

<div class="container">
  <div class="huge">huge</div>
</div>

<div class="container">
  <div class="vertical">vertical</div>
  <div>square</div>
  <div class="vertical">vertical</div>
  <div>square</div>
</div>

Codepen demo

NB:

To make the above layouts responsive (for tablet etc) you would have to decide how the overall grid will change to support that layout.

Notice that in the one example image with tablet view - the grid switches from being 3 X 2 to 2 X 3 - this can easily be done with a media query which redefines the grid with 2 columns and 3 rows.

Browser Support - Caniuse

Currently supported by Chrome (Blink), Safari and Firefox, with partial support from IE and Edge


答:
```<code>String comment = new String(cmntbox.getBytes("UTF-16LE"),"UTF-8");
</code>```

is almost certainly wrong. The String that you get from Utility.getCommentPage should contain the characters you want. Converting those characters into bytes using one encoding, and then converting the bytes back into characters with another encoding, would result in what you're seeing.

In particular, every other byte in UTF-16 encoding for typical HTML is zero. And zero is a perfectly valid byte that encodes into a single NUL character in UTF-8. IE might be thinking, "Clearly this is wrong, so I will try to be helpful and do what I think you meant"; while Firefox is just showing what you said you wanted.

What happens if you skip the conversion and just do

```<code>pw.write(cmntbox);
</code>```

directly? You already did the response.setContentType with the charset= before you did the response.getWriter. When you then write a String, it should do the character encoding for you.

Title: getting junk characters in firefox where as working fine in IE

Body:
String comment = new String(cmntbox.getBytes("UTF-16LE"),"UTF-8");

is almost certainly wrong. The String that you get from Utility.getCommentPage should contain the characters you want. Converting those characters into bytes using one encoding, and then converting the bytes back into characters with another encoding, would result in what you're seeing.

In particular, every other byte in UTF-16 encoding for typical HTML is zero. And zero is a perfectly valid byte that encodes into a single NUL character in UTF-8. IE might be thinking, "Clearly this is wrong, so I will try to be helpful and do what I think you meant"; while Firefox is just showing what you said you wanted.

What happens if you skip the conversion and just do

pw.write(cmntbox);

directly? You already did the response.setContentType with the charset= before you did the response.getWriter. When you then write a String, it should do the character encoding for you.

OwnerDisplayName: Ken


问:
get sql query result in xml format?
Hello i am trying the getting result in xml format in the sql server but i don't get propare xml format many data it's repeat in xml format. i have write this query in the sql server but not a getting propare data. any one know where is my mistake then please let me know how can do that.

Here i have write this query :

```<code>select * from (

    SELECT SSCF.SubSubCategoryId AS InterestId,c.FeedId,c.Description,u.UserId,u.Email,u.UserName,u.ProfileImage,u.Name,
           ISNULL(SSCL.SubSubCategory,SSC.SubSubCategory) AS Interest,
           1 AS [Type]
    FROM SubSubCategoryFollowers SSCF
    LEFT JOIN SubSubCategories SSC ON SSCF.SubSubCategoryId = SSC.SubSubCategoryId
    INNER JOIN Feed c on c.FeedId = SSC.FeedId
    inner join Users u on u.UserId = SSCF.UserId
    WHERE u.Email is not null

    UNION ALL

    SELECT  SCF.SubCategoryId AS InterestId,c.FeedId,c.Description,u.UserId,u.Email,u.UserName,u.ProfileImage,u.Name,
           ISNULL(SCL.SubCategory,SC.SubCategory) AS Interest,
           2 AS [Type]
    FROM SubCategoryFollowers SCF
    LEFT JOIN SubCategories SC ON SCF.SubCategoryId = SC.SubCategoryId
    INNER JOIN Feed c on c.FeedId = SC.FeedId
    inner join Users u on u.UserId = SCF.UserId
    WHERE u.Email is not null

 )as res

group by res.UserId,res.InterestId,res.FeedId,res.Description,res.Email,res.Interest,res.Type,res.UserName,res.ProfileImage,res.Name
order by res.FeedId
OFFSET 1   ROWS
FETCH NEXT  50000   ROWS ONLY
FOR XML PATH('User'), ROOT ('Users')
</code>```

this is my current op =>

```<code> <Users>
  <User>
    <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>15</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Event</Interest>
    <Type>2</Type>
</User>
<User>
     <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>16</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Party</Interest>
    <Type>2</Type>
</User>
<User>
    <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>21</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Club</Interest>
    <Type>2</Type>
</User>
<User>
<UserId>1661</UserId>
<Email>abc.com</Email>
<UserName>abc</UserName>
<ProfileImage>20160717035320959.jpeg</ProfileImage>
<InterestId>15</InterestId>
<FeedId>4690</FeedId>
<Description>Test1</Description>
<Interest>Cricket</Interest>
<Type>1</Type>
</code>```

My expected o/p =>

```<code><Users>
 <User>
 <UserId>1660</UserId>
<Email>xyz.com</Email>
<UserName>xyz</UserName>
 <ProfileImage>20160717035320958.jpeg</ProfileImage>

<InterestId>15</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Event</Interest>
<Type>2</Type>

<InterestId>16</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Party</Interest>
<Type>2</Type>

<InterestId>21</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Club</Interest>
<Type>2</Type>
</User>
<User>
<UserId>1661</UserId>
<Email>abc.com</Email>
<UserName>abc</UserName>
<ProfileImage>20160717035320959.jpeg</ProfileImage>

<InterestId>15</InterestId>
<FeedId>4690</FeedId>
<Description>Test1</Description>
<Interest>Cricket</Interest>
<Type>1</Type>
</code>```

i want like this data in xml format any one know please let me know.

答:
The idea is to give the xml the format you want by labelling the path tags.
Unfortunately I don't have time to work through your sqls but this is an example of grouping by labelling:</p>

```<code>select UserId as "User" , InterestId as "User/InterestId" from
(select '1' as 'UserId', 'I1' as 'InterestId'
union all
select '1' as 'UserId', 'I2' as 'InterestId') x
for xml path(''), root('Users')
</code>```

Title: get sql query result in xml format?

Body:
Hello i am trying the getting result in xml format in the sql server but i don't get propare xml format many data it's repeat in xml format. i have write this query in the sql server but not a getting propare data. any one know where is my mistake then please let me know how can do that.

Here i have write this query :

select * from (

    SELECT SSCF.SubSubCategoryId AS InterestId,c.FeedId,c.Description,u.UserId,u.Email,u.UserName,u.ProfileImage,u.Name,
           ISNULL(SSCL.SubSubCategory,SSC.SubSubCategory) AS Interest,
           1 AS [Type]
    FROM SubSubCategoryFollowers SSCF
    LEFT JOIN SubSubCategories SSC ON SSCF.SubSubCategoryId = SSC.SubSubCategoryId
    INNER JOIN Feed c on c.FeedId = SSC.FeedId
    inner join Users u on u.UserId = SSCF.UserId
    WHERE u.Email is not null

    UNION ALL

    SELECT  SCF.SubCategoryId AS InterestId,c.FeedId,c.Description,u.UserId,u.Email,u.UserName,u.ProfileImage,u.Name,
           ISNULL(SCL.SubCategory,SC.SubCategory) AS Interest,
           2 AS [Type]
    FROM SubCategoryFollowers SCF
    LEFT JOIN SubCategories SC ON SCF.SubCategoryId = SC.SubCategoryId
    INNER JOIN Feed c on c.FeedId = SC.FeedId
    inner join Users u on u.UserId = SCF.UserId
    WHERE u.Email is not null

 )as res

group by res.UserId,res.InterestId,res.FeedId,res.Description,res.Email,res.Interest,res.Type,res.UserName,res.ProfileImage,res.Name
order by res.FeedId
OFFSET 1   ROWS
FETCH NEXT  50000   ROWS ONLY
FOR XML PATH('User'), ROOT ('Users')

this is my current op =>

 <Users>
  <User>
    <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>15</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Event</Interest>
    <Type>2</Type>
</User>
<User>
     <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>16</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Party</Interest>
    <Type>2</Type>
</User>
<User>
    <UserId>1660</UserId>
    <Email>xyz.com</Email>
    <UserName>xyz</UserName>
    <ProfileImage>20160717035320958.jpeg</ProfileImage>
    <InterestId>21</InterestId>
    <FeedId>4689</FeedId>
    <Description>Test</Description>
    <Interest>Club</Interest>
    <Type>2</Type>
</User>
<User>
<UserId>1661</UserId>
<Email>abc.com</Email>
<UserName>abc</UserName>
<ProfileImage>20160717035320959.jpeg</ProfileImage>
<InterestId>15</InterestId>
<FeedId>4690</FeedId>
<Description>Test1</Description>
<Interest>Cricket</Interest>
<Type>1</Type>

My expected o/p =>

<Users>
 <User>
 <UserId>1660</UserId>
<Email>xyz.com</Email>
<UserName>xyz</UserName>
 <ProfileImage>20160717035320958.jpeg</ProfileImage>

<InterestId>15</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Event</Interest>
<Type>2</Type>

<InterestId>16</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Party</Interest>
<Type>2</Type>

<InterestId>21</InterestId>
<FeedId>4689</FeedId>
<Description>Test</Description>
<Interest>Club</Interest>
<Type>2</Type>
</User>
<User>
<UserId>1661</UserId>
<Email>abc.com</Email>
<UserName>abc</UserName>
<ProfileImage>20160717035320959.jpeg</ProfileImage>

<InterestId>15</InterestId>
<FeedId>4690</FeedId>
<Description>Test1</Description>
<Interest>Cricket</Interest>
<Type>1</Type>

i want like this data in xml format any one know please let me know.

Body:
The idea is to give the xml the format you want by labelling the path tags.
Unfortunately I don't have time to work through your sqls but this is an example of grouping by labelling:

select UserId as "User" , InterestId as "User/InterestId" from
(select '1' as 'UserId', 'I1' as 'InterestId'
union all
select '1' as 'UserId', 'I2' as 'InterestId') x
for xml path(''), root('Users')


问:
Why isn't Unity allowing me to apply certain changes to a prefab?
I have a prefab called square in the asset tray, I drag it into the scene to create an instance of the square prefab (in the hierarchy it is highlighted blue and has the select, revert and apply buttons in the properties). If I move/resize the instance and then press apply, the changes are applied to the prefab.

However, the square prefab has a script with a public game object. I drag the game object from the hierarchy into the slot in the instance's properties tab and is shows that the script is now referencing the actual gameobject. However, when I press apply this change isn't applied to the prefab (the prefab's script still isn't referencing any actual gameobject). All other changes to the prefab are applied.

I have tried dragging the instance into the asset tray to create a new prefab with the changes, but, as soon as I do, the script no longer references the game object.

I shouldn't have to create an entirely new prefab every time I add a public variable to a script so why can't I apply this change?

答:
Ok you can't really drag an instance to a prefab. As a rule of thumb keep instances with instances and prefabs with prefabs.
 I would instead find the instance from the prefab when this one is instantiated, with a method like findobjectoftype, or gameobject.find. Let me know if you want me to expand the answer</p>


问:
Connecting LDAP server from java application
I am building an application based on GXT (J2EE). Now the problem is that I have to connect the application to a LDAP server. Can you tell me how to connect a LDAP server from our java application and what Library or API I will have to use for that? </p>

答:
Connection to a LDAP server is made using JNDI (Java Naming and
Directory Interface) APIs in Java.

The JNDI’s interfaces, classes and exceptions are available in the
following packages come with JDK:

javax.naming.*

javax.naming.directory.*

That means we don’t have to use any external libraries for working
with LDAP servers, in most cases.

That specifies URL of a LDAP server consists of hostname on which
LDAP Server is running port number. A well known port number of the
Lightweight Directory Access Protocol is 389 which is default.

Also need to specify some environment properties for the connection
and authentication in a Hashtable object.

Here is the sample code:

```<code>import javax.naming.*;
import javax.naming.ldap.*;
import javax.naming.directory.*;

public class Ldap
{
    public static void main(String[]args)
    {
        Hashtable<String, String> environment = new Hashtable<String, String>();

        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.PROVIDER_URL, "ldap://<hostname>:389");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.SECURITY_PRINCIPAL, "<Login DN>");
        environment.put(Context.SECURITY_CREDENTIALS, "<password>");

        try
        {
            DirContext context = new InitialDirContext(environment);
            System.out.println("Connected..");
            System.out.println(context.getEnvironment());
            context.close();
        }
        catch (AuthenticationNotSupportedException exception)
        {
            System.out.println("The authentication is not supported by the server");
        }

        catch (AuthenticationException exception)
        {
            System.out.println("Incorrect password or username");
        }

        catch (NamingException exception)
        {
            System.out.println("Error when trying to create the context");
        }
    }
}
</code>```

Body:
Connection to a LDAP server is made using JNDI (Java Naming and
Directory Interface) APIs in Java.

The JNDI’s interfaces, classes and exceptions are available in the
following packages come with JDK:

javax.naming.*

javax.naming.directory.*

That means we don’t have to use any external libraries for working
with LDAP servers, in most cases.

That specifies URL of a LDAP server consists of hostname on which
LDAP Server is running port number. A well known port number of the
Lightweight Directory Access Protocol is 389 which is default.

Also need to specify some environment properties for the connection
and authentication in a Hashtable object.

Here is the sample code:

import javax.naming.*;
import javax.naming.ldap.*;
import javax.naming.directory.*;

public class Ldap
{
    public static void main(String[]args)
    {
        Hashtable<String, String> environment = new Hashtable<String, String>();

        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.PROVIDER_URL, "ldap://<hostname>:389");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.SECURITY_PRINCIPAL, "<Login DN>");
        environment.put(Context.SECURITY_CREDENTIALS, "<password>");

        try
        {
            DirContext context = new InitialDirContext(environment);
            System.out.println("Connected..");
            System.out.println(context.getEnvironment());
            context.close();
        }
        catch (AuthenticationNotSupportedException exception)
        {
            System.out.println("The authentication is not supported by the server");
        }

        catch (AuthenticationException exception)
        {
            System.out.println("Incorrect password or username");
        }

        catch (NamingException exception)
        {
            System.out.println("Error when trying to create the context");
        }
    }
}


问:
Check values in all previous rows in SQL table
I have the following SQL table:

```<code>declare @t table(START_DATE datetime,INDEX_ID int, GROSS_SALES_PRICE decimal(10,2));
insert into @t values
 ('20150619',10000410,38)
,('20170311',10000410,26.49)
,('20170312',10000410,26.49)
,('20170317',10000410,38)
,('20170318',10000410,38)
,('20170321',10000410,38);
</code>```

I would like to check if there are any temporary changes in GROSS_SALES_PRICE

For example, in this table I have a price 38, then I have two rows with 26.49 and then 38 again. There can be any number of lower price rows so I think I have to check multiple previous rows?

I would like to make third column with value of 1 if this situation happened:

答:
```<code>WITH maxPrice AS
(
    SELECT INDEX_ID, MAX(GROSS_SALES_PRICE) MaxPrice
    FROM   @t
    GROUP BY INDEX_ID
)
SELECT t.INDEX_ID, t.GROSS_SALES_PRICE,
       CASE WHEN GROSS_SALES_PRICE < maxPrice.MaxPrice THEN 1 ELSE 0 END AS [CHANGED]
FROM   @t t
INNER JOIN maxPrice
ON    maxPrice.INDEX_ID = t.INDEX_ID;
GO
</code>```

```
INDEX_ID | GROSS_SALES_PRICE | CHANGED
-------: | :---------------- | ------:
10000410 | 38.00             |       0
10000410 | 26.49             |       1
10000410 | 26.49             |       1
10000410 | 38.00             |       0
10000410 | 38.00             |       0
10000410 | 38.00             |       0
```

dbfiddle here

Body:
I have the following SQL table:

declare @t table(START_DATE datetime,INDEX_ID int, GROSS_SALES_PRICE decimal(10,2));
insert into @t values
 ('20150619',10000410,38)
,('20170311',10000410,26.49)
,('20170312',10000410,26.49)
,('20170317',10000410,38)
,('20170318',10000410,38)
,('20170321',10000410,38);

I would like to check if there are any temporary changes in GROSS_SALES_PRICE

For example, in this table I have a price 38, then I have two rows with 26.49 and then 38 again. There can be any number of lower price rows so I think I have to check multiple previous rows?

I would like to make third column with value of 1 if this situation happened:

Body:
WITH maxPrice AS
(
    SELECT INDEX_ID, MAX(GROSS_SALES_PRICE) MaxPrice
    FROM   @t
    GROUP BY INDEX_ID
)
SELECT t.INDEX_ID, t.GROSS_SALES_PRICE,
       CASE WHEN GROSS_SALES_PRICE < maxPrice.MaxPrice THEN 1 ELSE 0 END AS [CHANGED]
FROM   @t t
INNER JOIN maxPrice
ON    maxPrice.INDEX_ID = t.INDEX_ID;
GO

INDEX_ID | GROSS_SALES_PRICE | CHANGED
-------: | :---------------- | ------:
10000410 | 38.00             |       0
10000410 | 26.49             |       1
10000410 | 26.49             |       1
10000410 | 38.00             |       0
10000410 | 38.00             |       0
10000410 | 38.00             |       0

dbfiddle here


问:
Ajax, Json, selectors that are depending on each other
Hi
I have 3 selectors, where Products depends on type and number of products depends on Products.

Type --> Products --> Number Of Products

Im loading everything from a mySQL server and extract the data with $.getJSON. So when you load the types it automaticly fills the products with names and so on.

The problem I have now is that I want the number of products to change when the product change, but if you look at the example further down, you will see that's not the case.

Initially when you load the page the third selector wont even show any options, and when you change the "type" it wont update either.

It's only when you change the productname that this will happend.

I want this to automaticly change, how do I do this?

Thanks in advance!

This is the code I'm using,

```<code><form>
    Type:
    <select name="name" id="lensType">
        <option selected>Endagslins</option>
        <option>Dygnet-runt-lins</option>
        <option>2-veckorslins</option>
        <option>Manadslins</option>
    </select>
    Product:
    <select name="productName" id="products">
    </select>
    Number of products:
    <select name="numberOfLenses" id="numberOfLenses">
    </select>

</form>

<script type="text/javascript">
    function getProducts() {

        $.getJSON('getProducts.php', {lensType:$('#lensType').val()}, function(data) {

            var select = $('#products');
            var options = select.attr('options');
            $('option', select).remove();

            $.each(data, function(index, array) {
                options[options.length] = new Option(array['productName']);
            });

        });

    }

    $(document).ready(function() {

        getProducts();
        $('#lensType').change(function() {
            getProducts();
        });

    });

    function getNumberOfLenses() {

        $.getJSON('getNumberOfLenses.php', {productName:$('#products').val()}, function(data) {

            var select = $('#numberOfLenses');
            var options = select.attr('options');
            $('option', select).remove();

            $.each(data, function(index, array) {
                options[options.length] = new Option(array['numberOfLenses']);
            });

        });

    }

    $(document).ready(function() {

        getNumberOfLenses();
        $('#products').change(function() {
            getNumberOfLenses();
        });

    });

</script>
</code>```

答:
I figured it out myself :)

I used this code

```<code>function getProducts() {

    $.getJSON('getProducts.php', {lensType:$('#lensType').val()}, function(data) {

        var select = $('#products');
        var options = select.attr('options');
        $('option', select).remove();

        $.each(data, function(index, array) {
            options[options.length] = new Option(array['productName']);
        });

        getNumberOfLenses();

    });

}

function getNumberOfLenses() {

    $.getJSON('getNumberOfLenses.php', {productName:$('#products').val()}, function(data) {

        var select = $('#numberOfLenses');
        var options = select.attr('options');
        $('option', select).remove();

        $.each(data, function(index, array) {
            options[options.length] = new Option(array['numberOfLenses']);
        });

    });

}

$(document).ready(function() {
    getProducts();
    $('#lensType').change(function() {
        getProducts();
    });

    $('#products').change(function() {
        getNumberOfLenses();
    });

});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi
I have 3 selectors, where Products depends on type and number of products depends on Products.

Type --> Products --> Number Of Products

Im loading everything from a mySQL server and extract the data with $.getJSON. So when you load the types it automaticly fills the products with names and so on.

The problem I have now is that I want the number of products to change when the product change, but if you look at the example further down, you will see that's not the case.

Initially when you load the page the third selector wont even show any options, and when you change the "type" it wont update either.

It's only when you change the productname that this will happend.

I want this to automaticly change, how do I do this?

Thanks in advance!

This is the code I'm using,

<form>
    Type:
    <select name="name" id="lensType">
        <option selected>Endagslins</option>
        <option>Dygnet-runt-lins</option>
        <option>2-veckorslins</option>
        <option>Manadslins</option>
    </select>
    Product:
    <select name="productName" id="products">
    </select>
    Number of products:
    <select name="numberOfLenses" id="numberOfLenses">
    </select>

</form>

Body:
I figured it out myself :)

I used this code

function getProducts() {

    $.getJSON('getProducts.php', {lensType:$('#lensType').val()}, function(data) {

        var select = $('#products');
        var options = select.attr('options');
        $('option', select).remove();

        $.each(data, function(index, array) {
            options[options.length] = new Option(array['productName']);
        });

        getNumberOfLenses();

    });

}

function getNumberOfLenses() {

    $.getJSON('getNumberOfLenses.php', {productName:$('#products').val()}, function(data) {

        var select = $('#numberOfLenses');
        var options = select.attr('options');
        $('option', select).remove();

        $.each(data, function(index, array) {
            options[options.length] = new Option(array['numberOfLenses']);
        });

    });

}

$(document).ready(function() {
    getProducts();
    $('#lensType').change(function() {
        getProducts();
    });

    $('#products').change(function() {
        getNumberOfLenses();
    });

});


问:
Casting hex string to signed int results in different values in different platforms
I am dealing with an edge case in a program that I want to be multi-platform. Here is the extract of the problem:

```<code>#include <stdio.h>
#include <string.h>

void print_bits(size_t const size, void const * const ptr){
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = (b[i] >> j) & 1;
            printf("%u", byte);
        }
    }
    puts("");
}

int main() {

char* ascii = "0x80000000";
int myint = strtol(ascii, NULL, 16);

printf("%s to signed int is %d and bits are:\t", ascii, myint);
print_bits(sizeof myint, &myint);

return 0;
}
</code>```

So when I compile with GCC on Linux I get this output:

```<code>0x80000000 to signed int is -2147483648 and bits are:   10000000000000000000000000000000
</code>```

On a Windows, using MSVC and MinGW I get:

```<code>0x80000000 to signed int is 2147483647 and bits are:    01111111111111111111111111111111
</code>```

I think the GCC outputs the correct expected values. My question is, where does this difference come from and how to make sure that on all compilers I get the correct result?

UPDATE

The reason behind this code is, I have to check if the MSB (bit #31) of the HEX value is 0 or 1. Then, I have to get the unsigned integer value of the next 7 bits (#30 to #24) result (in case of 0x80000000these 7 bits should result in 0:

```<code>    int msb_is_set = myint & 1;
    uint8_t next_7_bits;

next_7_bits = myint >> 24; //fine on GCC, outputs 0 for the next 7 bits
#ifdef WIN32 //If I do not do this, next_7_bit will be 127 on Windows instead of 0
    if(msb_is_set )
        next_7_bits = myint >> 1;
#endif
</code>```

P.S. This is on the same machine (i5 64bit)

答:
You're dealing with different data models here.

Windows 64 uses LLP64, which means only long long and pointers are 64bit. As strtol converts to long, it converts to a 32bit value, and 0x80000000 in a 32bit signed integer is negative.

Linux 64 uses LP64, so long, long long and pointers are 64bit. I guess you see what's happening here now ;)

Thanks to the comments, I realize my initial answer was wrong. The different outcome indeed has to do with the differing models on those platforms. But: in case of the LP64 model, you have a conversion to a signed type that cannot hold the value, which is implementation defined. int is 32bit on both platforms and a 32bit int just cannot hold 0x80000000. So the correct answer is: you shouldn't expect any result from your code on Linux64. On Win64, as long is only 32bit, strtol() correctly returns LONG_MAX for 0x80000000, which happens to be just one smaller than your input.

Body:
I am dealing with an edge case in a program that I want to be multi-platform. Here is the extract of the problem:

#include <stdio.h>
#include <string.h>

void print_bits(size_t const size, void const * const ptr){
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = (b[i] >> j) & 1;
            printf("%u", byte);
        }
    }
    puts("");
}

int main() {

char* ascii = "0x80000000";
int myint = strtol(ascii, NULL, 16);

printf("%s to signed int is %d and bits are:\t", ascii, myint);
print_bits(sizeof myint, &myint);

return 0;
}

So when I compile with GCC on Linux I get this output:

0x80000000 to signed int is -2147483648 and bits are:   10000000000000000000000000000000

On a Windows, using MSVC and MinGW I get:

0x80000000 to signed int is 2147483647 and bits are:    01111111111111111111111111111111

I think the GCC outputs the correct expected values. My question is, where does this difference come from and how to make sure that on all compilers I get the correct result?

UPDATE

The reason behind this code is, I have to check if the MSB (bit #31) of the HEX value is 0 or 1. Then, I have to get the unsigned integer value of the next 7 bits (#30 to #24) result (in case of 0x80000000these 7 bits should result in 0:

    int msb_is_set = myint & 1;
    uint8_t next_7_bits;

next_7_bits = myint >> 24; //fine on GCC, outputs 0 for the next 7 bits
#ifdef WIN32 //If I do not do this, next_7_bit will be 127 on Windows instead of 0
    if(msb_is_set )
        next_7_bits = myint >> 1;
#endif

P.S. This is on the same machine (i5 64bit)


答:
```<code>int myint = strtol(ascii, NULL, 16);
</code>```

strtol is 'string to long', not string to int.

Also, you probably want 0x800000000 to be an unsigned long.

You may find that on (that version of ) Linux that int is 64bit, whereas on (that version of) Windo3ws, int is 32bits.

Title: Casting hex string to signed int results in different values in different platforms

Body:
int myint = strtol(ascii, NULL, 16);

strtol is 'string to long', not string to int.

Also, you probably want 0x800000000 to be an unsigned long.

You may find that on (that version of ) Linux that int is 64bit, whereas on (that version of) Windo3ws, int is 32bits.


问:
Tomcat : PreResources tag not loading jars
I am using tomcat 9, And trying to load all the project related jar's from below PreResources tag.

```<code><Resources className="org.apache.catalina.webresources.StandardRoot" cachingAllowed="true" cacheMaxSize="100000" allowLinking="true">
<PreResources className="org.apache.catalina.webresources.DirResourceSet"
    base="D:\SomePath\apache-tomcat-9.0.0.M17-windows-x64-2\apache-tomcat-9.0.0.M17"
    internalPath="/External-lib"
    webAppMount="/WEB-INF/classes" />
</code>```

The External-lib folder lies in tomcat directory as per the path mentioned in 'base'. but when application gets deployed, I get below error.

```<code> java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
</code>```

This gets called from web.xml,

    org.springframework.web.context.ContextLoaderListener

in tomcat lib, we have just tomcat libraries, where as rest all jar's are in External-lib folder. Since we have similar webApp and jar's are too many, we are trying to externalize them and not to load in webapp/web-inf/lib folder.

Please suggest, am I missing anything when loading the jar's from meta-inf/context.xml using PreResources element.

There is very less examples and documentation for this PreResources element.
Any direction or help would be appreciated.

答:
This should have been the content of context.xml. It worked and fixed my issues.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resources>
        <PreResources className="org.apache.catalina.webresources.DirResourceSet"
            base="SomePath\External-lib\"
            webAppMount="/WEB-INF/lib" />
    </Resources>
</Context>
</code>```

"Base" is the path to the external resources and "webAppMount" is where you want to mount these resources.

Body:
I am using tomcat 9, And trying to load all the project related jar's from below PreResources tag.

<Resources className="org.apache.catalina.webresources.StandardRoot" cachingAllowed="true" cacheMaxSize="100000" allowLinking="true">
<PreResources className="org.apache.catalina.webresources.DirResourceSet"
    base="D:\SomePath\apache-tomcat-9.0.0.M17-windows-x64-2\apache-tomcat-9.0.0.M17"
    internalPath="/External-lib"
    webAppMount="/WEB-INF/classes" />

The External-lib folder lies in tomcat directory as per the path mentioned in 'base'. but when application gets deployed, I get below error.

 java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

This gets called from web.xml,

    org.springframework.web.context.ContextLoaderListener

in tomcat lib, we have just tomcat libraries, where as rest all jar's are in External-lib folder. Since we have similar webApp and jar's are too many, we are trying to externalize them and not to load in webapp/web-inf/lib folder.

Please suggest, am I missing anything when loading the jar's from meta-inf/context.xml using PreResources element.

There is very less examples and documentation for this PreResources element.
Any direction or help would be appreciated.

Body:
This should have been the content of context.xml. It worked and fixed my issues.

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resources>
        <PreResources className="org.apache.catalina.webresources.DirResourceSet"
            base="SomePath\External-lib\"
            webAppMount="/WEB-INF/lib" />
    </Resources>
</Context>

"Base" is the path to the external resources and "webAppMount" is where you want to mount these resources.