问:
TransactionSystemException: Could not roll back Hibernate Transaction; Transaction not started
I have a test causing an error because of Hibernate. I have no idea how to resolve this problem. This is the stacktrace:

```<code> org.springframework.transaction.TransactionSystemException: Could not roll back Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:677)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:823)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:800)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:501)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:277)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:170)
    at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:344)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runAfters(SpringMethodRoadie.java:307)
    at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:338)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197)
    at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:160)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.TransactionException: Transaction not successfully started
    at org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:183)
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:674)
    ... 24 more
</code>```

This is what the test causing the error looks like:

```<code>@Test
@Transactional
public void shouldNotBeAbleToAddCandidateWhenEmailAlreadyExistsInDatabase() {
    Candidate c = new Candidate();
    c.setEmail(EMAIL);
    c.setCompany(CompanyTest.createDefaultCompany());
    userDAO.create(c);
    Candidate candidateFromDb = (Candidate) userDAO.find(c.getId());
    assertEquals(c, candidateFromDb);

    Candidate failingCandidate = new Candidate();
    failingCandidate.setEmail(EMAIL);
    failingCandidate.setCompany(CompanyTest.createDefaultCompany());

    boolean foundDuplicate = false;
    try {
        userDAO.create(failingCandidate);
    } catch (DuplicateEmailException duplicateEmailException) {
        foundDuplicate = true;
    }
    assertTrue(foundDuplicate);
}
</code>```

This is what the Transaction Manager in applicatipnContext-dao.xml looks like:

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

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>
</code>```

This is the applicationContext.xml :

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

    <bean id="dataConfigPropertyConfigurer"
                class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
        <property name="locations">
            <list>
                <value>classpath:${app.env}.properties</value>
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true"/>
    </bean>

    <bean id="wicketConfiguration" class="com.firmfactory.work.WicketConfiguration">
        <property name="configurationMode" value="development" />
        <property name="showStacktrace" value="true" />
    </bean>

    <context:component-scan base-package="com.firmfactory.work.daos" />
    <import resource="applicationContext-controllers.xml" />
    <import resource="applicationContext-services.xml" />

    <bean name="dataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
        <property name="url">
            <value>jdbc:mysql://localhost/workt?characterEncoding=UTF-8</value>
        </property>
        <property name="user">
            <value>work</value>
        </property>
        <property name="////">

        <!-- <value>work</value> -->
             <value>////</value>

        </property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="annotatedClasses">
            <list>
REMOVED SOME MODELS

        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

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

    <!-- <bean id="liquibase" class="liquibase.spring.SpringLiquibase">
        <property name="dataSource" ref="dataSource" />
        <property name="changeLog" value="classpath:DbChangeSet.xml" />
    </bean>-->

    <bean id="resumeInformationPriceString" class="java.lang.String">
        <constructor-arg value="25"></constructor-arg>
    </bean>

    <bean id="candidateInformationPriceString" class="java.lang.String">
        <constructor-arg value="75"></constructor-arg>
    </bean>

    <bean id="deafaultCompanyId" class="java.lang.Integer">
        <constructor-arg value="1"></constructor-arg>
    </bean>

    <bean id="uploadPath" class="java.lang.String">
        <constructor-arg value="/home/hudson/uploads/"></constructor-arg>
    </bean>

    <bean id="logoPath" class="java.lang.String">
        <constructor-arg value="../logos/"></constructor-arg>
    </bean>

    <tx:annotation-driven />
</beans>
</code>```

Edited applicationContext.xml as follows:

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

    <bean id="dataConfigPropertyConfigurer"
                class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
        <property name="locations">
            <list>
                <value>classpath:${app.env}.properties</value>
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true"/>
    </bean>

    <bean id="wicketConfiguration" class="com.firmfactory.work.WicketConfiguration">
        <property name="configurationMode" value="development" />
        <property name="showStacktrace" value="true" />
    </bean>

    <context:component-scan base-package="com.firmfactory.work.daos" />
    <import resource="applicationContext-controllers.xml" />
    <import resource="applicationContext-services.xml" />

    <bean name="dataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
        <property name="url">
            <value>jdbc:mysql://localhost/work?characterEncoding=UTF-8</value>
        </property>
        <property name="user">
            <value>work</value>
        </property>
        <property name="///">

        <!-- <value>work</value> -->
             <value>///</value>

        </property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="annotatedClasses">
            <list>
                <removed propertys of models>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.transaction">true</prop>
            </props>
        </property>
    </bean>

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

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- <bean id="liquibase" class="liquibase.spring.SpringLiquibase">
        <property name="dataSource" ref="dataSource" />
        <property name="changeLog" value="classpath:DbChangeSet.xml" />
    </bean>-->

    <bean id="resumeInformationPriceString" class="java.lang.String">
        <constructor-arg value="25"></constructor-arg>
    </bean>

    <bean id="candidateInformationPriceString" class="java.lang.String">
        <constructor-arg value="75"></constructor-arg>
    </bean>

    <bean id="deafaultCompanyId" class="java.lang.Integer">
        <constructor-arg value="1"></constructor-arg>
    </bean>

    <bean id="uploadPath" class="java.lang.String">
        <constructor-arg value="/home/hudson/uploads/"></constructor-arg>
    </bean>

    <bean id="logoPath" class="java.lang.String">
        <constructor-arg value="../logos/"></constructor-arg>
    </bean>

</beans>
</code>```

New (seemingly identical?) stacktrace:

```<code> org.springframework.transaction.TransactionSystemException: Could not roll back Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:677)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:823)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:800)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:501)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:277)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:170)
    at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:344)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runAfters(SpringMethodRoadie.java:307)
    at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:338)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197)
    at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:160)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.TransactionException: Transaction not successfully started
    at org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:183)
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:674)
    ... 24 more
</code>```

答:
add this conf. in your application-context.xml

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

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"  p:sessionFactory-ref="sessionFactory">
    </bean>
</code>```

hibernate.properties should contain

```<code>org.hibernate.transaction true
</code>```

Test class should be configured like

```<code>import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/yourapplication-context.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class MyTest {
</code>```

Note: not all fields may be required , I have just shown a working conf.

Body:
I have a test causing an error because of Hibernate. I have no idea how to resolve this problem. This is the stacktrace:

 org.springframework.transaction.TransactionSystemException: Could not roll back Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:677)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:823)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:800)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:501)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:277)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:170)
    at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:344)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runAfters(SpringMethodRoadie.java:307)
    at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:338)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197)
    at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:160)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.TransactionException: Transaction not successfully started
    at org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:183)
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:674)
    ... 24 more

This is what the test causing the error looks like:

@Test
@Transactional
public void shouldNotBeAbleToAddCandidateWhenEmailAlreadyExistsInDatabase() {
    Candidate c = new Candidate();
    c.setEmail(EMAIL);
    c.setCompany(CompanyTest.createDefaultCompany());
    userDAO.create(c);
    Candidate candidateFromDb = (Candidate) userDAO.find(c.getId());
    assertEquals(c, candidateFromDb);

    Candidate failingCandidate = new Candidate();
    failingCandidate.setEmail(EMAIL);
    failingCandidate.setCompany(CompanyTest.createDefaultCompany());

    boolean foundDuplicate = false;
    try {
        userDAO.create(failingCandidate);
    } catch (DuplicateEmailException duplicateEmailException) {
        foundDuplicate = true;
    }
    assertTrue(foundDuplicate);
}

This is what the Transaction Manager in applicatipnContext-dao.xml looks like:

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

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

This is the applicationContext.xml :

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

    <bean id="dataConfigPropertyConfigurer"
                class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
        <property name="locations">
            <list>
                <value>classpath:${app.env}.properties</value>
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true"/>
    </bean>

    <bean id="wicketConfiguration" class="com.firmfactory.work.WicketConfiguration">
        <property name="configurationMode" value="development" />
        <property name="showStacktrace" value="true" />
    </bean>

    <context:component-scan base-package="com.firmfactory.work.daos" />
    <import resource="applicationContext-controllers.xml" />
    <import resource="applicationContext-services.xml" />

    <bean name="dataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
        <property name="url">
            <value>jdbc:mysql://localhost/workt?characterEncoding=UTF-8</value>
        </property>
        <property name="user">
            <value>work</value>
        </property>
        <property name="////">

             <value>////</value>

        </property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="annotatedClasses">
            <list>
