问:
Concurrent request fail - "Session is closed!"
I dono what is wrong with my below code. If I hit my request from browser, it works fine. But when I give concurrent requests, it fails saying Session is closed!. I am hitting the below two urls simultaneously or concurrently (async calls).

```<code>http://localhost:8080/getEmployee
http://localhost:8080/getDepartment
</code>```

Controller.java

```<code>@RequestMapping(value = "/getEmployees", method = RequestMethod.POST)
 public @ResponseBody List<Employee> getEmployee() {

        List<Employee> empList = null;
        empList = services.getEmployee();
        return empList;
    }

 @RequestMapping(value = "/getDepartments", method = RequestMethod.GET)
 public @ResponseBody List<Department> getDepartment() {

        List<Department> deptList = null;
        deptList = services.getDepartment();
        return deptList;
    }
</code>```

Two Model class

```<code>Table 1 (Employee)
@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {

    private static final long serialVersionUID = 2650114334774359089L;

    @Id
    @Column(name = "id", unique = true, nullable = false, length = 100)
    private String id;

    @Column(name = "name", unique = true, nullable = false, length = 50)
    private String name;

// getter setter
</code>```

//Second model class

```<code>Table 2 (Department)
@Entity
@Table(name = "department")
public class Department implements java.io.Serializable {

    private static final long serialVersionUID = 2650114334774359089L;

    @Id
    @Column(name = "id", unique = true, nullable = false, length = 100)
    private String id;

    @Column(name = "dept_name", unique = true, nullable = false, length = 50)
    private String dept_name;

    // getter setter
</code>```

DAOImpl

```<code>@Autowired
    SessionFactory sessionFactory;

    Session session = null;
    Transaction tx = null;

    static final Logger LOGGER = Logger.getLogger(DataDaoImpl.class);
    public List<Employee> getEmployee() throws Exception {
        List<Employee> result = null;
        session = sessionFactory.openSession();
        String hql = "from Employee";
        Query lQuery = session.createQuery(hql);
        result = lQuery.list();
        tx = session.getTransaction();
        session.beginTransaction();
        tx.commit();
        return result;
    }

    public List<Department> getDepartment() throws Exception {
        List<Department> result = null;
        session = sessionFactory.openSession();
        String hql = "from Department";
        Query lQuery = session.createQuery(hql);
        result = lQuery.list();
        tx = session.getTransaction();
        session.beginTransaction();
        tx.commit();
        return result;
    }
</code>```

ServiceImpl

```<code>@Override
    public List<Employee> getEmployee() throws Exception {
        return dataDao.getEmployee();
    }

    @Override
    public List<Department> getDepartment() throws Exception {
        return dataDao.getDepartment();
    }
</code>```

spring-config.xml

```<code><bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
        <property name="username" value="root" />
        <property name="password" value="password"/>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.srdh.model.Employee</value>
                <value>com.srdh.model.Department</value>

            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

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

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

    <bean id="dataDao" class="com.test.dao.DaoImpl"></bean>
    <bean id="dataServices" class="com.test.service.ServicesImpl"></bean>
</code>```

Can anyone help me what I my doing wrong in my code. I have only one DAO to access both the department and employee table. I have to fetch records from the individual tables and show in output. In concurrent request it is failing.

Error Stack trace

```<code>org.hibernate.HibernateException: createQuery is not valid without active transaction
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
    at com.sun.proxy.$Proxy139.createQuery(Unknown Source)
    at com.srdh.dao.DataDaoImpl.getDepartment(DataDaoImpl.java:49)
    at com.srdh.service.DataServicesImpl.getDepartment(DataServicesImpl.java:26)
    at com.srdh.controller.MainController.getDepartment(MainController.java:44)
    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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
org.hibernate.SessionException: Session is closed!
    at org.hibernate.internal.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:133)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1433)
    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.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
    at com.sun.proxy.$Proxy139.beginTransaction(Unknown Source)
    at com.srdh.dao.DataDaoImpl.Employee(DataDaoImpl.java:126)
    at com.srdh.service.DataServicesImpl.Employee(DataServicesImpl.java:71)
    at com.srdh.controller.MainController.Employee(MainController.java:73)
    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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
org.hibernate.TransactionException: nested transactions not supported
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:154)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1435)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
</code>```

答:
Your DAOImpl looks suspect.

Spring beans are normally singletons. There's only one instance of the Spring bean in your running program. You didn't post the complete code, but it looks like your class DAOImpl has member variables for the session and transaction.

If multiple threads are using the same singleton DAOImpl object concurrently, changing the member variables, then they will interfere with each other. A thread handling one request will see the session and transaction from another thread handling another request.

Do not put state (member variables) in singleton Spring beans. session and tx should not be, and do not need to be, member variables in class DAOImpl. Make them local variables in the methods getEmployee and getDepartment instead.

Even better would be to use Spring Data JPA instead of implementing your own DAO object. This makes it easier and you won't have to deal with lower level details yourself directly, such as getting a session and transaction.

Body:
I dono what is wrong with my below code. If I hit my request from browser, it works fine. But when I give concurrent requests, it fails saying Session is closed!. I am hitting the below two urls simultaneously or concurrently (async calls).

http://localhost:8080/getEmployee
http://localhost:8080/getDepartment

Controller.java

@RequestMapping(value = "/getEmployees", method = RequestMethod.POST)
 public @ResponseBody List<Employee> getEmployee() {

        List<Employee> empList = null;
        empList = services.getEmployee();
        return empList;
    }

 @RequestMapping(value = "/getDepartments", method = RequestMethod.GET)
 public @ResponseBody List<Department> getDepartment() {

        List<Department> deptList = null;
        deptList = services.getDepartment();
        return deptList;
    }

Two Model class

Table 1 (Employee)
@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {

    private static final long serialVersionUID = 2650114334774359089L;

    @Id
    @Column(name = "id", unique = true, nullable = false, length = 100)
    private String id;

    @Column(name = "name", unique = true, nullable = false, length = 50)
    private String name;

// getter setter

//Second model class

Table 2 (Department)
@Entity
@Table(name = "department")
public class Department implements java.io.Serializable {

    private static final long serialVersionUID = 2650114334774359089L;

    @Id
    @Column(name = "id", unique = true, nullable = false, length = 100)
    private String id;

    @Column(name = "dept_name", unique = true, nullable = false, length = 50)
    private String dept_name;

    // getter setter

DAOImpl

@Autowired
    SessionFactory sessionFactory;

    Session session = null;
    Transaction tx = null;

    static final Logger LOGGER = Logger.getLogger(DataDaoImpl.class);
    public List<Employee> getEmployee() throws Exception {
        List<Employee> result = null;
        session = sessionFactory.openSession();
        String hql = "from Employee";
        Query lQuery = session.createQuery(hql);
        result = lQuery.list();
        tx = session.getTransaction();
        session.beginTransaction();
        tx.commit();
        return result;
    }

    public List<Department> getDepartment() throws Exception {
        List<Department> result = null;
        session = sessionFactory.openSession();
        String hql = "from Department";
        Query lQuery = session.createQuery(hql);
        result = lQuery.list();
        tx = session.getTransaction();
        session.beginTransaction();
        tx.commit();
        return result;
    }

ServiceImpl

@Override
    public List<Employee> getEmployee() throws Exception {
        return dataDao.getEmployee();
    }

    @Override
    public List<Department> getDepartment() throws Exception {
        return dataDao.getDepartment();
    }

spring-config.xml

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
        <property name="username" value="root" />
        <property name="password" value="password"/>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.srdh.model.Employee</value>
                <value>com.srdh.model.Department</value>

            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

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

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

    <bean id="dataDao" class="com.test.dao.DaoImpl"></bean>
    <bean id="dataServices" class="com.test.service.ServicesImpl"></bean>

Can anyone help me what I my doing wrong in my code. I have only one DAO to access both the department and employee table. I have to fetch records from the individual tables and show in output. In concurrent request it is failing.

Error Stack trace

org.hibernate.HibernateException: createQuery is not valid without active transaction
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
    at com.sun.proxy.$Proxy139.createQuery(Unknown Source)
    at com.srdh.dao.DataDaoImpl.getDepartment(DataDaoImpl.java:49)
    at com.srdh.service.DataServicesImpl.getDepartment(DataServicesImpl.java:26)
    at com.srdh.controller.MainController.getDepartment(MainController.java:44)
    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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
org.hibernate.SessionException: Session is closed!
    at org.hibernate.internal.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:133)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1433)
    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.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
    at com.sun.proxy.$Proxy139.beginTransaction(Unknown Source)
    at com.srdh.dao.DataDaoImpl.Employee(DataDaoImpl.java:126)
    at com.srdh.service.DataServicesImpl.Employee(DataServicesImpl.java:71)
    at com.srdh.controller.MainController.Employee(MainController.java:73)
    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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