REMOVED SOME MODELS

        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

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

    <bean id="resumeInformationPriceString" class="java.lang.String">
        <constructor-arg value="25"></constructor-arg>
    </bean>

    <bean id="candidateInformationPriceString" class="java.lang.String">
        <constructor-arg value="75"></constructor-arg>
    </bean>

    <bean id="deafaultCompanyId" class="java.lang.Integer">
        <constructor-arg value="1"></constructor-arg>
    </bean>

    <bean id="uploadPath" class="java.lang.String">
        <constructor-arg value="/home/hudson/uploads/"></constructor-arg>
    </bean>

    <bean id="logoPath" class="java.lang.String">
        <constructor-arg value="../logos/"></constructor-arg>
    </bean>

    <tx:annotation-driven />
</beans>

Edited applicationContext.xml as follows:

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

    <bean id="dataConfigPropertyConfigurer"
                class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
        <property name="locations">
            <list>
                <value>classpath:${app.env}.properties</value>
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true"/>
    </bean>

    <bean id="wicketConfiguration" class="com.firmfactory.work.WicketConfiguration">
        <property name="configurationMode" value="development" />
        <property name="showStacktrace" value="true" />
    </bean>

    <context:component-scan base-package="com.firmfactory.work.daos" />
    <import resource="applicationContext-controllers.xml" />
    <import resource="applicationContext-services.xml" />

    <bean name="dataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
        <property name="url">
            <value>jdbc:mysql://localhost/work?characterEncoding=UTF-8</value>
        </property>
        <property name="user">
            <value>work</value>
        </property>
        <property name="///">

             <value>///</value>

        </property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="annotatedClasses">
            <list>
                <removed propertys of models>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.transaction">true</prop>
            </props>
        </property>
    </bean>

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

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="resumeInformationPriceString" class="java.lang.String">
        <constructor-arg value="25"></constructor-arg>
    </bean>

    <bean id="candidateInformationPriceString" class="java.lang.String">
        <constructor-arg value="75"></constructor-arg>
    </bean>

    <bean id="deafaultCompanyId" class="java.lang.Integer">
        <constructor-arg value="1"></constructor-arg>
    </bean>

    <bean id="uploadPath" class="java.lang.String">
        <constructor-arg value="/home/hudson/uploads/"></constructor-arg>
    </bean>

    <bean id="logoPath" class="java.lang.String">
        <constructor-arg value="../logos/"></constructor-arg>
    </bean>

</beans>

New (seemingly identical?) stacktrace:

 org.springframework.transaction.TransactionSystemException: Could not roll back Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:677)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:823)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:800)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:501)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:277)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:170)
    at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:344)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runAfters(SpringMethodRoadie.java:307)
    at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:338)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217)
    at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197)
    at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:160)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.TransactionException: Transaction not successfully started
    at org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:183)
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:674)
    ... 24 more

Body:
add this conf. in your application-context.xml

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

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"  p:sessionFactory-ref="sessionFactory">
    </bean>

hibernate.properties should contain

org.hibernate.transaction true