org.hibernate.TransactionException: nested transactions not supported
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:154)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1435)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)


来源: stackexchange

问:
Run AVD Emulator without Android Studio
is there a way to run the emulator without starting the Android Studio first. Perhaps from the command line. I know that this feature was available in older versions and has vanished since then. But perhaps someone found out how to do it anyways?</p>

答:
In the ANDROID_HOME folder you will have tools folder

In Mac/Linux

emulator -avd <avdName>

In Windows

emulator.exe -avd <avdName>

If you are using API 24 You can get the names of the emulator from the list

android list avds

If you are using API 25 then you will get it with avdmanager in tools\bin

avdmanager list avds

ContentLicense: CC BY-SA 3.0

Title: Run AVD Emulator without Android Studio


问:
git repository in window server 2008 cannot clone to local with ssh
I am now trying to do git repository in server with ssh and I cannot clone  it to my local.
My IP is 103.244.89.55  and use ssh with bitvise ssh server.

i used git to init in "C:xampp/htdoc/maya" folder

And i cannot clone to my local from server,please

答:
You need to configure your username and email in the commandline git so it can  access github, for example at the shell prompt:

```<code>$ git config --global user.name "Richard E. Silverman"
$ git config --global user.email res@oreilly.com
</code>```

After those are set you should be all set.

comment response

In that case if you want to install it the same configuration as above you need to run Powershell or bash on unbuntu on windows, or whatever shell that is, as Administrator to give you access rights to the install directory.

Body:
You need to configure your username and email in the commandline git so it can  access github, for example at the shell prompt:

$ git config --global user.name "Richard E. Silverman"
$ git config --global user.email res@oreilly.com

After those are set you should be all set.

comment response

In that case if you want to install it the same configuration as above you need to run Powershell or bash on unbuntu on windows, or whatever shell that is, as Administrator to give you access rights to the install directory.


问:
Log4Net not generating log file
I have ASP.Net WebAPI project & using Log4Net API.

```<code> protected void LogException(Exception ex)
    {
        var msgParams = new Dictionary<string, string>
                {
                    { "Message", ex.Message },
                    { "StackTrace", ex.StackTrace },
                };

        _logger.Info(JsonConvert.SerializeObject(msgParams));
    }
</code>```

XML Configuration

```<code><?xml version="1.0" encoding="utf-8" ?> <log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

    <file value="App.log" />

    <appendToFile value="true" />

    <maximumFileSize value="50KB" />
    <maxSizeRollBackups value="2" />

    <encoding value="utf-8" />

    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %thread %logger - %message%newline" />
    </layout>

</appender>

<root>
    <level value="DEBUG" />
    <appender-ref ref="RollingFile" />
</root>
</code>```

But when any exception occurs & above LogException() gets hit, neither I am getting any exception nor I see any App.Log file in my directory.

What I am missing here?
Any help/suggestion highly appreciated.

答:
The problem is probably in the location:

```<code><file value="App.log" />
</code>```

This will log relative to your webserver directory, not the location of you code/executable. Set the full path to test this, the log location has to be writable for the user that runs your application.

Title: Log4Net not generating log file

Body:
I have ASP.Net WebAPI project & using Log4Net API.

 protected void LogException(Exception ex)
    {
        var msgParams = new Dictionary<string, string>
                {
                    { "Message", ex.Message },
                    { "StackTrace", ex.StackTrace },
                };

        _logger.Info(JsonConvert.SerializeObject(msgParams));
    }

XML Configuration

<?xml version="1.0" encoding="utf-8" ?> <log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

    <file value="App.log" />

    <appendToFile value="true" />

    <maximumFileSize value="50KB" />
    <maxSizeRollBackups value="2" />

    <encoding value="utf-8" />

    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %thread %logger - %message%newline" />
    </layout>

</appender>

<root>
    <level value="DEBUG" />
    <appender-ref ref="RollingFile" />
</root>

But when any exception occurs & above LogException() gets hit, neither I am getting any exception nor I see any App.Log file in my directory.

What I am missing here?
Any help/suggestion highly appreciated.

Body:
The problem is probably in the location:

<file value="App.log" />

This will log relative to your webserver directory, not the location of you code/executable. Set the full path to test this, the log location has to be writable for the user that runs your application.


答:
The Error stack trace says createQuery is not valid without active transaction from which we can see that there's no active transaction in other words there's no open transaction, and this is because you create and execute the query before opening the transaction.

So your big mistake is that you are querying the database before opening any transaction.

You need to move:

```<code>tx = session.getTransaction();
session.beginTransaction();
</code>```

Before the line where you create and execute your query.

And you are using a new Session in each request, you should use sessionFactory.getCurrentSession() instead of sessionFactory.openSession().

So you need to update your code like this:

```<code> public List<Employee> getEmployee() throws Exception {
    List<Employee> result = null;
    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.getTransaction();
    session.beginTransaction();
    String hql = "from Employee";
    Query lQuery = session.createQuery(hql);
    result = lQuery.list();
    tx.commit();
    return result;
}

public List<Department> getDepartment() throws Exception {
    List<Department> result = null;
    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.getTransaction();
    session.beginTransaction();
    String hql = "from Department";
    Query lQuery = session.createQuery(hql);
    result = lQuery.list();
    tx.commit();
    return result;
}
</code>```

This should fix your problem.

Note:

As reported and pointed out by @SergeBallesta you should not use session and tx as instance variable in your DAO, you better use them as local varibales in your methods like in my code above.

Title: Concurrent request fail - "Session is closed!"

Body:
The Error stack trace says createQuery is not valid without active transaction from which we can see that there's no active transaction in other words there's no open transaction, and this is because you create and execute the query before opening the transaction.

So your big mistake is that you are querying the database before opening any transaction.

You need to move:

tx = session.getTransaction();
session.beginTransaction();

Before the line where you create and execute your query.

And you are using a new Session in each request, you should use sessionFactory.getCurrentSession() instead of sessionFactory.openSession().

So you need to update your code like this:

 public List<Employee> getEmployee() throws Exception {
    List<Employee> result = null;
    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.getTransaction();
    session.beginTransaction();
    String hql = "from Employee";
    Query lQuery = session.createQuery(hql);
    result = lQuery.list();
    tx.commit();
    return result;
}

public List<Department> getDepartment() throws Exception {
    List<Department> result = null;
    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.getTransaction();
    session.beginTransaction();
    String hql = "from Department";
    Query lQuery = session.createQuery(hql);
    result = lQuery.list();
    tx.commit();
    return result;
}

This should fix your problem.

Note:

As reported and pointed out by @SergeBallesta you should not use session and tx as instance variable in your DAO, you better use them as local varibales in your methods like in my code above.