Test class should be configured like

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/yourapplication-context.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class MyTest {

Note: not all fields may be required , I have just shown a working conf.


来源: stackexchange

问:
How to access an object defined in a function from another function?
I am building a simple GUI app to manage priorities. I'm stuck with accessing an object defined in a function from another function, in this instance accessing root in the function createWindow from display(). The window opens but there is no label, and this is what it gives me when I quit the program:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
  Traceback (most recent call last):   File
  "/home/cali/PycharmProjects/priorities/priorities.py", line 34, in

      c.main()   File "/home/cali/PycharmProjects/priorities/priorities.py", line 31, in
  main
      g.display()   File "/home/cali/PycharmProjects/priorities/priorities.py", line 22, in
  display
      Label(root, NameError: name 'root' is not defined

Process finished with exit code 1

Here is what I have done so far:

```<code># priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:
    pass

class GuiPart:

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title = "Priorities"
        root.mainloop()

        return root

    def display(self):

        Label(root,
              text = "testes").grid(row = 0, column = 1)

class Client:

    def main(self):

        g = GuiPart()
        g.createWindow()
        g.display()

c = Client()
c.main()
</code>```

I'm using Python 3.6.

答:
I think what you probably want to do is store root as an instance variable of the GuiPart class once createWindow() is called:

```<code>class GuiPart:
    def __init__(self):
        self.root = createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title = "Priorities"
        root.mainloop()

        return root

    def display(self):

        Label(self.root,
              text = "testes").grid(row = 0, column = 1)
</code>```

What happens now is that root is stored as g.root when you create the GuiPart instance. Your main function would just look like this then:

```<code>def main(self):

    g = GuiPart()
    g.display()
</code>```

You could also do it like this:

```<code>class GuiPart:
    def __init__(self):
        self.root = None

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title = "Priorities"
        root.mainloop()

        self.root = root

    def display(self):

        Label(self.root,
              text = "testes").grid(row = 0, column = 1)
</code>```

Then your main would be like this:

```<code>def main(self):
    g = GuiPart()
    g.createWindow()
    g.display()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am building a simple GUI app to manage priorities. I'm stuck with accessing an object defined in a function from another function, in this instance accessing root in the function createWindow from display(). The window opens but there is no label, and this is what it gives me when I quit the program:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
  Traceback (most recent call last):   File
  "/home/cali/PycharmProjects/priorities/priorities.py", line 34, in

      c.main()   File "/home/cali/PycharmProjects/priorities/priorities.py", line 31, in
  main
      g.display()   File "/home/cali/PycharmProjects/priorities/priorities.py", line 22, in
  display
      Label(root, NameError: name 'root' is not defined

Process finished with exit code 1

Here is what I have done so far:

# priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:
    pass

class GuiPart:

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title = "Priorities"
        root.mainloop()

        return root

    def display(self):

        Label(root,
              text = "testes").grid(row = 0, column = 1)

class Client:

    def main(self):

        g = GuiPart()
        g.createWindow()
        g.display()

c = Client()
c.main()

I'm using Python 3.6.

Body:
I think what you probably want to do is store root as an instance variable of the GuiPart class once createWindow() is called:

class GuiPart:
    def __init__(self):
        self.root = createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title = "Priorities"
        root.mainloop()

        return root

    def display(self):

        Label(self.root,
              text = "testes").grid(row = 0, column = 1)

What happens now is that root is stored as g.root when you create the GuiPart instance. Your main function would just look like this then:

def main(self):

    g = GuiPart()
    g.display()

You could also do it like this:

class GuiPart:
    def __init__(self):
        self.root = None

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title = "Priorities"
        root.mainloop()

        self.root = root

    def display(self):

        Label(self.root,
              text = "testes").grid(row = 0, column = 1)

Then your main would be like this:

def main(self):
    g = GuiPart()
    g.createWindow()
    g.display()


问:
class-loading throwing error in JBoss Wildfly
When I deployed my application mono.ear in JBoss 4.2, our jboss-web.xml has class-loading like below:

<class-loading java2ClassLoadingCompliance='false'>
    <loader-repository>
      com.mono.techstack:loader=mono.ear
    </loader-repository>
</class-loading>
```

Now I am migrating JBoss 4.2 to Wildfly 8.
When I deployed my application mono.ear in JBoss Wildfly, class-loading is throwing error. So how can I load class in Wildfly 8?

答: I'm not familiar with JBoss 4, but when I deploy to Wildfly 8 & 9, i'm not even using any class loading directives. All of the dependencies defined in Maven are loaded automatically. There's some information here: https://docs.jboss.org/author/display/WFLY8/Class+Loading+in+WildFly</p>

Body:
When I deployed my application mono.ear in JBoss 4.2, our jboss-web.xml has class-loading like below:

<class-loading java2ClassLoadingCompliance='false'>
    <loader-repository>
      com.mono.techstack:loader=mono.ear
    </loader-repository>
</class-loading>

Now I am migrating JBoss 4.2 to Wildfly 8.
When I deployed my application mono.ear in JBoss Wildfly, class-loading is throwing error. So how can I load class in Wildfly 8?


问:
JUnit 5 Before TestFactory Annotation
I've written a dynamic Test @TestFactory in JUnit5, now I've seen I can't do @Before for a dynamic Test, referring to
JUnit 5 User Guide - Writing Test Annotations.

Is there any workaround to do a @Before or similar to that before a TestFactory?

Method I want to put in an @Before since it's only initialization stuff:

```<code>public static void initialize() throws Exception{
    buildTest = new XQueryTestHelper();
    buildTest.initialization();

    listTestSuiteIdentifier = buildTest.getListTestsuiteIdentifier();
    arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
    arrayHeaderAndBodyTestcases = buildTest.getHeaderAndBodyTestcases();
    listHeaderAndBodyTestSuites = buildTest.getHeaderAndBodyTestSuites();
    listHdrInbPayTestSuites = buildTest.getHdrInbPayTestsuites();

}
</code>```

Solution:

Using @BeforeAll / @AfterAll is possible in a dynamic Test. Referring to
Improve documentation of DynamicTest lifecycle

Dynamic Test Lifecycle

The execution lifecycle of a dynamic test is quite different than it is for a standard @Test case. Specifically, there are not any lifecycle callbacks for dynamic tests. This means that @BeforeEach and @AfterEach methods and their corresponding extension callbacks are not executed for dynamic tests. In other words, if you access fields from the test instance within a lambda expression for a dynamic test, those fields will not be reset by callback methods or extensions between the execution of dynamic tests generated by the same @TestFactory method.

ContentLicense: CC BY-SA 4.0

Title: JUnit 5 Before TestFactory Annotation

Body:
I've written a dynamic Test @TestFactory in JUnit5, now I've seen I can't do @Before for a dynamic Test, referring to
JUnit 5 User Guide - Writing Test Annotations.

Is there any workaround to do a @Before or similar to that before a TestFactory?

Method I want to put in an @Before since it's only initialization stuff:

public static void initialize() throws Exception{
    buildTest = new XQueryTestHelper();
    buildTest.initialization();

    listTestSuiteIdentifier = buildTest.getListTestsuiteIdentifier();
    arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
    arrayHeaderAndBodyTestcases = buildTest.getHeaderAndBodyTestcases();
    listHeaderAndBodyTestSuites = buildTest.getHeaderAndBodyTestSuites();
    listHdrInbPayTestSuites = buildTest.getHdrInbPayTestsuites();

}

Solution:

Using @BeforeAll / @AfterAll is possible in a dynamic Test. Referring to
Improve documentation of DynamicTest lifecycle

Dynamic Test Lifecycle

The execution lifecycle of a dynamic test is quite different than it is for a standard @Test case. Specifically, there are not any lifecycle callbacks for dynamic tests. This means that @BeforeEach and @AfterEach methods and their corresponding extension callbacks are not executed for dynamic tests. In other words, if you access fields from the test instance within a lambda expression for a dynamic test, those fields will not be reset by callback methods or extensions between the execution of dynamic tests generated by the same @TestFactory method.


问:
Date to Correct Format (Ex. 01-MAR-2017 00:00:00)
Every time I've tried to change my date to a specific format, excel automatically autoformats to "3/1/2017 0:00" instead of 01-MAR-2017 00:00:00.

My code is the following:

```<code>objMasterDefectLog.Sheets(1).Range(strFrozenCustReqDateLoc).Offset(iCounter, 0).Value = Format(tempString, "dd-mmm-yyyy hh:mm:ss")
</code>```

Even if I convert tempString into a date, it still does not format correctly. I would rather not parse everything out if I don't have to.

答:
Did you want the cell to contain the date/time, or text that presents the date/time? If the former, use @Peh's example. If the latter, you could force it with the old apostrophe trick:</p>

```<code>...Offset(iCounter, 0).Value = "'" & Ucase(Format(tempString, "dd-mmm-yyyy hh:mm:ss"))
</code>```

Body:
Every time I've tried to change my date to a specific format, excel automatically autoformats to "3/1/2017 0:00" instead of 01-MAR-2017 00:00:00.

My code is the following:

objMasterDefectLog.Sheets(1).Range(strFrozenCustReqDateLoc).Offset(iCounter, 0).Value = Format(tempString, "dd-mmm-yyyy hh:mm:ss")

Even if I convert tempString into a date, it still does not format correctly. I would rather not parse everything out if I don't have to.

Body:
Did you want the cell to contain the date/time, or text that presents the date/time? If the former, use @Peh's example. If the latter, you could force it with the old apostrophe trick:

...Offset(iCounter, 0).Value = "'" & Ucase(Format(tempString, "dd-mmm-yyyy hh:mm:ss"))


问:
Detecting colour of a specific x and y coordinate of an image in MATLAB
I'm trying to obtain the colour of a specific coordinate on an image. For example: X is an image with size width:300 and height:300. I would like to know the colour at x:10 and y:10 coordinate. I couldn't write any code because I don't know if this is even possible in matlab?

Thank you.

答:
If you want to get the color by manually selecting a pixel in Matlab you can do something like that:

```<code>A = imread('Lena.png');
imshow(A);
[x,y] = ginput(1); % Select a point on the plot
x = fix(x); y = fix(y); % Fix to nearest pixel
hold on;
plot(x,y,'bo'); % Plot the point
color = squeeze(A(x,y,:))'; % Get the color
</code>```

and then even use something like that to convert it to it's name. In this particular example the code would be maybe something like that:

```<code>A = imread('Lena.png');
h = figure;
imshow(A);
while true
    [x,y,key] = ginput(1);
    x = fix(x); y = fix(y);
    hold on;
    plot(x,y,'bo');
    color = squeeze(A(x,y,:))';
    name = rgb2name(double(color)/256);
    disp(name);
    if key == 27; break; end; % key == escape
end
close(h);
</code>```

Have fun! ;)

Body:
If you want to get the color by manually selecting a pixel in Matlab you can do something like that:

A = imread('Lena.png');
imshow(A);
[x,y] = ginput(1); % Select a point on the plot
x = fix(x); y = fix(y); % Fix to nearest pixel
hold on;
plot(x,y,'bo'); % Plot the point
color = squeeze(A(x,y,:))'; % Get the color

and then even use something like that to convert it to it's name. In this particular example the code would be maybe something like that:

A = imread('Lena.png');
h = figure;
imshow(A);
while true
    [x,y,key] = ginput(1);
    x = fix(x); y = fix(y);
    hold on;
    plot(x,y,'bo');
    color = squeeze(A(x,y,:))';
    name = rgb2name(double(color)/256);
    disp(name);
    if key == 27; break; end; % key == escape
end
close(h);

Have fun! ;)


问:
Can I add a wrapper to my layout that has a pure CSS dynamic sticky footer?
After countless hours trying to find a way to implement a sticky footer with fluid height without resorting to using javascript, I finally found a way. No matter how much content I add to the .footer, it remains stuck to the bottom of the viewport, regardless of whether there is enough in the .content div to push it down. None of the javascript solutions I tried worked as smoothly as this, and I'd like to keep using this method if possible.

My problem is that due to an issue with various mobile browsers not accepting the overflow-x:hidden; rule on the body tag, I'm now having to add a wrapper to my layout. This fixes the mobile browser issue, but unfortunately stops the .footer from sticking to the bottom of the viewport when the .content div is empty.

I have of course tried to move several of the CSS rules from the body to the wrapper to see if this works, but I haven't had any success. Is there a way around this?

Here are two jsFiddle examples to show the problem, one with a .wrapper and one without.

Example 1: Without wrapper (Sticky footer works) – https://jsfiddle.net/v5h2f5wd/