问:
How to combine multiple images to make
I have linear layout with horizontal orientation and with multiple ImageView. How do I make single Bitmap with these images?

Like this:

If there are more than 6 images, then remaining images go in next lines.
This one is working for horizontal:

```<code>       Bitmap[] parts = new Bitmap[4];
        Bitmap result = Bitmap.createBitmap(parts[0].getWidth() * 2, parts[0].getHeight() * 2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        for (int i = 0; i < parts.length; i++) {
            canvas.drawBitmap(parts[i], parts[i].getWidth() * (i % 2), parts[i].getHeight() * (i / 2), paint);
        }
</code>```

答:
You should take LienarLayout  in below method:

```<code>public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
</code>```

pass your LienarLayout object in above method to take Bitmap from View.

Title: How to combine multiple images to make

Body:
I have linear layout with horizontal orientation and with multiple ImageView. How do I make single Bitmap with these images?

Like this:

If there are more than 6 images, then remaining images go in next lines.
This one is working for horizontal:

       Bitmap[] parts = new Bitmap[4];
        Bitmap result = Bitmap.createBitmap(parts[0].getWidth() * 2, parts[0].getHeight() * 2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        for (int i = 0; i < parts.length; i++) {
            canvas.drawBitmap(parts[i], parts[i].getWidth() * (i % 2), parts[i].getHeight() * (i / 2), paint);
        }

Body:
You should take LienarLayout  in below method:

public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}

pass your LienarLayout object in above method to take Bitmap from View.


问:
Data Manipulation in R for Apriori
I have a part of the data-set as shown below in the form of csv,the number of rows and columns are more than what is shown.I want to implement apriori on this data-set,Say I have this:-

```<code>    Maths Science C++ Java DC
[1]    75   44      55  56  88
[2]    56   88      54  78  44
</code>```

the original dataset has total columns(representing subjects)=30 and serial number(representing students)=24,

DATASET:link

I want to covert this dataset in the form shown below:-

```<code>[1] {Maths,DC}
[2] {Science,Java}
</code>```

i.e A list of list(I think this is what it is called) containing the colnames.A list for a student shows in which subject he/she scored more than or equal to 75 marks,rest of the subjects are dropped(The only condition of the problem)

eq:- first student scored 75+ marks in Dc and Maths and so his list includes only dc and maths.

I am sorry for posting this,but I searched a lot on stack,and found a few of the working suggestions ,but couldn't reach the final goal.
My goal is to get a form like this:-

```<code>[9834] {semi-finished bread,
        bottled water,
        soda,
        bottled beer}
[9835] {chicken,
        tropical fruit,
        other vegetables,
        vinegar,
        shopping bags}
</code>```

As given in :-

```<code>library(arules)
inspect(Groceries)
</code>```

OR I WILL APPRECIATE IF ANYONE CAN SUGGEST A WAY TO REPRESENT THE DATA IN OTHER FORM WHICH APRIORI CAN UNDERSTAND,BUT IT SHOULD FOLLOW THE NECESSARY CONDITIONS AS STATED.

*(sorry for the long post,I hope this conversion of my dataset in this format may help me study the pattern in student-subject dataset,thnx a ton for all the help)

答:
```<code>library(plyr)
library(arules)
df <- read.table(text =
"   75   44      55  56  88
    56   88      54  78  44")
names(df) <- c("Maths", "Science", "C++", "Java", "DC")
transactions <- as(alply(df, 1, function(x) names(x)[x >= 75]), "transactions")
inspect(transactions)

#     items          transactionID
# [1] {DC,Maths}     1
# [2] {Java,Science} 2
</code>```

Edit: It works with your example dataset, too:

```<code>library(plyr)
library(arules)
df <- read.csv(file = url("https://drive.google.com/uc?export=download&id=0B3kdblyHw4qLR0dpT24xWUZGcGs"))
transactions <- as(alply(df, 1, function(x) names(x)[x >= 75]), "transactions")
inspect(transactions)

#      items                              transactionID
# [1]  {CD,CG,CN,DA,Data.Struc}           1
# [2]  {CD,CG,CO,ML,OS}                   2
# [3]  {CN,Data.Struc,DC,DM,DMS}          3
# [4]  {CHE,DD,DM,EC,EE}                  4
# [5]  {CHE,CN,MATHS,PHY}                 5
# [6]  {Data.Science,DM,DMS,ML,OS}        6
# [7]  {CD,DA,Data.Struc,EC,MATHS}        7
# [8]  {CG,CHE,CN,CO,OS}                  8
# [9]  {CN,CO,Data.Science,DC,DMS}        9
# [10] {DC,DD,EC,EE,PHY}                  10
# [11] {CHE,DD,DMS,MATHS,PHY}             11
# [12] {CN,Data.Science,DM,MATHS,ML}      12
# [13] {CD,CG,DA,Data.Science,Data.Struc} 13
# [14] {CG,CO,EE,MATHS,OS}                14
# [15] {CN,CO,DC,DMS,PHY}                 15
# [16] {CN,CO,DD,EC,EE}                   16
# [17] {CHE,DA,EE,MATHS,PHY}              17
# [18] {Data.Science,DD,DM,ML,PHY}        18
# [19] {CD,CO,DA,Data.Struc,DC}           19
# [20] {CG,CO,DD,DM,OS}                   20
# [21] {CG,CN,DA,DC,DMS}                  21
# [22] {DD,EC,EE,ML,OS}                   22
# [23] {CHE,CN,Data.Struc,MATHS,PHY}      23
# [24] {CG,Data.Science,DM,EE,ML}         24
</code>```

Title: Data Manipulation in R for Apriori

Body:
I have a part of the data-set as shown below in the form of csv,the number of rows and columns are more than what is shown.I want to implement apriori on this data-set,Say I have this:-

    Maths Science C++ Java DC
[1]    75   44      55  56  88
[2]    56   88      54  78  44

the original dataset has total columns(representing subjects)=30 and serial number(representing students)=24,

DATASET:link

I want to covert this dataset in the form shown below:-

[1] {Maths,DC}
[2] {Science,Java}

i.e A list of list(I think this is what it is called) containing the colnames.A list for a student shows in which subject he/she scored more than or equal to 75 marks,rest of the subjects are dropped(The only condition of the problem)

eq:- first student scored 75+ marks in Dc and Maths and so his list includes only dc and maths.

I am sorry for posting this,but I searched a lot on stack,and found a few of the working suggestions ,but couldn't reach the final goal.
My goal is to get a form like this:-

[9834] {semi-finished bread,
        bottled water,
        soda,
        bottled beer}
[9835] {chicken,
        tropical fruit,
        other vegetables,
        vinegar,
        shopping bags}

As given in :-

library(arules)
inspect(Groceries)

OR I WILL APPRECIATE IF ANYONE CAN SUGGEST A WAY TO REPRESENT THE DATA IN OTHER FORM WHICH APRIORI CAN UNDERSTAND,BUT IT SHOULD FOLLOW THE NECESSARY CONDITIONS AS STATED.

*(sorry for the long post,I hope this conversion of my dataset in this format may help me study the pattern in student-subject dataset,thnx a ton for all the help)