Example 2: With wrapper (Sticky footer does not work) – https://jsfiddle.net/v5h2f5wd/1/

Code from Example 2:

```<code><div class="wrapper">
    <header class="header"></header>
        <div class="content">
            <button>Click here to insert content into footer.</button>
        </div>
    <footer class="footer"></footer>
</div>

html {
    position:relative;
    height:100%;
}

body {
    position:relative;
    width:100%;
    min-height:100%;
    margin:0;
    padding:0;
    overflow-x:hidden;
    background-color:#eee;
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
}

.header {
    position:absolute;
    width:100%;
    height:55px;
    background-color:#fff;
}

.content {
    -webkit-box-flex:1;
    -webkit-flex:1;
    -ms-flex:1;
    flex:1;
    width:100%;
    height:auto;
    background-color:pink;
}

button {
    margin:65px 0 0 10px;
}

.footer {
    width:100%;
    background-color:#fff;
    padding:25px 0;
}
</code>```

答:
Here is a flexbox solution.

Looks like you were trying to do something similar. The key points in this setup are height: 100%; on the html element (inherits from viewport height), min-height: 100%; on body element (inherits from html height) and flex-grow: 1; on main element (tells element to take up remaining space inside the container element).

With this solution the footer's height is dynamic which saves you the headache of have to update selectors in your stylesheet if it ever changes.

The JS in the solution is simply for demo purposes.

var btnC   = document.querySelector( '.btn-c' );
var btnF   = document.querySelector( '.btn-f' );
var main   = document.querySelector( 'main' );
var footer = document.querySelector( 'footer' );

function addContent( target, str ) {

    var p = document.createElement( 'p' );

    p.innerHTML = str;

    target.appendChild( p );

}

btnC.addEventListener( 'click', function ( e ) {

  for ( var i = 0, len = 5; i < len; i++ ) {
    addContent( main, 'Content' );
  }

} );

btnF.addEventListener( 'click', function ( e ) {
    addContent( footer, 'Footer' );
} );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 100%;
}
body {
  margin: 0;
}
header {
  background-color: gold;
}
main {
  flex-grow: 1;
  background-color: skyblue;
}
footer {
  background-color: indianred;
}
.wrap {
 display: flex;
 flex-direction: column;
 min-height: 100%;
}</code>```

    Header

      Content

    <button class="btn-c">Add to Content</button>

    <button class="btn-f">Add to Footer</button>

    Footer

```

No need to do all the positioning (unnecessary) and width declarations (those elements already take up 100% width because they're block level elements).

Body:
After countless hours trying to find a way to implement a sticky footer with fluid height without resorting to using javascript, I finally found a way. No matter how much content I add to the .footer, it remains stuck to the bottom of the viewport, regardless of whether there is enough in the .content div to push it down. None of the javascript solutions I tried worked as smoothly as this, and I'd like to keep using this method if possible.

My problem is that due to an issue with various mobile browsers not accepting the overflow-x:hidden; rule on the body tag, I'm now having to add a wrapper to my layout. This fixes the mobile browser issue, but unfortunately stops the .footer from sticking to the bottom of the viewport when the .content div is empty.

I have of course tried to move several of the CSS rules from the body to the wrapper to see if this works, but I haven't had any success. Is there a way around this?

Here are two jsFiddle examples to show the problem, one with a .wrapper and one without.

Example 1: Without wrapper (Sticky footer works) – https://jsfiddle.net/v5h2f5wd/

Example 2: With wrapper (Sticky footer does not work) – https://jsfiddle.net/v5h2f5wd/1/

Code from Example 2:

            <button>Click here to insert content into footer.</button>

html {
    position:relative;
    height:100%;
}

body {
    position:relative;
    width:100%;
    min-height:100%;
    margin:0;
    padding:0;
    overflow-x:hidden;
    background-color:#eee;
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
}

.header {
    position:absolute;
    width:100%;
    height:55px;
    background-color:#fff;
}

.content {
    -webkit-box-flex:1;
    -webkit-flex:1;
    -ms-flex:1;
    flex:1;
    width:100%;
    height:auto;
    background-color:pink;
}

button {
    margin:65px 0 0 10px;
}

.footer {
    width:100%;
    background-color:#fff;
    padding:25px 0;
}

Body:
Here is a flexbox solution.

Looks like you were trying to do something similar. The key points in this setup are height: 100%; on the html element (inherits from viewport height), min-height: 100%; on body element (inherits from html height) and flex-grow: 1; on main element (tells element to take up remaining space inside the container element).

With this solution the footer's height is dynamic which saves you the headache of have to update selectors in your stylesheet if it ever changes.

The JS in the solution is simply for demo purposes.

var btnC   = document.querySelector( '.btn-c' );
var btnF   = document.querySelector( '.btn-f' );
var main   = document.querySelector( 'main' );
var footer = document.querySelector( 'footer' );

function addContent( target, str ) {

    var p = document.createElement( 'p' );

    p.innerHTML = str;

    target.appendChild( p );

}

btnC.addEventListener( 'click', function ( e ) {

  for ( var i = 0, len = 5; i < len; i++ ) {
    addContent( main, 'Content' );
  }

} );

btnF.addEventListener( 'click', function ( e ) {
    addContent( footer, 'Footer' );
} );

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
header {
  background-color: gold;
}
main {
  flex-grow: 1;
  background-color: skyblue;
}
footer {
  background-color: indianred;
}
.wrap {
 display: flex;
 flex-direction: column;
 min-height: 100%;
}

<div class="wrap">
  <header>
    Header
  </header>
  <main>
    <p>
      Content
    </p>
    <button class="btn-c">Add to Content</button>
    <br>
    <button class="btn-f">Add to Footer</button>
  </main>
  <footer>
    Footer
  </footer>
</div>

No need to do all the positioning (unnecessary) and width declarations (those elements already take up 100% width because they're block level elements).


问:
Reporting Services export to Excel with Multiple Worksheets
I'm currently building a MS Reporting Services Report that gets rendered to excel. I'm trying to figure out how to set up the report so that it creates multiple Worksheets (Tabs) of the data on the report. I understand that entering a page break in the report gives you a new worksheet, however, is there a way to name each tab instead of it default to (worksheet 1, worksheet 2) etc.

How can this be done?

答:
To late for the original asker of the question, but with SQL Server 2008 R2 this is now possible:

Set the property "Pagebreak" on the tablix or table or other element to force a new tab, and then set the property "Pagename" on both the element before the pagebreak and the element after the pagebreak. These names will appear on the tabs when the report is exported to Excel.

Read about it here: http://technet.microsoft.com/en-us/library/dd255278.aspx

OwnerDisplayName: DotNetJayHawk

LastEditorDisplayName: Lawrence Johnston

ContentLicense: CC BY-SA 2.5


问:
CSS element not showing over image
I bet this is probably something stupid, I am trying put an absolute element over an image, but its not appearing.

```<code><div class="circle" style="position: absolute; top: 200px; left: 100px;"></div>

                    <img src="images/madison-siteplan.png" class="siteplan" />
</code>```

here is the attentional css for the circle:

```<code>.circle {
            border-radius: 50%;
            width: 100px;
            height: 100px;
            color: red;
            }
</code>```

答:
@Quentin is right, I just read his answer, but since I already made a snippet, I add it here. (I only added a background-color to the original code, apart from moving the inline CSS to the external CSS rule):

.circle {
  position: absolute;
  top: 200px;
  left: 100px;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  color: red;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="circle"> </div>
  <img src="http://placehold.it/400x400" class="siteplan" /></code>```

Title: CSS element not showing over image

Body:
I bet this is probably something stupid, I am trying put an absolute element over an image, but its not appearing.

here is the attentional css for the circle:

.circle {
            border-radius: 50%;
            width: 100px;
            height: 100px;
            color: red;
            }

Body:
@Quentin is right, I just read his answer, but since I already made a snippet, I add it here. (I only added a background-color to the original code, apart from moving the inline CSS to the external CSS rule):

.circle {
  position: absolute;
  top: 200px;
  left: 100px;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  color: red;
  background: green;
}

  <div class="circle"> </div>
  <img src="http://placehold.it/400x400" class="siteplan" />


问:
play framework using slick with java
I want to start a new play framework project, and I want to use a database mapper.
For Scala there is slick.

Can I use Slick with java as well? Or is there a nice pendant for java?

答:
The straightforward answer is no. You may be using it in Scala (eg. write DAO layer in Scala) and then use that in your Java but honestly it may be too much of a hustle.

There is no straightforword alternative - you would need to use Hibernate or Ebean.

Title: play framework using slick with java


问:
Redirect all blog posts from %postname% permalink structure to /news/%postname%
I have changed my permalink to the custom structure /news/%postname% however I am now trying to set up a 301 redirect so if someone types in the old url of http://example.com/this-is-my-post they will automatically be redirect to http://example.com/news/this-is-my-post

I have successfully set up a redirect for my custom post types as I moved all the posts over from the custom post type "events" to "latest" by using this:

RewriteRule ^events/(.*) http://www.example.com/latest/$1 [R=301,L]
```

However I'm not sure I can use this to redirect the main blog posts without affecting the website pages.

答:
To omit the requests for events or latest, you must define an appropriate condition. The rule looks similar to the one you already have

```<code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/events/
RewriteCond %{REQUEST_URI} !^/latest/
RewriteCond %{REQUEST_URI} !^/news/
RewriteRule ^(.*)$ /news/$1 [R,L]
</code>```

You may also combine the three excluding conditions into one

```<code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/(events|latest|news)/
RewriteRule ^(.*)$ /news/$1 [R,L]
</code>```

When everything works as it should, you may replace R with R=301 (permanent redirect). Never test with R=301.

Body:
I have changed my permalink to the custom structure /news/%postname% however I am now trying to set up a 301 redirect so if someone types in the old url of http://example.com/this-is-my-post they will automatically be redirect to http://example.com/news/this-is-my-post

I have successfully set up a redirect for my custom post types as I moved all the posts over from the custom post type "events" to "latest" by using this:

RewriteRule ^events/(.*) http://www.example.com/latest/$1 [R=301,L]

However I'm not sure I can use this to redirect the main blog posts without affecting the website pages.

Body:
To omit the requests for events or latest, you must define an appropriate condition. The rule looks similar to the one you already have

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/events/
RewriteCond %{REQUEST_URI} !^/latest/
RewriteCond %{REQUEST_URI} !^/news/
RewriteRule ^(.*)$ /news/$1 [R,L]

You may also combine the three excluding conditions into one

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/(events|latest|news)/
RewriteRule ^(.*)$ /news/$1 [R,L]

When everything works as it should, you may replace R with R=301 (permanent redirect). Never test with R=301.


问:
Changing the request XML in Load Script
I have a soapui project for a big IT-System which offers hundreds of Webservice, only some of the webservice are in my project. Everytime I add a new WSDL to my project, I have to do a lot of monkey work to adjust the xml for the request (like adding placeholder for properties, removing comments, replace questionmarks....).

I thought I could easily write a "Load Script" for the project in which I register some Listener, and everytime a new request is added the script will fetch the xml-request from the new request-object, change it and save it back. But I failed, because I have no clue how to even get the xml from the request.

This is how far I got:

import com.eviware.soapui.SoapUI
import com.eviware.soapui.model.support.ProjectListenerAdapter
import com.eviware.soapui.model.support.InterfaceListenerAdapter
import com.eviware.soapui.model.iface.*
import com.eviware.soapui.impl.wsdl.WsdlRequest
import com.eviware.soapui.impl.wsdl.WsdlContentPart
import com.eviware.soapui.model.propertyexpansion.DefaultPropertyExpansionContext
import com.eviware.soapui.support.XmlHolder

final logger = log
SoapUI.log.info("Load Script executet")
for(Interface i : project.getInterfaceList()){
    i.addInterfaceListener(new RequestAddListener())
}

project.addProjectListener(new ProjectListenerAdapter(){
    public void interfaceAdded(Interface i){
        SoapUI.log.info("Interface added: "+ i.getName())
        i.addInterfaceListener(new RequestAddListener())
    }
})

public class RequestAddListener extends InterfaceListenerAdapter {
    public void requestAdded(Request r) {
        if(r instanceof WsdlRequest){
            WsdlRequest request = (WsdlRequest) r
            SoapUI.log.info("Request added: "+request.getName())
            // here i want to retrieve the xml-request from the request-object,
            // do something with it, and set it back to the request-object.
        }
    }
}
```

I looked in every property of the WsdlRequest-Instance and could not find any XML. I tried to create a context (load Script does not provide a context instance) and somehow get the XmlHolder from it, but failed (Unexpected element: CDATA). All examples I found, where run in a TestCase/Step and I was not able to transfer them to the Load Script of the project.

Can someone help me?

Edit:

I want to change the request-data of new request (4. in the picture) to the example above (3. in the picture). I thought, I could solve it by using the load script of the project (2. in the picture). My approach was to register a InterfaceListener in every Interface and react to the creation of new Requests (method requestAdded). This works, but I did not found a way to retrieve the request-data from the request-object.

答:
Because of the help and effort from Rao (thanks again) I did the following workaorund:

Register listener for new request in the load script

on request creation, write the interface- and the request-name as custom properties to the project (operation-name is in my case always the same)

the customazing is done with a special testcase which i run afterwards

The load script from the project:

import com.eviware.soapui.model.support.ProjectListenerAdapter
import com.eviware.soapui.model.support.InterfaceListenerAdapter
import com.eviware.soapui.model.iface.*
import com.eviware.soapui.model.project.Project
import com.eviware.soapui.impl.wsdl.WsdlRequest

// Request-Listener for all existing interfaces
for(Interface i : project.getInterfaceList()){
  i.addInterfaceListener(new RequestAddListener())
}

// this Project-Listener adds a Request-Listener to all new Interfaces
project.addProjectListener(new ProjectListenerAdapter(){
  public void interfaceAdded(Interface i){
    i.addInterfaceListener(new RequestAddListener())
  }
})

public class RequestAddListener extends InterfaceListenerAdapter {
  public void requestAdded(Request r) {
    if(r instanceof WsdlRequest){
      Operation o = r.getOperation()
      Interface i = o.getInterface()
      Project p = i.getProject()
      // save name of request and interface as project-property
      p.setPropertyValue("lastAddedRequest.Request", r.getName())
      p.setPropertyValue("lastAddedRequest.Interface", i.getName())
    }
  }
}
```

<p>The setup script of the empty testcase which I run manually after request creation:</p>

<pre class="lang-java prettyprint-override"><code>import com.eviware.soapui.model.iface.*
import com.eviware.soapui.model.testsuite.TestCase
import com.eviware.soapui.model.project.Project

def project = testCase.getProject()
def i = project.getInterfaceByName(project.getPropertyValue("lastAddedRequest.Interface"))
// in my case all operations are named execute
def request = i.getOperationByName("execute").getRequestByName(project.getPropertyValue("lastAddedRequest.Request"))
def requestData = request.getRequestContent()
// change the xml with some regexs

// put the xml back
request.setRequestContent(requestData)
project.setPropertyValue("lastAddedRequest.Interface", "")
project.setPropertyValue("lastAddedRequest.Request", "")
</code>```

Title: Changing the request XML in Load Script

Body:
I have a soapui project for a big IT-System which offers hundreds of Webservice, only some of the webservice are in my project. Everytime I add a new WSDL to my project, I have to do a lot of monkey work to adjust the xml for the request (like adding placeholder for properties, removing comments, replace questionmarks....).

I thought I could easily write a "Load Script" for the project in which I register some Listener, and everytime a new request is added the script will fetch the xml-request from the new request-object, change it and save it back. But I failed, because I have no clue how to even get the xml from the request.

This is how far I got:

import com.eviware.soapui.SoapUI
import com.eviware.soapui.model.support.ProjectListenerAdapter
import com.eviware.soapui.model.support.InterfaceListenerAdapter
import com.eviware.soapui.model.iface.*
import com.eviware.soapui.impl.wsdl.WsdlRequest
import com.eviware.soapui.impl.wsdl.WsdlContentPart
import com.eviware.soapui.model.propertyexpansion.DefaultPropertyExpansionContext
import com.eviware.soapui.support.XmlHolder

final logger = log
SoapUI.log.info("Load Script executet")
for(Interface i : project.getInterfaceList()){
    i.addInterfaceListener(new RequestAddListener())
}

project.addProjectListener(new ProjectListenerAdapter(){
    public void interfaceAdded(Interface i){
        SoapUI.log.info("Interface added: "+ i.getName())
        i.addInterfaceListener(new RequestAddListener())
    }
})

public class RequestAddListener extends InterfaceListenerAdapter {
    public void requestAdded(Request r) {
        if(r instanceof WsdlRequest){
            WsdlRequest request = (WsdlRequest) r
            SoapUI.log.info("Request added: "+request.getName())
            // here i want to retrieve the xml-request from the request-object,
            // do something with it, and set it back to the request-object.
        }
    }
}

I looked in every property of the WsdlRequest-Instance and could not find any XML. I tried to create a context (load Script does not provide a context instance) and somehow get the XmlHolder from it, but failed (Unexpected element: CDATA). All examples I found, where run in a TestCase/Step and I was not able to transfer them to the Load Script of the project.

Can someone help me?

Edit:

I want to change the request-data of new request (4. in the picture) to the example above (3. in the picture). I thought, I could solve it by using the load script of the project (2. in the picture). My approach was to register a InterfaceListener in every Interface and react to the creation of new Requests (method requestAdded). This works, but I did not found a way to retrieve the request-data from the request-object.

Body:
Because of the help and effort from Rao (thanks again) I did the following workaorund:

Register listener for new request in the load script

on request creation, write the interface- and the request-name as custom properties to the project (operation-name is in my case always the same)

the customazing is done with a special testcase which i run afterwards

The load script from the project:

import com.eviware.soapui.model.support.ProjectListenerAdapter
import com.eviware.soapui.model.support.InterfaceListenerAdapter
import com.eviware.soapui.model.iface.*
import com.eviware.soapui.model.project.Project
import com.eviware.soapui.impl.wsdl.WsdlRequest

// Request-Listener for all existing interfaces
for(Interface i : project.getInterfaceList()){
  i.addInterfaceListener(new RequestAddListener())
}

// this Project-Listener adds a Request-Listener to all new Interfaces
project.addProjectListener(new ProjectListenerAdapter(){
  public void interfaceAdded(Interface i){
    i.addInterfaceListener(new RequestAddListener())
  }
})

public class RequestAddListener extends InterfaceListenerAdapter {
  public void requestAdded(Request r) {
    if(r instanceof WsdlRequest){
      Operation o = r.getOperation()
      Interface i = o.getInterface()
      Project p = i.getProject()
      // save name of request and interface as project-property
      p.setPropertyValue("lastAddedRequest.Request", r.getName())
      p.setPropertyValue("lastAddedRequest.Interface", i.getName())
    }
  }
}

The setup script of the empty testcase which I run manually after request creation:

import com.eviware.soapui.model.iface.*
import com.eviware.soapui.model.testsuite.TestCase
import com.eviware.soapui.model.project.Project

def project = testCase.getProject()
def i = project.getInterfaceByName(project.getPropertyValue("lastAddedRequest.Interface"))
// in my case all operations are named execute
def request = i.getOperationByName("execute").getRequestByName(project.getPropertyValue("lastAddedRequest.Request"))
def requestData = request.getRequestContent()
// change the xml with some regexs

// put the xml back
request.setRequestContent(requestData)
project.setPropertyValue("lastAddedRequest.Interface", "")
project.setPropertyValue("lastAddedRequest.Request", "")


问:
Newbie stuck on a jQuery question...conditional statement
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

```<code><script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total') == 0) {
  $(span.fc_info).addClass('foo');
 };
});
</script>
</code>```

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

```<code><span class="fc_info">Info 1</span><br />
<span class="fc_cart_item_price_total">$0.00</span><br />
<span class="fc_info">Info 2</span>
</code>```

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

答:
For each cart item whose price is $0.00, this will add the "foo" class to the preceding (and only the preceding) fc_info.</p>

```<code>$(function() {
    $(".fc_cart_item_price_total:contains($0.00)").each(function(i, n) {
        (n=$(n)).prevAll(".fc_info:first").addClass("foo");
    });
});
</code>```

Body:
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

Info 1

$0.00

Info 2

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

Body:
For each cart item whose price is $0.00, this will add the "foo" class to the preceding (and only the preceding) fc_info.

$(function() {
    $(".fc_cart_item_price_total:contains($0.00)").each(function(i, n) {
        (n=$(n)).prevAll(".fc_info:first").addClass("foo");
    });
});


问:
Jest, Typescript, ts-jest: Coverage is slightly incorrect
I am wrtiting a project using TypeScript, Jest and the ts-jest NPM module.

When I run my test, I do get some amount of coverage, but the HTML report is not quite right:

Furthermore, some functions are being marked as untested even though they are certainly being called.

My package.json is set as follows:

```<code>{
    "jest": {
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js",
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.{ts,tsx}"
    ],
    "coverageReporters": [
      "html",
      "json"
    ]
  }
}
</code>```

Is something wrong with my configuration?

答:
UPDATE

Starting from jest@20 you can pass mapCoverage option and use coverage/lcov-report/index.html file.

OLD

I also have been struggling with this problem, but then I notice that line.

Long story short - coverage reports goes to coverage/remapped/html/index.html file.

Body:
I am wrtiting a project using TypeScript, Jest and the ts-jest NPM module.

When I run my test, I do get some amount of coverage, but the HTML report is not quite right:

Furthermore, some functions are being marked as untested even though they are certainly being called.

My package.json is set as follows:

{
    "jest": {
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js",
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.{ts,tsx}"
    ],
    "coverageReporters": [
      "html",
      "json"
    ]
  }
}

Is something wrong with my configuration?


问:
Issue with SetForegroundWindow in .NET
I'm using SetForegroundWindow API in .NET using PInvoke.

When I use the API while debugging in Visual Studio its works perfectly. But it doesn't work always when the application is running normally.

I put some logs just before a call to SetForegroundWindow and its confirmed that the API is getting called but doesn't take effect at times. I have also seen a couple of posts regarding this issue but I want to know why is it failing.

The links of the post are a follows:

Win32 SetForegroundWindow unreliable

SetForegroundWindow only working while visual studio is open

答:
The trick is to 'fool' windows (not trying to talk in pleonasms) and attach the input to the new thread to which the window-to-focus belongs, I took most of this from the pinvoke website but added a test to restore minimized windows:</p>

```<code>private const uint WS_MINIMIZE = 0x20000000;