Body:
library(plyr)
library(arules)
df <- read.table(text =
"   75   44      55  56  88
    56   88      54  78  44")
names(df) <- c("Maths", "Science", "C++", "Java", "DC")
transactions <- as(alply(df, 1, function(x) names(x)[x >= 75]), "transactions")
inspect(transactions)

#     items          transactionID
# [1] {DC,Maths}     1
# [2] {Java,Science} 2

Edit: It works with your example dataset, too:

library(plyr)
library(arules)
df <- read.csv(file = url("https://drive.google.com/uc?export=download&id=0B3kdblyHw4qLR0dpT24xWUZGcGs"))
transactions <- as(alply(df, 1, function(x) names(x)[x >= 75]), "transactions")
inspect(transactions)

#      items                              transactionID
# [1]  {CD,CG,CN,DA,Data.Struc}           1
# [2]  {CD,CG,CO,ML,OS}                   2
# [3]  {CN,Data.Struc,DC,DM,DMS}          3
# [4]  {CHE,DD,DM,EC,EE}                  4
# [5]  {CHE,CN,MATHS,PHY}                 5
# [6]  {Data.Science,DM,DMS,ML,OS}        6
# [7]  {CD,DA,Data.Struc,EC,MATHS}        7
# [8]  {CG,CHE,CN,CO,OS}                  8
# [9]  {CN,CO,Data.Science,DC,DMS}        9
# [10] {DC,DD,EC,EE,PHY}                  10
# [11] {CHE,DD,DMS,MATHS,PHY}             11
# [12] {CN,Data.Science,DM,MATHS,ML}      12
# [13] {CD,CG,DA,Data.Science,Data.Struc} 13
# [14] {CG,CO,EE,MATHS,OS}                14
# [15] {CN,CO,DC,DMS,PHY}                 15
# [16] {CN,CO,DD,EC,EE}                   16
# [17] {CHE,DA,EE,MATHS,PHY}              17
# [18] {Data.Science,DD,DM,ML,PHY}        18
# [19] {CD,CO,DA,Data.Struc,DC}           19
# [20] {CG,CO,DD,DM,OS}                   20
# [21] {CG,CN,DA,DC,DMS}                  21
# [22] {DD,EC,EE,ML,OS}                   22
# [23] {CHE,CN,Data.Struc,MATHS,PHY}      23
# [24] {CG,Data.Science,DM,EE,ML}         24


问:
R: ecdf with bars instead of line
Is it possible to plot the
ecdf function in R with bars instead of a line ore steps?

Ore is there another way to plot the cumulative histogram in ggplot with cumulative densities on the y-axis instead of frequencys?

答:
ggplot has a stat_ecdf() function out of the box, but it doesn't support geom = "bar". We can use stat_bin() in combination with the special variable ..density.. to arrive at a bar plot version of ecdf:

```<code>library(ggplot2)
ggplot(df, aes(x)) + stat_ecdf(col = "red") +
                     stat_bin(aes(y = cumsum(..density..)/
                                      sum(..density..)),
                              alpha = 0.8)
</code>```

Title: R: ecdf with bars instead of line

Body:
ggplot has a stat_ecdf() function out of the box, but it doesn't support geom = "bar". We can use stat_bin() in combination with the special variable ..density.. to arrive at a bar plot version of ecdf:

library(ggplot2)
ggplot(df, aes(x)) + stat_ecdf(col = "red") +
                     stat_bin(aes(y = cumsum(..density..)/
                                      sum(..density..)),
                              alpha = 0.8)


问:
Enforce type safety in C++ without using extra classes
I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

```<code>// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);
</code>```

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.

答:
What about creating a class that inherits (public) from std::vector to have a strong typecheck. The advantage is that you only need to rewrite constructors..

You can also regroup your parameters in a std::unordered_map>, to implement argument as a dict (like  in python, or javascript)

Body:
I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.


问:
function pointer equal to another pointer within the function, why need to add *
please take look at Node *newNode(), i dont understand why i must add * for p=x
i made an Node named x(with data & next), and created a new memory space *p by using malloc,
then let p = x, but by i must add * for p=x?</p>

```<code>#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    Node *next;
};

Node *newNode(int data, Node *next){
    Node x = {data, next};
    Node *p = (Node *)malloc(sizeof(Node));
    *p = x; //i dont understand why an * need to be added here
    return p;
}

showNode(const struct Node *p){
    printf("%d\n", p->data);
}

int main(){
    Node *pHead = NULL;
    for(int i=4; i>=0; i--) {
        pHead = newNode(i,pHead);
    }
    printf("%d\n", pHead->next->next->next->data);

    Node* p = pHead;
    while(p != NULL){
        showNode(p);
        p = p-> next;
    }

    p = pHead;
    while(p != NULL){
        Node *pTemp = p;
        p = p->next;
        free(pTemp);
    }
}
</code>```

答:
Because it is a pointer. That's just the syntax in c/c++.

If you are using a pointer without the *, you are saying that you want the memory address. When you use the * you instead want the content on that address.

Body:
please take look at Node *newNode(), i dont understand why i must add * for p=x
i made an Node named x(with data & next), and created a new memory space *p by using malloc,
then let p = x, but by i must add * for p=x?

#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    Node *next;
};

Node *newNode(int data, Node *next){
    Node x = {data, next};
    Node *p = (Node *)malloc(sizeof(Node));
    *p = x; //i dont understand why an * need to be added here
    return p;
}

showNode(const struct Node *p){
    printf("%d\n", p->data);
}

int main(){
    Node *pHead = NULL;
    for(int i=4; i>=0; i--) {
        pHead = newNode(i,pHead);
    }
    printf("%d\n", pHead->next->next->next->data);

    Node* p = pHead;
    while(p != NULL){
        showNode(p);
        p = p-> next;
    }

    p = pHead;
    while(p != NULL){
        Node *pTemp = p;
        p = p->next;
        free(pTemp);
    }
}


问:
Send email with profile picture PHP mail function
I would like to show a profile picture in my users inbox when they receive an email sent from my website with PHP.

In this image the first email is from my website and the second one is what I want.

And here is my PHP mail function:

```<code>            $emailTo=$_POST['emialNewPass'];
            $emailSubject="Recovery";
            $emailLoctuz="noreply@loctuz.com";
            $message="msg";

            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                            // En-têtes additionnels
            $headers .= 'To: '.$emailTo."\r\n";
            $headers .= 'From: Loctuz Security <'. $emailLoctuz . '>' ."\r\n";

            if(@mail($emailTo,$emailSubject,$message, $headers))
            {
                ?><script>window.location = "?sent";</script><?php
            }
</code>```

答:
I believe what you try to accomplish has nothing to do with PHP for mail sending, but rather code for displaying your website favicon. Here is a good read about them:
https://css-tricks.com/favicon-quiz/</p>

ContentLicense: CC BY-SA 4.0

Body:
I would like to show a profile picture in my users inbox when they receive an email sent from my website with PHP.

In this image the first email is from my website and the second one is what I want.

And here is my PHP mail function:

            $emailTo=$_POST['emialNewPass'];
            $emailSubject="Recovery";
            $emailLoctuz="noreply@loctuz.com";
            $message="msg";

            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                            // En-têtes additionnels
            $headers .= 'To: '.$emailTo."\r\n";
            $headers .= 'From: Loctuz Security <'. $emailLoctuz . '>' ."\r\n";

            if(@mail($emailTo,$emailSubject,$message, $headers))
            {
                ?><?php
            }


问:
My viewDidAppear not called in view controller
It turns out that what I want to do is that when I come from a 3d shortcut, forcing the UITabBarController to choose an index, if I do this in the tab bar viewDidAppear() the problem is that the viewDidAppear() of my main UIViewController Embedded is not called, if I click again on the tab bar item then already if it is called. With the rest of the drivers does not happen, I understand why it is not the one that is first in the list of items in the UITabBarController.

Tab bar controller: (Here it comes)

```<code>override func viewDidAppear(_ animated: Bool) {
    if goTasks {
        self.selectedIndex = 0
    } else if goTodo {
        self.selectedIndex = 2
    } else if goProjects {
        self.selectedIndex = 3
    } else if goSearch {
        self.selectedIndex = 0
    }

}
</code>```

My first UIViewController:
(Not called this method)

```<code>override func viewDidAppear(_ animated: Bool) {
    print("Entry")
}
</code>```

Is the problem override the methods? Any solution?

答:
i think you have to call function from super: </p>

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated) // here what i ment

    if goTasks {
        self.selectedIndex = 0
    } else if goTodo {
        self.selectedIndex = 2
    } else if goProjects {
        self.selectedIndex = 3
    } else if goSearch {
        self.selectedIndex = 0
    }

}
</code>```

Body:
It turns out that what I want to do is that when I come from a 3d shortcut, forcing the UITabBarController to choose an index, if I do this in the tab bar viewDidAppear() the problem is that the viewDidAppear() of my main UIViewController Embedded is not called, if I click again on the tab bar item then already if it is called. With the rest of the drivers does not happen, I understand why it is not the one that is first in the list of items in the UITabBarController.

Tab bar controller: (Here it comes)

override func viewDidAppear(_ animated: Bool) {
    if goTasks {
        self.selectedIndex = 0
    } else if goTodo {
        self.selectedIndex = 2
    } else if goProjects {
        self.selectedIndex = 3
    } else if goSearch {
        self.selectedIndex = 0
    }

}

My first UIViewController:
(Not called this method)

override func viewDidAppear(_ animated: Bool) {
    print("Entry")
}

Is the problem override the methods? Any solution?

Body:
i think you have to call function from super:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated) // here what i ment

    if goTasks {
        self.selectedIndex = 0
    } else if goTodo {
        self.selectedIndex = 2
    } else if goProjects {
        self.selectedIndex = 3
    } else if goSearch {
        self.selectedIndex = 0
    }

}


问:
How do I scroll to an item using the mouse wheel on angular
I've got some trouble.
I've got home page with 4 div elements with a different id.
Example:

```<code>   <div id='one' class='sectionscroll'></div>
    <div id='two' class='sectionscroll'></div>
    <div id='three' class='sectionscroll'></div>
    <div id='four' class='sectionscroll'></div>
</code>```

All these div pick the height from the screen.
When page loads I made an automatic scroll to the div with id two

.

And from this position, I want to scroll to another position.
But I couldn't understand how to make this.

This is my factory wich made slow scroll to position by using ng-click.

```<code>(function () {
    'use strict';

    angular
        .module('app.scroll.home.page', [])
        .factory('$scrollHomePage', $scrollHomePage);

    $scrollHomePage.inject = [];

    function $scrollHomePage() {
        return {
            scrollTo: function(eId) {

                var startY = currentYPosition();
                var stopY = elmYPosition(eId);
                var distance = stopY > startY ? stopY - startY : startY - stopY;
                if (distance < 100) {
                    scrollTo(0, stopY);
                    return;
                }
                var speed = Math.round(distance / 65);
                if (speed >= 250) speed = 250;
                var step = Math.round(distance / 25);
                var leapY = stopY > startY ? startY + step : startY - step;
                var timer = 0;
                if (stopY > startY) {
                    for (var i = startY; i < stopY; i += step) {
                        setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed);
                        leapY += step;
                        if (leapY > stopY) leapY = stopY;
                        timer++;
                    }
                    return;
                }
                for (var i = startY; i > stopY; i -= step) {
                    setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed);
                    leapY -= step;
                    if (leapY < stopY) leapY = stopY;
                    timer++;
                }

                function currentYPosition() {
                    if ('scrollRestoration' in history) {
                        history.scrollRestoration = 'manual';
                    }
                    if (document.documentElement && document.documentElement.scrollTop)
                        return document.documentElement.scrollTop;
                    if (document.body.scrollTop) return document.body.scrollTop;
                    return 0;
                }

                function elmYPosition(eID) {
                    var elm = document.getElementById(eID);
                    var y = elm.offsetTop;
                    var node = elm;
                    while (node.offsetParent && node.offsetParent != document.body) {
                        node = node.offsetParent;
                        y += node.offsetTop;
                    }
                    return y;
                }
            }

        };
    }
})();
</code>```

and in controller I used automatical scroll by

```<code>$(window).load(function () {
            $("div.sectionscroll").height($('body').height());
            $location.hash('');
            $scrollHomePage.scrollTo('two');
        });
</code>```

答:
Hey @Volodymyr If I got your question correctly, you need to scroll to a particular hash (id of div)
You can use $anchorScroll and $location services of angular.

Below code will scroll to a div with id output and you can even add an offset to the scroll position if you want to take the user to a bit lower position than the exact div

```<code>$anchorScroll.yOffset = 30; // to add extra top margin
$location.hash('output');
$anchorScroll();
</code>```

You can then call this function on ng-click of a button or something you want.

Body:
I've got some trouble.
I've got home page with 4 div elements with a different id.
Example:

All these div pick the height from the screen.
When page loads I made an automatic scroll to the div with id two

.

And from this position, I want to scroll to another position.
But I couldn't understand how to make this.

This is my factory wich made slow scroll to position by using ng-click.

(function () {
    'use strict';

    angular
        .module('app.scroll.home.page', [])
        .factory('$scrollHomePage', $scrollHomePage);

    $scrollHomePage.inject = [];

    function $scrollHomePage() {
        return {
            scrollTo: function(eId) {

                var startY = currentYPosition();
                var stopY = elmYPosition(eId);
                var distance = stopY > startY ? stopY - startY : startY - stopY;
                if (distance < 100) {
                    scrollTo(0, stopY);
                    return;
                }
                var speed = Math.round(distance / 65);
                if (speed >= 250) speed = 250;
                var step = Math.round(distance / 25);
                var leapY = stopY > startY ? startY + step : startY - step;
                var timer = 0;
                if (stopY > startY) {
                    for (var i = startY; i < stopY; i += step) {
                        setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed);
                        leapY += step;
                        if (leapY > stopY) leapY = stopY;
                        timer++;
                    }
                    return;
                }
                for (var i = startY; i > stopY; i -= step) {
                    setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed);
                    leapY -= step;
                    if (leapY < stopY) leapY = stopY;
                    timer++;
                }

                function currentYPosition() {
                    if ('scrollRestoration' in history) {
                        history.scrollRestoration = 'manual';
                    }
                    if (document.documentElement && document.documentElement.scrollTop)
                        return document.documentElement.scrollTop;
                    if (document.body.scrollTop) return document.body.scrollTop;
                    return 0;
                }

                function elmYPosition(eID) {
                    var elm = document.getElementById(eID);
                    var y = elm.offsetTop;
                    var node = elm;
                    while (node.offsetParent && node.offsetParent != document.body) {
                        node = node.offsetParent;
                        y += node.offsetTop;
                    }
                    return y;
                }
            }

        };
    }
})();

and in controller I used automatical scroll by

$(window).load(function () {
            $("div.sectionscroll").height($('body').height());
            $location.hash('');
            $scrollHomePage.scrollTo('two');
        });

Body:
Hey @Volodymyr If I got your question correctly, you need to scroll to a particular hash (id of div)
You can use $anchorScroll and $location services of angular.

Below code will scroll to a div with id output and you can even add an offset to the scroll position if you want to take the user to a bit lower position than the exact div

$anchorScroll.yOffset = 30; // to add extra top margin
$location.hash('output');
$anchorScroll();

You can then call this function on ng-click of a button or something you want.


问:
How to formatting a monetary value with ICU hiding the minor units if zero
I'm trying to format a currency value with Zend's CurrencyFormat (using ICU). Basically it's working - the pattern #,##0.# outputs a correct format like
1.200,00 €.

Is it possible to leave out the minor unit part if it's zero just by modifying the pattern? I want to have the following formatting results:

1.200 € if minor units are ".00"

1.200,34 € if minour units are not ".00"

答:
I don't think it is possible to achieve it by modifying pattern. I mean, you can check if provided number is type of float or int. If it's int you can set different pattern, but there is simpler way (more recommended way IMO).

3rd argument of __invoke() method is $showDecimal. It takes bool value. If you want decimals to be visible- pass true (it's default value), false otherwise.

Example

true - if number is integer

```<code><?php echo $this->currencyFormat(1234, "EUR", true, "de_DE"); ?>
</code>```

Output:

1.234,00 €

false - if number is float

```<code><?php echo $this->currencyFormat(1234, "EUR", false, "de_DE"); ?>
</code>```

Output:

1.234 €

Loop example

```<code>// $prices = [1234, 1234.23, 234, 3456.54]
<?php foreach($prices as $price): ?>
    <?php $showDecimal = is_float($price) ? true : false;
    <p><?php echo $this->currencyFormat(1234, "EUR", $showDecimal, "de_DE"); ?></p>