private const uint SW_SHOW     = 0x05;
private const uint SW_MINIMIZE = 0x06;
private const uint SW_RESTORE  = 0x09;

public static void FocusWindow(IntPtr focusOnWindowHandle)
{
    int style = GetWindowLong(focusOnWindowHandle, GWL_STYLE);

    // Minimize and restore to be able to make it active.
    if ((style & WS_MINIMIZE) == WS_MINIMIZE)
    {
        ShowWindow(focusOnWindowHandle, SW_RESTORE);
    }

    uint currentlyFocusedWindowProcessId = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
    uint appThread = GetCurrentThreadId();

    if (currentlyFocusedWindowProcessId != appThread)
    {
        AttachThreadInput(currentlyFocusedWindowProcessId, appThread, true);
        BringWindowToTop(focusOnWindowHandle);
        ShowWindow(focusOnWindowHandle, SW_SHOW);
        AttachThreadInput(currentlyFocusedWindowProcessId, appThread, false);
    }

    else
    {
        BringWindowToTop(focusOnWindowHandle);
        ShowWindow(focusOnWindowHandle, SW_SHOW);
    }
}
</code>```

Title: Issue with SetForegroundWindow in .NET

Body:
The trick is to 'fool' windows (not trying to talk in pleonasms) and attach the input to the new thread to which the window-to-focus belongs, I took most of this from the pinvoke website but added a test to restore minimized windows:

private const uint WS_MINIMIZE = 0x20000000;

private const uint SW_SHOW     = 0x05;
private const uint SW_MINIMIZE = 0x06;
private const uint SW_RESTORE  = 0x09;

public static void FocusWindow(IntPtr focusOnWindowHandle)
{
    int style = GetWindowLong(focusOnWindowHandle, GWL_STYLE);

    // Minimize and restore to be able to make it active.
    if ((style & WS_MINIMIZE) == WS_MINIMIZE)
    {
        ShowWindow(focusOnWindowHandle, SW_RESTORE);
    }

    uint currentlyFocusedWindowProcessId = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
    uint appThread = GetCurrentThreadId();

    if (currentlyFocusedWindowProcessId != appThread)
    {
        AttachThreadInput(currentlyFocusedWindowProcessId, appThread, true);
        BringWindowToTop(focusOnWindowHandle);
        ShowWindow(focusOnWindowHandle, SW_SHOW);
        AttachThreadInput(currentlyFocusedWindowProcessId, appThread, false);
    }

    else
    {
        BringWindowToTop(focusOnWindowHandle);
        ShowWindow(focusOnWindowHandle, SW_SHOW);
    }
}


问:
Batch command to open files of the same name in Notepad++
I would like to open all files called "asdf.txt" in Notepad++, found in all subfolders from the directory that the batch file is located in.

The solution found here applies to file types but does not translate to exact file names:
Batch command to open all files of a certain type in Notepad++

Here is my attempt:

```<code>FOR /R %%a IN (asdf.txt) DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%%a"
</code>```

This results in Notepad++ stating that asdf.txt doesn't exist and would I like to create it. It continues to ask me for every subfolder that exists (which can be hundreds of times). If I say yes, then it creates the file asdf.txt in every subfolder. If I keep pressing yes/no, then it eventually does open the existing files. What I want, however, is to open all existing files with exactly the same name and not create new files.

答:
your filename doesn't contain any wildcard, so it's taken as a string, not a file mask.

Either add a wildcard:

```<code> FOR /R %%a IN ("asdf.txt?") DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%%a"
</code>```

or use:

```<code>FOR /F "delims=" %%a IN ('dir /s /b /a-d "asdf.txt"') DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%%a"
</code>```

Body:
I would like to open all files called "asdf.txt" in Notepad++, found in all subfolders from the directory that the batch file is located in.

The solution found here applies to file types but does not translate to exact file names:
Batch command to open all files of a certain type in Notepad++

Here is my attempt:

FOR /R %%a IN (asdf.txt) DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%%a"

This results in Notepad++ stating that asdf.txt doesn't exist and would I like to create it. It continues to ask me for every subfolder that exists (which can be hundreds of times). If I say yes, then it creates the file asdf.txt in every subfolder. If I keep pressing yes/no, then it eventually does open the existing files. What I want, however, is to open all existing files with exactly the same name and not create new files.

Body:
your filename doesn't contain any wildcard, so it's taken as a string, not a file mask.

Either add a wildcard:

 FOR /R %%a IN ("asdf.txt?") DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%%a"

or use:

FOR /F "delims=" %%a IN ('dir /s /b /a-d "asdf.txt"') DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%%a"


问:
extended algorithm implementation in matlab
i have  found following pseudo-code for extended euclidean algorithm

i implemented following algorithm

```<code>    function [x1,y1,d1]=extend_eucledian(a,b)
            if b==0
                x1=1;
                y1=0;
                d1=a;
                return;
            end

            [x1,y1,d1]=extend_eucledian(b,mod(a,b));

 x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;

        end