<?php endforeach; ?>
</code>```

Global

If for some reason you want hide decimal numbers for all currencies/formats, you can use setShouldShowDecimals() method:

```<code>$this->plugin("currencyformat")->setShouldShowDecimals(false)->setCurrencyCode("USD")->setLocale("en_US");

echo $this->currencyFormat(1234.00);  // "$1,234"
</code>```

Here is a list of all available symbols for pattern http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#details

Body:
I don't think it is possible to achieve it by modifying pattern. I mean, you can check if provided number is type of float or int. If it's int you can set different pattern, but there is simpler way (more recommended way IMO).

3rd argument of __invoke() method is $showDecimal. It takes bool value. If you want decimals to be visible- pass true (it's default value), false otherwise.

Example

true - if number is integer

<?php echo $this->currencyFormat(1234, "EUR", true, "de_DE"); ?>

Output:

1.234,00 €

false - if number is float

<?php echo $this->currencyFormat(1234, "EUR", false, "de_DE"); ?>

Output:

1.234 €

Loop example

// $prices = [1234, 1234.23, 234, 3456.54]
<?php foreach($prices as $price): ?>
    <?php $showDecimal = is_float($price) ? true : false;
    <p><?php echo $this->currencyFormat(1234, "EUR", $showDecimal, "de_DE"); ?></p>
<?php endforeach; ?>

Global

If for some reason you want hide decimal numbers for all currencies/formats, you can use setShouldShowDecimals() method:

$this->plugin("currencyformat")->setShouldShowDecimals(false)->setCurrencyCode("USD")->setLocale("en_US");

echo $this->currencyFormat(1234.00);  // "$1,234"

Here is a list of all available symbols for pattern http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#details


问:
AlertDialog Class Cast exception
When i use android.support.v7.app.AlertDialog then i get class cast option if i use

setView(view)

method of AlertDialog . If i use android.app.AlertDialog then i have no crash but dialog is not in material style .

```<code>public class SearchFilterFragment extends DialogFragment {

boolean isAscending;
CheckBox checkbox;
View view;
SearchFilterInterface searchFilterInterface = null;
int which_one;
int array_id;

public interface SearchFilterInterface {

    void onSelect(int which, boolean asc);
}

public static SearchFilterFragment newInstance(@ArrayRes int array_id) {

    Bundle args = new Bundle();
    args.putInt(GiantBomb.ARRAY,array_id);
    SearchFilterFragment fragment = new SearchFilterFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        searchFilterInterface = (SearchFilterInterface) getTargetFragment();
    } catch (Exception e) {
        Toaster.make(getContext(), "interface cast exception");
    }

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    array_id = getArguments().getInt(GiantBomb.ARRAY);
    if (array_id==R.array.search_filter) {
        which_one = SharedPreference.getFromSharedPreferences(GiantBomb.WHICH, 4, getContext());
        isAscending = SharedPreference.getFromSharedPreferences(GiantBomb.ASCENDING, true, getContext());
    }else {
        which_one = SharedPreference.getFromSharedPreferences(GiantBomb.SORT_WHICH,1,getContext());
        isAscending = SharedPreference.getFromSharedPreferences(GiantBomb.SORT_ASCENDING,true,getContext());
    }
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    view = getActivity().getLayoutInflater().inflate(R.layout.search_option_layout,null);

    checkbox = (CheckBox) view.findViewById(R.id.checkbox);
    final int uncheck_color = ContextCompat.getColor(getContext(),R.color.black_white);
    checkbox.setChecked(!isAscending);
    if (!checkbox.isChecked()) { checkbox.setTextColor(uncheck_color) ;}

    final AlertDialog dialog =  new AlertDialog.Builder(getContext(),R.style.MyDialogTheme)
            .setCancelable(true)
            .setTitle("Sort result")

            .setSingleChoiceItems(getResources().getStringArray(array_id), which_one, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    which_one = which;
                }
            })
           //crashes here if i use v7 AlertDialog class
            .setView(view)

            }).create();
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialogInterface) {
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(getContext(),R.color.primary));
                }
            });
            return dialog;
}
</code>```

}

My custom view

```<code><?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:padding="20dp"

>

<CheckBox android:id="@+id/checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Descending"
android:textColor="?android:attr/textColorPrimary"
android:theme="@style/MyCheckBox"
android:drawableLeft="@android:color/transparent"
android:drawableStart="@android:color/transparent"
android:drawablePadding="20dp"
style="?android:attr/textAppearanceMedium"
 />

</FrameLayout>
</code>```

MyDialogTheme

```<code><style name="MyDialogTheme" parent="Theme.AppCompat.DayNight">
    <!--item RadioButton or CheckBox color-->
    <item name="colorControlNormal">@color/black_white</item>
    <item name="colorControlActivated">@color/accent</item>
    <!--item text color-->
    <item name="textColorAlertDialogListItem">?android:attr/textColorPrimary</item>
    <!--buttons color-->
    <item name="colorAccent">@color/accent</item>
    <!--title and message color-->
    <item name="android:textColor">?android:attr/textColorPrimary</item>
    <item name="android:background">@color/cardColor</item>

</style>
</code>```

Stack trace

```<code> java.lang.ClassCastException: android.support.v7.widget.LinearLayoutCompat$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                                at android.support.v7.app.AlertController.setupCustomContent(AlertController.java:655)
                                                                                at android.support.v7.app.AlertController.setupView(AlertController.java:463)
                                                                                at android.support.v7.app.AlertController.installContent(AlertController.java:226)
                                                                                at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
                                                                                at android.app.Dialog.dispatchOnCreate(Dialog.java:361)
                                                                                at android.app.Dialog.show(Dialog.java:262)
                                                                                at android.support.v4.app.DialogFragment.onStart(DialogFragment.java:418)
                                                                                at android.support.v4.app.Fragment.performStart(Fragment.java:2215)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1340)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
                                                                                at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                                                                                at android.os.Handler.handleCallback(Handler.java:733)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5113)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
                                                                                at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
It's a known bug in support-v7 library. For a workaround you can use a version <= 25.0.1

You can also follow the bug discussed in a related bug report:

https://code.google.com/p/android/issues/detail?id=231238

Title: AlertDialog Class Cast exception

Body:
When i use android.support.v7.app.AlertDialog then i get class cast option if i use

setView(view)

method of AlertDialog . If i use android.app.AlertDialog then i have no crash but dialog is not in material style .

public class SearchFilterFragment extends DialogFragment {

boolean isAscending;
CheckBox checkbox;
View view;
SearchFilterInterface searchFilterInterface = null;
int which_one;
int array_id;

public interface SearchFilterInterface {