</code>```

when i run   following  this program, i got following  result

```<code>[x1,y1,d1]=extend_eucledian(23,20)

x1 =

     0

y1 =

     0

d1 =

     1
</code>```

i guess that  [x1,y1,d1] are not changing their values  during the iteration, for instance  , i have tried following code

```<code>    function [x1,y1,d1]=extend_eucledian(a,b)
            if b==0
                x1=1;
                y1=0;
                d1=a;
                return;
            else
                 x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;
            end

            [x1,y1,d1]=extend_eucledian(b,mod(a,b));

        end
</code>```

but i got

```<code>>> [x1,y1,d1]=extend_eucledian(23,20)
Undefined function or variable 'y1'.

Error in extend_eucledian (line 8)
                 x1=y1;
</code>```

how can i fix this  problem? where i am making mistake?

答:
The problem can be solved by introducing intermediate working variables, that will store the result of the recursive call:

```<code>function [x,y,d]=extended_euclid(a,b)
    if b==0
        x=1;
        y=0;
        d=a;
        return;
    end
    [x1,y1,d1]=extended_euclid(b,mod(a,b));

    x=y1;
    y=x1-floor(a/b)*y1;
    d=d1;

end
</code>```

This function works as expected:

```<code>>> [x, y, d] = extended_euclid(23,20)

x =
     7

y =
    -8

d =
     1

>> [x, y, d] = extended_euclid(25,20)

x =
     1

y =
    -1

d =
     5