    void onSelect(int which, boolean asc);
}

public static SearchFilterFragment newInstance(@ArrayRes int array_id) {

    Bundle args = new Bundle();
    args.putInt(GiantBomb.ARRAY,array_id);
    SearchFilterFragment fragment = new SearchFilterFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        searchFilterInterface = (SearchFilterInterface) getTargetFragment();
    } catch (Exception e) {
        Toaster.make(getContext(), "interface cast exception");
    }

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    array_id = getArguments().getInt(GiantBomb.ARRAY);
    if (array_id==R.array.search_filter) {
        which_one = SharedPreference.getFromSharedPreferences(GiantBomb.WHICH, 4, getContext());
        isAscending = SharedPreference.getFromSharedPreferences(GiantBomb.ASCENDING, true, getContext());
    }else {
        which_one = SharedPreference.getFromSharedPreferences(GiantBomb.SORT_WHICH,1,getContext());
        isAscending = SharedPreference.getFromSharedPreferences(GiantBomb.SORT_ASCENDING,true,getContext());
    }
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    view = getActivity().getLayoutInflater().inflate(R.layout.search_option_layout,null);

    checkbox = (CheckBox) view.findViewById(R.id.checkbox);
    final int uncheck_color = ContextCompat.getColor(getContext(),R.color.black_white);
    checkbox.setChecked(!isAscending);
    if (!checkbox.isChecked()) { checkbox.setTextColor(uncheck_color) ;}

    final AlertDialog dialog =  new AlertDialog.Builder(getContext(),R.style.MyDialogTheme)
            .setCancelable(true)
            .setTitle("Sort result")

            .setSingleChoiceItems(getResources().getStringArray(array_id), which_one, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    which_one = which;
                }
            })
           //crashes here if i use v7 AlertDialog class
            .setView(view)

            }).create();
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialogInterface) {
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(getContext(),R.color.primary));
                }
            });
            return dialog;
}

}

My custom view

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:padding="20dp"

>

<CheckBox android:id="@+id/checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Descending"
android:textColor="?android:attr/textColorPrimary"
android:theme="@style/MyCheckBox"
android:drawableLeft="@android:color/transparent"
android:drawableStart="@android:color/transparent"
android:drawablePadding="20dp"
style="?android:attr/textAppearanceMedium"
 />

</FrameLayout>

MyDialogTheme

Stack trace

 java.lang.ClassCastException: android.support.v7.widget.LinearLayoutCompat$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                                at android.support.v7.app.AlertController.setupCustomContent(AlertController.java:655)
                                                                                at android.support.v7.app.AlertController.setupView(AlertController.java:463)
                                                                                at android.support.v7.app.AlertController.installContent(AlertController.java:226)
                                                                                at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
                                                                                at android.app.Dialog.dispatchOnCreate(Dialog.java:361)
                                                                                at android.app.Dialog.show(Dialog.java:262)
                                                                                at android.support.v4.app.DialogFragment.onStart(DialogFragment.java:418)
                                                                                at android.support.v4.app.Fragment.performStart(Fragment.java:2215)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1340)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
                                                                                at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                                                                                at android.os.Handler.handleCallback(Handler.java:733)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5113)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
                                                                                at dalvik.system.NativeStart.main(Native Method)


问:
Read invalid json in PHP
I have a problem with decoding json.
Here is the screen of the json where Google Chrome and Java recognized it.

Chrome: https://ibb.co/gZ33Qa

Android Studio: https://ibb.co/kTXV5a

I can not decode it in PHP via json_decode(), error number 4 is a syntax error.
How can you fix this json?

json himself