</code>```

Body:
i have  found following pseudo-code for extended euclidean algorithm

i implemented following algorithm

    function [x1,y1,d1]=extend_eucledian(a,b)
            if b==0
                x1=1;
                y1=0;
                d1=a;
                return;
            end

            [x1,y1,d1]=extend_eucledian(b,mod(a,b));

 x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;

        end

when i run   following  this program, i got following  result

[x1,y1,d1]=extend_eucledian(23,20)

x1 =

     0

y1 =

     0

d1 =

     1

i guess that  [x1,y1,d1] are not changing their values  during the iteration, for instance  , i have tried following code

    function [x1,y1,d1]=extend_eucledian(a,b)
            if b==0
                x1=1;
                y1=0;
                d1=a;
                return;
            else
                 x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;
            end

            [x1,y1,d1]=extend_eucledian(b,mod(a,b));

        end

but i got

>> [x1,y1,d1]=extend_eucledian(23,20)
Undefined function or variable 'y1'.

Error in extend_eucledian (line 8)
                 x1=y1;

how can i fix this  problem? where i am making mistake?

Body:
The problem can be solved by introducing intermediate working variables, that will store the result of the recursive call:

function [x,y,d]=extended_euclid(a,b)
    if b==0
        x=1;
        y=0;
        d=a;
        return;
    end
    [x1,y1,d1]=extended_euclid(b,mod(a,b));

    x=y1;
    y=x1-floor(a/b)*y1;
    d=d1;

end

This function works as expected:

>> [x, y, d] = extended_euclid(23,20)

x =
     7

y =
    -8

d =
     1

>> [x, y, d] = extended_euclid(25,20)

x =
     1

y =
    -1

d =
     5


问:
How to create an executable program for windows through a PHP file?
Is it possible to convert a PHP PHAR file to an executable application?</p>

答:
There is multiple ways to do this :

.bat file that executes your PHAR file

OR

Write a program with a compiled language (C, C++ etc.) that executes your PHAR (via system commands) file and compile it


问:
How much space is required to install OpenCV on Raspberry Pi 3
I am new user to the Raspberry Pi 3.
How much space is required to install OpenCV on Raspberry?</p>

答:
Installing OpenCV on your Raspberry Pi can be done in two ways, both having different space requirements:

You can use the Debian repositories with the sudo apt-get install libopencv-dev command. This is the easiest way to install OpenCV on your Pi, and also takes the least amount of space (if that's a concern for you). It will take around 80M when installed. The downsides of this approach is that you get OpenCV 2.4.9., there isn't and upgrade to OpenCV 3.0 yet. Also you can't customize the installation.

The second and more difficult option is to compile the sources yourself. To compile the code you will need more than 4GB of disk space as the compiled code takes a lot more space. However the installed libraries (.lib) are under a 100M. If you want to use this option I recommend you to connect a USB stick or external HDD to your Pi. Use the USB or HDD (with more than 4GB of free space) to compile and build OpenCV. After installing OpenCV you can delete this directory again as you only need the library files (of course, this changes when you actually want to develop code on your Pi).


问:
Mamp Pro 4 HTTP and HTTPS
Is it not possible in Mamp Pro 4 to have both http and https? The application I am working on requires both depending on the page.

I must be missing something as it makes no sense when I enable SSL only https works and http then stops working.

I tried going through the http.conf, but really have no idea whats causing this.

I think it just generates the vhost for https only and then removes http. Doesn't even look like you can manually edit it.

Any suggestion would be great.

答:
I got a simple solution by edit template:

Open Mamp Pro

File > Edit Template > Apache > httpd-ssl.conf

Add these line after

<VirtualHost *:80>
    ServerName MAMP_SSLVirtualHost_ServerName_MAMP
    MAMP_SSLVirtualHost_ServerAdmin_MAMP
    MAMP_SSLVirtualHost_DirectoryIndex_MAMP
    DocumentRoot MAMP_SSLVirtualHost_DocumentRoot_MAMP
</VirtualHost>

Title: Mamp Pro 4 HTTP and HTTPS


问:
byte swapping and C++/C
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

```<code>int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}
</code>```

Best,
U.

答: This is the endian problem.  Intel CPU use little endian. The "network byte order" / SPARC / Motorola  use big endian.  Many legacy, portable application save files in big endian for interoperability.</p>

Title: byte swapping and C++/C

Body:
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}

Best,
U.


问:
How can I connect to a Bluetooth service on Gear S3?
I am writing a web app for the Gear S3 and a companion Win-App for UWP in C#.
What I want it to do: S3 acting as a BT server, sending data, and the Win-App as a client, which is supposed to receive the data.
In Tizen I used the registerRfcommServiceByUUID() function as below:

```<code>function publishTransferService() {

if(remoteDevice.isConnented){
    console.log("Connection Status: " + remoteDevice.isConnected);
    var TRANS_SERVICE_UUID = '5BCE9431-6C75-32AB-AFE0-2EC108A30860';
    adapter.registerRFCOMMServiceByUUID(TRANS_SERVICE_UUID, 'My Service', ServiceSuccessCb,
            function(e) {
        console.log( "Could not register service record, Error: " + e.message);
    });
}else{
    console.error("Connection Status: " + remoteDevice.isConnected);
    }
</code>```

In C# i try to connect to the service as follows:

```<code>        //to ulong converted MAC-Address of the Gear
        ulong gearBtAddress = 145914022804881;
        //create device-instance of the gear
        BluetoothDevice gearDevice = await  BluetoothDevice.FromBluetoothAddressAsync(gearBtAddress);
        //list the services found on the gear and connect to the one with
        //the same uuid as in tizen
        var gearServices = await gearDevice.GetRfcommServicesAsync();
        foreach (var service in gearServices.Services)
        {
            if(service.ServiceId == RfcommServiceId.FromUuid(Guid.Parse("5BCE9431-6C75-32AB-AFE0-2EC108A30860")))
            {
                _service = await RfcommDeviceService.FromIdAsync(service.ToString());
            }

        }
</code>```

The Problem I am facing is, that the C# won't find the wanted Uuid, although it finds several other uuids. I don't see where it gets lost?

Thanks in advance.

答:
I solved it myself, the problem was, that the UUID was uncached. Adding the following was all to do:</p>

```<code>        var cacheMode = BluetoothCacheMode.Uncached;
        var gearServices = await gearDevice.GetRfcommServicesAsync(cacheMode);
</code>```

Body:
I am writing a web app for the Gear S3 and a companion Win-App for UWP in C#.
What I want it to do: S3 acting as a BT server, sending data, and the Win-App as a client, which is supposed to receive the data.
In Tizen I used the registerRfcommServiceByUUID() function as below:

function publishTransferService() {

if(remoteDevice.isConnented){
    console.log("Connection Status: " + remoteDevice.isConnected);
    var TRANS_SERVICE_UUID = '5BCE9431-6C75-32AB-AFE0-2EC108A30860';
    adapter.registerRFCOMMServiceByUUID(TRANS_SERVICE_UUID, 'My Service', ServiceSuccessCb,
            function(e) {
        console.log( "Could not register service record, Error: " + e.message);
    });
}else{
    console.error("Connection Status: " + remoteDevice.isConnected);
    }

In C# i try to connect to the service as follows:

        //to ulong converted MAC-Address of the Gear
        ulong gearBtAddress = 145914022804881;
        //create device-instance of the gear
        BluetoothDevice gearDevice = await  BluetoothDevice.FromBluetoothAddressAsync(gearBtAddress);
        //list the services found on the gear and connect to the one with
        //the same uuid as in tizen
        var gearServices = await gearDevice.GetRfcommServicesAsync();
        foreach (var service in gearServices.Services)
        {
            if(service.ServiceId == RfcommServiceId.FromUuid(Guid.Parse("5BCE9431-6C75-32AB-AFE0-2EC108A30860")))
            {
                _service = await RfcommDeviceService.FromIdAsync(service.ToString());
            }

        }

The Problem I am facing is, that the C# won't find the wanted Uuid, although it finds several other uuids. I don't see where it gets lost?

Thanks in advance.

Body:
I solved it myself, the problem was, that the UUID was uncached. Adding the following was all to do:

        var cacheMode = BluetoothCacheMode.Uncached;
        var gearServices = await gearDevice.GetRfcommServicesAsync(cacheMode);


问:
Upload an image (Base64) using Alamofire Swift 3
Iam trying to upload 2 images to server with JSON request using alamofire

and here's my code :

```<code>   let parameters = ["CreditCardImage":CreditCardImage,"CreditCardBackImage":CreditCardBackImage , "CustomerID" : CustomerID]

            let headers: HTTPHeaders = [
                "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
                "Accept": "application/json"
            ]

   Alamofire.request("MY URL", method : .post , parameters : parameters, encoding: JSONEncoding.default ,  headers: headers).responseJSON { response in

        // get json Response

        let json = JSON(response.result.value)

        print(json)

   }
</code>```

When i print the response iam getting message <<  unknown  >> in the console

and i tried that in postman it's not working too what's wrong with that ? any help ?

答:
You can try this</p>

```<code>let image = UIImage.init(named: "myImage")
 let imgData = UIImageJPEGRepresentation(image!, 0.2)!

 let parameters = ["name": rname]

Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
    },
to:"mysite/upload.php")
{ (result) in
    switch result {
    case .success(let upload, _, _):

        upload.uploadProgress(closure: { (progress) in
            print("Upload Progress: \(progress.fractionCompleted)")
        })

        upload.responseJSON { response in
             print(response.result.value)
        }

    case .failure(let encodingError):
        print(encodingError)
    }
}
</code>```

Body:
Iam trying to upload 2 images to server with JSON request using alamofire

and here's my code :

   let parameters = ["CreditCardImage":CreditCardImage,"CreditCardBackImage":CreditCardBackImage , "CustomerID" : CustomerID]

            let headers: HTTPHeaders = [
                "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
                "Accept": "application/json"
            ]

   Alamofire.request("MY URL", method : .post , parameters : parameters, encoding: JSONEncoding.default ,  headers: headers).responseJSON { response in

        // get json Response

        let json = JSON(response.result.value)

        print(json)

   }

When i print the response iam getting message <<  unknown  >> in the console

and i tried that in postman it's not working too what's wrong with that ? any help ?

Body:
You can try this

let image = UIImage.init(named: "myImage")
 let imgData = UIImageJPEGRepresentation(image!, 0.2)!

 let parameters = ["name": rname]

Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
    },
to:"mysite/upload.php")
{ (result) in
    switch result {
    case .success(let upload, _, _):

        upload.uploadProgress(closure: { (progress) in
            print("Upload Progress: \(progress.fractionCompleted)")
        })

        upload.responseJSON { response in
             print(response.result.value)
        }

    case .failure(let encodingError):
        print(encodingError)
    }
}