{"rs":[["addChd",["sFCF6",[
['zul.wgt.Div','sFCFb',{sclass:'transparent table contentHolder',prolog:'\n    '},[
['zk.Native','sFCFc',{prolog:'\n

Управляющая компания',epilog:'
'},[]],
['zk.Native','sFCFd',{prolog:'\n

\n            ',epilog:'\n
'},[
['zk.Native','sFCFe',{prolog:'

\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFf',{id:'nameLabel',sclass:'value',style:'font-weight: bold',value:'Общество с ограниченной ответственностью Управляющая компания "Якутск"'},[]]]],
['zk.Native','sFCFg',{prolog:'\n            '},[]],
['zk.Native','sFCFh',{prolog:'

\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFi',{id:'addressLabel',sclass:'value',multiline:true,value:'РС (Я), г.Якутск, ул.Орджоникидзе, д.38'},[]]]],
['zk.Native','sFCFj',{prolog:'\n            '},[]],
['zk.Native','sFCFk',{prolog:'

\n
    Телефоны:	\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFl',{id:'phoneLabel',sclass:'value',value:'8(4112) 40-56-41'},[]]]],
['zk.Native','sFCFm',{prolog:'\n            '},[]],
['zk.Native','sFCFn',{prolog:'

\n
    Директор:	\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFo',{id:'directorLabel',sclass:'value',value:'Молонов Алексей Владимирович тел.: 89142946345'},[]]]],
['zk.Native','sFCFp',{prolog:'\n            '},[]],
['zk.Native','sFCFq',{prolog:'

\n
    Бухгалтер:	\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFr',{id:'accounterLabel',sclass:'value',value:'Антипина Русалина Николаевна тел.: 89142946345'},[]]]],
['zk.Native','sFCFs',{prolog:'\n            '},[]],
['zk.Native','sFCFt',{prolog:'

\n
    Эл. адрес:	\n
    \n                    ',epilog:'\n                	\n

'},[
['zul.wgt.Label','sFCFu',{id:'emailLabel',sclass:'value',value:'kk_centr_2013@mail.ru'},[]]]]]],
['zk.Native','sFCFv',{prolog:'\n

'},[]],
['zul.box.Vlayout','sFCFw',{id:'noteHolder',prolog:'\n        '},[]],
['zk.Native','sFCFx',{prolog:'\n

'},[]]]]]]],["script",["jq('.contentHolder').hide().fadeIn(500); select_menu_item('organization');"]]],"rid":1}```

答:
I think the problem is with what the API is delivering. I have had a similar problem in the past with a Google API delivering incorrect JSON.

You could try the following:

Replace single quotes with double quotes:

```<code>$result=str_replace($test,'\'','"');
</code>```

Use preg_replace to wrap keys in double quotes:

```<code>$pattern='/\b([^"].*?[^"])\b:(.*?[,}])/';
$result=preg_replace($pattern,'"\1":\2',$result);
</code>```

That might help.

Title: Read invalid json in PHP

Body:
I think the problem is with what the API is delivering. I have had a similar problem in the past with a Google API delivering incorrect JSON.

You could try the following:

Replace single quotes with double quotes:

$result=str_replace($test,'\'','"');

Use preg_replace to wrap keys in double quotes:

$pattern='/\b([^"].*?[^"])\b:(.*?[,}])/';
$result=preg_replace($pattern,'"\1":\2',$result);

That might help.


问:
Return only one of the matching columns of a JOIN
I use RODBC to connect R to a SQL Server database, e.g.

```<code>test1 <- sqlQuery(channel_gh,
         query=test1.Query <-
           paste("SELECT *",
                 "FROM Table1 a",
                 "INNER JOIN Table2 b ON a.nId = b.nId",
                 "WHERE nLeistung=",LeistungId,
                 "AND dDatum < '20150101'",
                 "AND dDatum > '20131231'"))
</code>```

I have noticed that, in joins, columns that define the join are returned twice:

```<code>> names(test1)
[1] "nId" "nLeistung" "nAnzahl"  "dDatum" "nId.1" "nQuartal" "nAGruppe" ...
</code>```

This would be an irrelevant nuisance if it would not interfere with further work:

```<code>test2 <- sqlQuery(channel_gh,
                  query=test2.Query <-
                    paste("WITH Test1Restult AS (", test1.Query, ")",
                          "SELECT * FROM Test1Result tr",
                          "JOIN Table2 b ON tr.Id = b.Id",
                          "WHERE nLeistung='1144'"))

> test2
</code>```

[1] "42000 8156 [Microsoft][ODBC SQL Server Driver][SQL Server]The column 'nId' was specified multiple times for 'Test1Restult'."

[2] "[RODBC] ERROR: Could not SQLExecDirect [...]

If I change test1 to return only one of the Id columns, the second query works. But I do not prefer this solution because there are quite a lot of columns in Table1 and Table2 and I do not want to list all of them every time I do a join.

Unfortunately I cannot check whether this problem exists only in R-accessed SQL Server, or in general.

Is there a way to obtain only one instance of JOIN ON columns in SQL Server joins?

答:
In SQL Server, you would have to list the columns for all but one table:

```<code>SELECT a.*, b.col1, b.col2, . . .
FROM Table1 a INNER JOIN
     Table2 b
     ON a.nId = b.nId
WHERE nLeistung = LeistungId AND dDatum < '20150101' AND
      dDatum > '20131231';
</code>```

Other databases support the USING clause.  This allows you to do:

```<code>SELECT *
FROM Table1 a INNER JOIN
     Table2 b
     USING (nId)
WHERE nLeistung = LeistungId AND dDatum < '20150101' AND
      dDatum > '20131231';
</code>```

Only one nid would be in the result set.  However, SQL Server does not support this (standard) syntax.

Body:
I use RODBC to connect R to a SQL Server database, e.g.

test1 <- sqlQuery(channel_gh,
         query=test1.Query <-
           paste("SELECT *",
                 "FROM Table1 a",
                 "INNER JOIN Table2 b ON a.nId = b.nId",
                 "WHERE nLeistung=",LeistungId,
                 "AND dDatum < '20150101'",
                 "AND dDatum > '20131231'"))

I have noticed that, in joins, columns that define the join are returned twice:

> names(test1)
[1] "nId" "nLeistung" "nAnzahl"  "dDatum" "nId.1" "nQuartal" "nAGruppe" ...

This would be an irrelevant nuisance if it would not interfere with further work:

test2 <- sqlQuery(channel_gh,
                  query=test2.Query <-
                    paste("WITH Test1Restult AS (", test1.Query, ")",
                          "SELECT * FROM Test1Result tr",
                          "JOIN Table2 b ON tr.Id = b.Id",
                          "WHERE nLeistung='1144'"))

> test2

[1] "42000 8156 [Microsoft][ODBC SQL Server Driver][SQL Server]The column 'nId' was specified multiple times for 'Test1Restult'."

[2] "[RODBC] ERROR: Could not SQLExecDirect [...]

If I change test1 to return only one of the Id columns, the second query works. But I do not prefer this solution because there are quite a lot of columns in Table1 and Table2 and I do not want to list all of them every time I do a join.

Unfortunately I cannot check whether this problem exists only in R-accessed SQL Server, or in general.

Is there a way to obtain only one instance of JOIN ON columns in SQL Server joins?

Body:
In SQL Server, you would have to list the columns for all but one table:

SELECT a.*, b.col1, b.col2, . . .
FROM Table1 a INNER JOIN
     Table2 b
     ON a.nId = b.nId
WHERE nLeistung = LeistungId AND dDatum < '20150101' AND
      dDatum > '20131231';

Other databases support the USING clause.  This allows you to do:

SELECT *
FROM Table1 a INNER JOIN
     Table2 b
     USING (nId)
WHERE nLeistung = LeistungId AND dDatum < '20150101' AND
      dDatum > '20131231';

Only one nid would be in the result set.  However, SQL Server does not support this (standard) syntax.


问:
Log4Net - make smtp appender send email only after 100 errors
I would like to send an email only after 100 ERRORS were written as a html table(That's the purpose of the SmtpExtendedAppender, iterate over all the messages that were saved) but I am not sure how to access them.

This is my app.config:

```<code><appender name="SmtpAppender" type="log4net.Appender.SmtpExtendedAppender">
        <authentication value="Basic" />
        <password value="xxxxxx"/>
        <username value="xxxxxxxx"/>
        <from value="myemail@gmail.com" />
        <to value="toemail@gmail.com" />
        <smtpHost value="smtp.gmail.com" />
        <isBodyHtml value="true" />
        <bufferSize value="100" />
        <EnableSsl value="true"/>
        <subject value="test logging message" />
        <lossy value="true" />
        <evaluator type="log4net.Core.LevelEvaluator">
            <threshold value="WARN"/>
        </evaluator>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date{ABSOLUTE} [%logger]%newlineUsername: %property{username}%newline%level - %message%newline%exception" />
        </layout>
    </appender>
</code>```

This is my console application:

```<code>static void Main(string[] args)
        {
            Console.WriteLine("hello world");

            log.Error("This is my first error message");

            log.Error("This is my second error message");

            Console.ReadLine();
        }
</code>```

I am not fully understand how the log4net buffer size works, even though I gave it a value of 100, it sends me 2 separated emails every time I run my console application.

If I will run this application 50 times to get to 100 ERRORS, would it be possible to accumulate them  and then send them in one email?

答: No that is not possible. The appender works not over multiple instances of your application. Every time you restart your application, all buffers are empty.</p>

Body:
I would like to send an email only after 100 ERRORS were written as a html table(That's the purpose of the SmtpExtendedAppender, iterate over all the messages that were saved) but I am not sure how to access them.

This is my app.config:

<appender name="SmtpAppender" type="log4net.Appender.SmtpExtendedAppender">
        <authentication value="Basic" />
        <password value="xxxxxx"/>
        <username value="xxxxxxxx"/>
        <from value="myemail@gmail.com" />
        <to value="toemail@gmail.com" />
        <smtpHost value="smtp.gmail.com" />
        <isBodyHtml value="true" />
        <bufferSize value="100" />
        <EnableSsl value="true"/>
        <subject value="test logging message" />
        <lossy value="true" />
        <evaluator type="log4net.Core.LevelEvaluator">
            <threshold value="WARN"/>
        </evaluator>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date{ABSOLUTE} [%logger]%newlineUsername: %property{username}%newline%level - %message%newline%exception" />
        </layout>
    </appender>

This is my console application:

static void Main(string[] args)
        {
            Console.WriteLine("hello world");

            log.Error("This is my first error message");

            log.Error("This is my second error message");

            Console.ReadLine();
        }

I am not fully understand how the log4net buffer size works, even though I gave it a value of 100, it sends me 2 separated emails every time I run my console application.

If I will run this application 50 times to get to 100 ERRORS, would it be possible to accumulate them  and then send them in one email?


问:
How to upload PHP and MySQL into a webserver
I am developing a site in vertigoserver. Now I need to test the webpage in webserver.

I am using the webserver Host-Europe VirtualServer 3.0.

Now what are the steps I need to upload the PHP pages?

What is the software needed to upload MySQL queries?

Are there any tutorials or suggestions?

答:
This seems like basic stuff, but I'll give you some pointers!

Upload the pages with an FTP client or similar. If you have shell access, tools like rsync can make this easier.

You've probably got some sort of web based front end for MySQL like phpMyAdmin - this will let you upload and restore a database dump. If you have shell access, or if the MySQL server is open to the Internet, you can pipe the dump into the MySQL command line client, for example,

```<code>mysql -h<hostname> -u<username> -p<password> mydatabase < dump.mysql
</code>```

OwnerDisplayName: venkatachalam

LastEditorDisplayName: Paul Dixon

Body:
This seems like basic stuff, but I'll give you some pointers!

Upload the pages with an FTP client or similar. If you have shell access, tools like rsync can make this easier.

You've probably got some sort of web based front end for MySQL like phpMyAdmin - this will let you upload and restore a database dump. If you have shell access, or if the MySQL server is open to the Internet, you can pipe the dump into the MySQL command line client, for example,

mysql -h<hostname> -u<username> -p<password> mydatabase < dump.mysql

OwnerDisplayName: Paul Dixon