问:
Iterator and printing details
Hey all. I've been asked to create a method that uses an iterator to print details of 'lots'. I'm able to create an iterator that prints all of the details, however, for any lots that haven't been bought, a message should print out this fact and I'm unsure how I can add that code in. It is the public void close method I'm focusing on. This is what I have so far. Help is greatly appreciated.</p>

```<code>public class Auction{

    // The list of Lots in this auction.
    private final ArrayList<Lot> lots;
    // The number that will be given to the next lot entered
    // into this auction.
    private int nextLotNumber;

    /**
     * Create a new auction.
     */
    public Auction(){
        lots = new ArrayList<Lot>();
        nextLotNumber = 1;
    }

    /**
     * Enter a new lot into the auction.
     *
     * @param description
     *            A description of the lot.
     */
    public void enterLot(final String description){
        lots.add(new Lot(nextLotNumber, description));
        nextLotNumber++;
    }

    /**
     * Show the full list of lots in this auction.
     */
    public void showLots(){
        for(final Lot lot : lots){
            System.out.println(lot.toString());
        }
    }

    public void close(){
        final Iterator<Lot> it = lots.iterator();
        while(it.hasNext()){

        }
    }

    /**
     * Bid for a lot. A message indicating whether the bid is
     * successful or not is printed.
     *
     * @param number
     *            The lot number being bid for.
     * @param bidder
     *            The person bidding for the lot.
     * @param value
     *            The value of the bid.
     */
    public void bidFor(final int lotNumber,
        final Person bidder,
        final long value){
        final Lot selectedLot = getLot(lotNumber);
        if(selectedLot != null){
            final boolean successful =
                selectedLot.bidFor(new Bid(bidder, value));
            if(successful){
                System.out.println("The bid for lot number " + lotNumber
                    + " was successful.");
            } else{
                // Report which bid is higher.
                final Bid highestBid = selectedLot.getHighestBid();
                System.out.println("Lot number: " + lotNumber
                    + " already has a bid of: " + highestBid.getValue());
            }
        }
    }

}
</code>```

答:
Add an attribute to the Lot class of type Person called "winner" or something similar.

In the bidFor method, in the if (successful) block, set the winner attribute:

```<code>selectedLot.setWinner(bidder);
</code>```

Then when iterating through the lots, if the winner attribute is null, print your message that the lot hasn't been bought.

Or you could use:

```<code>if (lot.getHighestBid() == null)
</code>```

depending on how the Lot class is implemented, hard to know without seeing the Lot class.

Title: Iterator and printing details

Body:
Hey all. I've been asked to create a method that uses an iterator to print details of 'lots'. I'm able to create an iterator that prints all of the details, however, for any lots that haven't been bought, a message should print out this fact and I'm unsure how I can add that code in. It is the public void close method I'm focusing on. This is what I have so far. Help is greatly appreciated.

public class Auction{

    // The list of Lots in this auction.
    private final ArrayList<Lot> lots;
    // The number that will be given to the next lot entered
    // into this auction.
    private int nextLotNumber;

    /**
     * Create a new auction.
     */
    public Auction(){
        lots = new ArrayList<Lot>();
        nextLotNumber = 1;
    }

    /**
     * Enter a new lot into the auction.
     *
     * @param description
     *            A description of the lot.
     */
    public void enterLot(final String description){
        lots.add(new Lot(nextLotNumber, description));
        nextLotNumber++;
    }

    /**
     * Show the full list of lots in this auction.
     */
    public void showLots(){
        for(final Lot lot : lots){
            System.out.println(lot.toString());
        }
    }

    public void close(){
        final Iterator<Lot> it = lots.iterator();
        while(it.hasNext()){

        }
    }

    /**
     * Bid for a lot. A message indicating whether the bid is
     * successful or not is printed.
     *
     * @param number
     *            The lot number being bid for.
     * @param bidder
     *            The person bidding for the lot.
     * @param value
     *            The value of the bid.
     */
    public void bidFor(final int lotNumber,
        final Person bidder,
        final long value){
        final Lot selectedLot = getLot(lotNumber);
        if(selectedLot != null){
            final boolean successful =
                selectedLot.bidFor(new Bid(bidder, value));
            if(successful){
                System.out.println("The bid for lot number " + lotNumber
                    + " was successful.");
            } else{
                // Report which bid is higher.
                final Bid highestBid = selectedLot.getHighestBid();
                System.out.println("Lot number: " + lotNumber
                    + " already has a bid of: " + highestBid.getValue());
            }
        }
    }

}

Body:
Add an attribute to the Lot class of type Person called "winner" or something similar.

In the bidFor method, in the if (successful) block, set the winner attribute:

selectedLot.setWinner(bidder);

Then when iterating through the lots, if the winner attribute is null, print your message that the lot hasn't been bought.

Or you could use:

if (lot.getHighestBid() == null)

depending on how the Lot class is implemented, hard to know without seeing the Lot class.


来源: stackexchange

问:
How to get substring out of String in java?
i am getting this String input="One Two Three";
how to get substrings out of it?
I want to get optimized solutions.
help me!</p>

答:
This should do the job:</p>

```<code>String substrings[] = input.split(" ");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This should do the job:

String substrings[] = input.split(" ");


问:
How to create Dropdown list in excel using php
I need to create a drop down list in excel using php. Actually i need to restrict user's input to given value by me. have a look on the image.
I have generated excel file successfully, but not able to create drop downlist. No help from googling :)please have a look on image. Thanks in advance

答:
If you are using PHPEXCEL API to generate the excel sheet then you can use this:

```<code>$objPHPExcel->getActiveSheet()->setAutoFilter('A1:I20');
</code>```

or this:

```<code>$objPHPExcel->getActiveSheet()->setAutoFilter(
    $objPHPExcel->getActiveSheet()->calculateWorksheetDimension()
);
</code>```

Body:
If you are using PHPEXCEL API to generate the excel sheet then you can use this:

$objPHPExcel->getActiveSheet()->setAutoFilter('A1:I20');

or this:

$objPHPExcel->getActiveSheet()->setAutoFilter(
    $objPHPExcel->getActiveSheet()->calculateWorksheetDimension()
);

ContentLicense: CC BY-SA 4.0


问:
Spring Data JPA - "No Property Found for Type" Exception
Well, I searched Google and found many results, but none of them was able to answer my problem. So, here it goes.

I am trying to study Spring MVC and Spring Data JPA by doing a minimal implementation of pinterest clone. So, following is the parts of code which I think is relevant to my problem.

Models/Entities

```<code>@Entity
@Table(name = "pin_item")
public class PinItem implements Serializable {
    // properties ...
    @JoinColumn(name = "board_id", referencedColumnName = "user_board_id")
    @ManyToOne(optional = false)
    private UserBoard board;

    // getters and setters...
}

@Entity
@Table(name = "user_board")
public class UserBoard implements Serializable {
    // properties ...
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "board")
    private List<PinItem> pinItemList;

    // getters and setters...
}
</code>```

Service

```<code>@Service
@Transactional(readOnly = true)
public class BoardServiceImpl implements BoardService {
    @Autowired
    private UserBoardRepository boardRepository;

    @Override
    public List<UserBoard> findLatestBoards() {
        PageRequest request = new PageRequest(
                     0, PresentationUtil.PAGE_SIZE,
                     Sort.Direction.DESC, "boardId"
        );
        return boardRepository.findAll(request).getContent();
    }

    // Other Methods
}
</code>```

Repository

```<code>public interface UserBoardRepository extends JpaRepository<UserBoard, Integer> {

}
</code>```

Now, when I call the findLatestBoards method in BoardService, "No Property Found" exception is thrown on the line return boardRepository.findAll(request).getContent();. Here is the excerpt from tomcat log.

DEBUG LOG

```<code>12:28:44,254 DEBUG AnnotationTransactionAttributeSource:106 - Adding transactional method 'findLatestBoards' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,254 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'transactionManager'
12:28:44,254 DEBUG JpaTransactionManager:366 - Creating new transaction with name [com.tecnooc.picpin.service.impl.BoardServiceImpl.findLatestBoards]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,254 DEBUG JpaTransactionManager:369 - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] for JPA transaction
12:28:44,255 DEBUG AbstractTransactionImpl:158 - begin
12:28:44,255 DEBUG LogicalConnectionImpl:212 - Obtaining JDBC connection
12:28:44,255 DEBUG DriverManagerDataSource:162 - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/pic_pin]
12:28:44,266 DEBUG LogicalConnectionImpl:218 - Obtained JDBC connection
12:28:44,267 DEBUG JdbcTransaction:69 - initial autocommit status: true
12:28:44,267 DEBUG JdbcTransaction:71 - disabling autocommit
12:28:44,267 DEBUG JpaTransactionManager:401 - Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@370da60e]
12:28:44,274 DEBUG TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:286 - Adding transactional method 'findAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,274 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'transactionManager'
12:28:44,274 DEBUG JpaTransactionManager:332 - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] for JPA transaction
12:28:44,274 DEBUG JpaTransactionManager:471 - Participating in existing transaction
12:28:44,279 DEBUG CachedIntrospectionResults:159 - Not strongly caching class [java.io.Serializable] because it is not cache-safe
12:28:44,281 DEBUG JpaTransactionManager:851 - Participating transaction failed - marking existing transaction as rollback-only
12:28:44,281 DEBUG JpaTransactionManager:559 - Setting JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] rollback-only
12:28:44,283 DEBUG JpaTransactionManager:844 - Initiating transaction rollback
12:28:44,284 DEBUG JpaTransactionManager:534 - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194]
12:28:44,284 DEBUG AbstractTransactionImpl:203 - rolling back
12:28:44,284 DEBUG JdbcTransaction:164 - rolled JDBC Connection
12:28:44,285 DEBUG JdbcTransaction:126 - re-enabling autocommit
12:28:44,285 DEBUG JpaTransactionManager:594 - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] after transaction
12:28:44,285 DEBUG EntityManagerFactoryUtils:338 - Closing JPA EntityManager
12:28:44,286 DEBUG LogicalConnectionImpl:232 - Releasing JDBC connection
12:28:44,286 DEBUG LogicalConnectionImpl:250 - Released JDBC connection
12:28:44,287 DEBUG ExceptionHandlerExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,289 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,290 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,291 DEBUG DispatcherServlet:959 - Could not complete request
</code>```

Exception

The exception is "org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard". But, if I understood correctly, the property board is present in PinItem and is correctly mapped with mappedBy = "board" in UserBoard.

```<code>org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:353)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:271)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:245)
    at org.springframework.data.jpa.repository.query.QueryUtils.toJpaOrder(QueryUtils.java:408)
    at org.springframework.data.jpa.repository.query.QueryUtils.toOrders(QueryUtils.java:372)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:456)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:437)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:319)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:289)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:333)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:318)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy147.findAll(Unknown Source)
    at com.tecnooc.picpin.service.impl.BoardServiceImpl.findLatestBoards(BoardServiceImpl.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy148.findLatestBoards(Unknown Source)
    at com.tecnooc.picpin.controller.BoardController.latest(BoardController.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
</code>```

I don't get why this exception is thrown. Any idea why it is happening?

Note: I am using Hibernate as Persistence provider. Also, the code portion I put here is what I thought is relevant to the problem. If it is not, let me know and I will update the question with required portion.

答:
Fixed, While using CrudRepository of Spring , we have to append the propertyname correctly after findBy otherwise it will give you exception
"No Property Found for Type”

I was getting this exception as. because property name and method name were not in sync.

I have used below code for DB Access.

```<code>public interface UserDao extends CrudRepository<User, Long> {
    User findByUsername(String username);
</code>```

and my Domain User has property.

```<code>@Entity
public class User implements UserDetails {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "userId", nullable = false, updatable = false)
    private Long userId;
    private String username;
</code>```

Body:
Well, I searched Google and found many results, but none of them was able to answer my problem. So, here it goes.

I am trying to study Spring MVC and Spring Data JPA by doing a minimal implementation of pinterest clone. So, following is the parts of code which I think is relevant to my problem.

Models/Entities

@Entity
@Table(name = "pin_item")
public class PinItem implements Serializable {
    // properties ...
    @JoinColumn(name = "board_id", referencedColumnName = "user_board_id")
    @ManyToOne(optional = false)
    private UserBoard board;

    // getters and setters...
}

@Entity
@Table(name = "user_board")
public class UserBoard implements Serializable {
    // properties ...
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "board")
    private List<PinItem> pinItemList;

    // getters and setters...
}

Service

@Service
@Transactional(readOnly = true)
public class BoardServiceImpl implements BoardService {
    @Autowired
    private UserBoardRepository boardRepository;

    @Override
    public List<UserBoard> findLatestBoards() {
        PageRequest request = new PageRequest(
                     0, PresentationUtil.PAGE_SIZE,
                     Sort.Direction.DESC, "boardId"
        );
        return boardRepository.findAll(request).getContent();
    }

    // Other Methods
}

Repository

public interface UserBoardRepository extends JpaRepository<UserBoard, Integer> {

}

Now, when I call the findLatestBoards method in BoardService, "No Property Found" exception is thrown on the line return boardRepository.findAll(request).getContent();. Here is the excerpt from tomcat log.

DEBUG LOG

12:28:44,254 DEBUG AnnotationTransactionAttributeSource:106 - Adding transactional method 'findLatestBoards' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,254 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'transactionManager'
12:28:44,254 DEBUG JpaTransactionManager:366 - Creating new transaction with name [com.tecnooc.picpin.service.impl.BoardServiceImpl.findLatestBoards]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,254 DEBUG JpaTransactionManager:369 - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] for JPA transaction
12:28:44,255 DEBUG AbstractTransactionImpl:158 - begin
12:28:44,255 DEBUG LogicalConnectionImpl:212 - Obtaining JDBC connection
12:28:44,255 DEBUG DriverManagerDataSource:162 - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/pic_pin]
12:28:44,266 DEBUG LogicalConnectionImpl:218 - Obtained JDBC connection
12:28:44,267 DEBUG JdbcTransaction:69 - initial autocommit status: true
12:28:44,267 DEBUG JdbcTransaction:71 - disabling autocommit
12:28:44,267 DEBUG JpaTransactionManager:401 - Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@370da60e]
12:28:44,274 DEBUG TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:286 - Adding transactional method 'findAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,274 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'transactionManager'
12:28:44,274 DEBUG JpaTransactionManager:332 - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] for JPA transaction
12:28:44,274 DEBUG JpaTransactionManager:471 - Participating in existing transaction
12:28:44,279 DEBUG CachedIntrospectionResults:159 - Not strongly caching class [java.io.Serializable] because it is not cache-safe
12:28:44,281 DEBUG JpaTransactionManager:851 - Participating transaction failed - marking existing transaction as rollback-only
12:28:44,281 DEBUG JpaTransactionManager:559 - Setting JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] rollback-only
12:28:44,283 DEBUG JpaTransactionManager:844 - Initiating transaction rollback
12:28:44,284 DEBUG JpaTransactionManager:534 - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194]
12:28:44,284 DEBUG AbstractTransactionImpl:203 - rolling back
12:28:44,284 DEBUG JdbcTransaction:164 - rolled JDBC Connection
12:28:44,285 DEBUG JdbcTransaction:126 - re-enabling autocommit
12:28:44,285 DEBUG JpaTransactionManager:594 - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] after transaction
12:28:44,285 DEBUG EntityManagerFactoryUtils:338 - Closing JPA EntityManager
12:28:44,286 DEBUG LogicalConnectionImpl:232 - Releasing JDBC connection
12:28:44,286 DEBUG LogicalConnectionImpl:250 - Released JDBC connection
12:28:44,287 DEBUG ExceptionHandlerExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,289 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,290 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,291 DEBUG DispatcherServlet:959 - Could not complete request

Exception

The exception is "org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard". But, if I understood correctly, the property board is present in PinItem and is correctly mapped with mappedBy = "board" in UserBoard.

org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:353)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:271)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:245)
    at org.springframework.data.jpa.repository.query.QueryUtils.toJpaOrder(QueryUtils.java:408)
    at org.springframework.data.jpa.repository.query.QueryUtils.toOrders(QueryUtils.java:372)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:456)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:437)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:319)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:289)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:333)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:318)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy147.findAll(Unknown Source)
    at com.tecnooc.picpin.service.impl.BoardServiceImpl.findLatestBoards(BoardServiceImpl.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy148.findLatestBoards(Unknown Source)
    at com.tecnooc.picpin.controller.BoardController.latest(BoardController.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

I don't get why this exception is thrown. Any idea why it is happening?

Note: I am using Hibernate as Persistence provider. Also, the code portion I put here is what I thought is relevant to the problem. If it is not, let me know and I will update the question with required portion.

Body:
Fixed, While using CrudRepository of Spring , we have to append the propertyname correctly after findBy otherwise it will give you exception
"No Property Found for Type”

I was getting this exception as. because property name and method name were not in sync.

I have used below code for DB Access.

public interface UserDao extends CrudRepository<User, Long> {
    User findByUsername(String username);

and my Domain User has property.

@Entity
public class User implements UserDetails {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "userId", nullable = false, updatable = false)
    private Long userId;
    private String username;


问:
Extract image sequence with only 1 color chanel out of rgb avi movie with VirtualDub
I have an uncompressed RGB AVI file which containes 10 greyscale images: https://drive.google.com/open?id=0B9wKP6yNcpyfY1JzdmJTcHhjTmM (10 images)

With VirtualDub I would like to extract the images whicht should have only 1 channel. I all cases that I tried the images have always 3 channels.

How can that be done?

答:
If you need to do this often your option is "export via external encoder" with VirtualDub FilterMod https://sourceforge.net/projects/vdfiltermod
(rgb export was not possible with official VirtualDub)

the preset below will save gray tiff sequence using ffmpeg (download ffmpeg.exe and replace path to it)

```

{
    "description": "VirtualDub external encoder profile collection",
    "externalEncoders": {
        "sets": {
            "tiff_gray": {
                "videoEncoder": "tiff_gray",
                "audioEncoder": "",
                "multiplexer": "",
                "description": "",
                "extension": "",
                "processPartial": false,
                "useOutputAsTemp": true
            }
        },
        "profiles": {
            "tiff_gray": {
                "name": "tiff_gray",
                "program": "E:\\download\\vd\\ffmpeg\\ffmpeg.exe",
                "commandArguments": "-f rawvideo -pix_fmt %(pix_fmt) -s %(width)x%(height) -r %(fpsnum)/%(fpsden) -i - -pix_fmt gray8 %(tempvideofile)_%%04d.tif",
                "outputFilename": "",
                "type": 0,
                "pixelFormat": "bgra",
                "inputFormat": 0,
                "checkReturnCode": true,
                "logStdout": true,
                "logStderr": true,
                "bypassCompression": false,
                "predeleteOutputFile": true
            }
        }
    }
}

```

Body:
If you need to do this often your option is "export via external encoder" with VirtualDub FilterMod https://sourceforge.net/projects/vdfiltermod
(rgb export was not possible with official VirtualDub)

the preset below will save gray tiff sequence using ffmpeg (download ffmpeg.exe and replace path to it)

{
    "description": "VirtualDub external encoder profile collection",
    "externalEncoders": {
        "sets": {
            "tiff_gray": {
                "videoEncoder": "tiff_gray",
                "audioEncoder": "",
                "multiplexer": "",
                "description": "",
                "extension": "",
                "processPartial": false,
                "useOutputAsTemp": true
            }
        },
        "profiles": {
            "tiff_gray": {
                "name": "tiff_gray",
                "program": "E:\\download\\vd\\ffmpeg\\ffmpeg.exe",
                "commandArguments": "-f rawvideo -pix_fmt %(pix_fmt) -s %(width)x%(height) -r %(fpsnum)/%(fpsden) -i - -pix_fmt gray8 %(tempvideofile)_%%04d.tif",
                "outputFilename": "",
                "type": 0,
                "pixelFormat": "bgra",
                "inputFormat": 0,
                "checkReturnCode": true,
                "logStdout": true,
                "logStderr": true,
                "bypassCompression": false,
                "predeleteOutputFile": true
            }
        }
    }
}


答: Just use a String Tokenizer or, if you know where the substrings are, use .substring(int start,int end).

Title: How to get substring out of String in java?

Body:
i am getting this String input="One Two Three";
how to get substrings out of it?
I want to get optimized solutions.
help me!


问:
How can I programmatically change the background in Mac OS X?
How would I go about programmatically changing the desktop background in Mac OS X?  I'd like to use python, but I'm interested in any way possible.  Could I hook up to Terminal and call a certain command?</p>

答: You could also use py-appscript instead of Popening osascript or use ScriptingBridge with pyobjc which is included in 10.5 but a bit more cumbersome to use.</p>

OwnerDisplayName: stalepretzel

ContentLicense: CC BY-SA 2.5


问:
Java 8 Streams - Grouping into Single value
I am currently working with a List<Map<String, Object>> where I am trying to group across various keys within the map.
This seems to work nicely using the Java 8 Streams:

```<code>Map<Object, Map<Object, List<Map<String, Object>>>> collect =
   list
   .stream()
   .collect(Collectors.groupingBy(
       item -> item.get("key1"),
       Collectors.groupingBy(item -> item.get("key2"))
   ));
</code>```

As expected this give me a Map<Object, Map<Object, List<Map<String, Object>>>> which works well where the possible grouped results are greater than 1.

I have various examples where the grouping being done will always result in a single item in the lowest level list, for example.

List of Rows

```<code>{
  [reference="PersonX", firstname="Person", dob="test", lastname="x"],
  [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]
}
</code>```

Grouped by reference

Currently - grouped into a list with 1 Map<String,Object>

```<code>[PersonX, { [reference="PersonX", firstname="Person", dob="test", lastname="x"]}],
[JohnBartlett, { [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]}]
</code>```

Preference - No List just a single Map<String,Object>

```<code>[PersonX, [reference="PersonX", firstname="Person", dob="test", lastname="x"]],
[JohnBartlett, [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]]
</code>```

is there a way within the streams to force the output for these instances to be Map<Object, Map<Object, Map<String, Object>>> - so a single Map<String,Object> rather than a List of them?

Any help would be greatly appreciated.

答:
If I understood correctly, then for the cases where you are sure that there is a single item, you should just replace:

```<code> .collect(Collectors.groupingBy(
   item -> item.get("key1"),
   Collectors.toMap(item -> item.get("key2"), Function.identity())
 ));
</code>```

You can even provide a third argument as a BinaryOperator to merge your same entries (in case you need to)

Body:
I am currently working with a List<Map<String, Object>> where I am trying to group across various keys within the map.
This seems to work nicely using the Java 8 Streams:

Map<Object, Map<Object, List<Map<String, Object>>>> collect =
   list
   .stream()
   .collect(Collectors.groupingBy(
       item -> item.get("key1"),
       Collectors.groupingBy(item -> item.get("key2"))
   ));

As expected this give me a Map<Object, Map<Object, List<Map<String, Object>>>> which works well where the possible grouped results are greater than 1.

I have various examples where the grouping being done will always result in a single item in the lowest level list, for example.

List of Rows

{
  [reference="PersonX", firstname="Person", dob="test", lastname="x"],
  [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]
}

Grouped by reference

Currently - grouped into a list with 1 Map<String,Object>

[PersonX, { [reference="PersonX", firstname="Person", dob="test", lastname="x"]}],
[JohnBartlett, { [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]}]

Preference - No List just a single Map<String,Object>

[PersonX, [reference="PersonX", firstname="Person", dob="test", lastname="x"]],
[JohnBartlett, [reference="JohnBartlett", firstname="John", dob="test", lastname="Bartlett"]]

is there a way within the streams to force the output for these instances to be Map<Object, Map<Object, Map<String, Object>>> - so a single Map<String,Object> rather than a List of them?

Any help would be greatly appreciated.

Body:
If I understood correctly, then for the cases where you are sure that there is a single item, you should just replace:

 .collect(Collectors.groupingBy(
   item -> item.get("key1"),
   Collectors.toMap(item -> item.get("key2"), Function.identity())
 ));

You can even provide a third argument as a BinaryOperator to merge your same entries (in case you need to)


问:
move elements in a twig form depending on your needs - Symfony 3
I have a rendered form in my view which I need to shape regarding the mock-up.

and this is the mock up I shall follow (this is on a mobile device)

this is the actual layout I have in my view

and this is the code in my view so far

```<code><section class="restaurant__nav col-xs-offset-1 col-xs-10 col-md-offset-0 col-md-3 well">
    <div class="container">
        {{ form_start(form) }}
            {{ form_widget(form) }}
            {% if app.user %}
                <input type="submit" value="{{ 'buy.field' |trans |upper }}">
            {% else %}
                {{ 'not_connected.text' |trans }}
            {% endif %}
        {{ form_end(form) }}
    </div>
</section>
</code>```

So I'm really not good with sass (as i'm using it) and css either. But I tried to margin each element but I find it struggling a little.

Any good advice or method to actually do like my mockup without using too much pixels or avoiding that kind of things -> margin-left: 20px?

(just ignore the RÉSERVER I really try to put my form in the middle and element to equal sizing)

thank you

答:
So first of all, if you didn't notice you are using Bootstrap.
It means that to align in left side and in the middle your two main block, you can use class like : "col-md-*". It's the grid concept of bootstrap, basic.
Here is a reference : w3schools

Once block are correctly placed, you have to make the button and input together. Commonly called "input-group". You can implement this by many way, here is a reference : getbootstrap.com

Then for your button, you have some good examples again on w3schools

Once that's done, you may'd like to know that you can center element with :

```<code>display: block; // if element isn't natively block
margin: auto;
</code>```

To know what html element is considered by css as Block or Inline elements, again another reference : w3schools

To end this, you'd probably like to fix the width of the label and input as the same value.

I made you more than an example, my bad, but here it is :
JsFiddle

Body:
I have a rendered form in my view which I need to shape regarding the mock-up.

and this is the mock up I shall follow (this is on a mobile device)

this is the actual layout I have in my view

and this is the code in my view so far

        {{ form_start(form) }}
            {{ form_widget(form) }}
            {% if app.user %}
                <input type="submit" value="{{ 'buy.field' |trans |upper }}">
            {% else %}
                {{ 'not_connected.text' |trans }}
            {% endif %}
        {{ form_end(form) }}

So I'm really not good with sass (as i'm using it) and css either. But I tried to margin each element but I find it struggling a little.

Any good advice or method to actually do like my mockup without using too much pixels or avoiding that kind of things -> margin-left: 20px?

(just ignore the RÉSERVER I really try to put my form in the middle and element to equal sizing)

thank you

Body:
So first of all, if you didn't notice you are using Bootstrap.
It means that to align in left side and in the middle your two main block, you can use class like : "col-md-*". It's the grid concept of bootstrap, basic.
Here is a reference : w3schools

Once block are correctly placed, you have to make the button and input together. Commonly called "input-group". You can implement this by many way, here is a reference : getbootstrap.com

Then for your button, you have some good examples again on w3schools

Once that's done, you may'd like to know that you can center element with :

display: block; // if element isn't natively block
margin: auto;

To know what html element is considered by css as Block or Inline elements, again another reference : w3schools

To end this, you'd probably like to fix the width of the label and input as the same value.

I made you more than an example, my bad, but here it is :
JsFiddle


问:
Control FPS of Kinect v2
I want to control FPS rate of Microsoft Kinect v2 , For example if image processing computation taking more time then FPs rate will slow and if image processing computation taking less time then Fps rate will fast.</p>

答:
You can't.

The best you can do is to acquire at the maximum fps (30 or 15 according to the light for color camera) and then discard frames if the processing is not finished.

Alex

Title: Control FPS of Kinect v2


问:
How to send an Excel chart from outlook macro
I got to the point where I run an outlook macro with rules and alerts.

The macro searches the inbox for a mail from mail address, when it finds it, it moves it to a sub folder, then extracts only the Number from the mail body, open an Excel, paste the number and mail date into the Excel on the next free row, updates the Excel, saves it and closes it.

last it moves the mail to the DONE directory and mark it as read.

In the Excel there is a pivot table that creates a graph (Chart 3).

Now I want to send that graph from the excel to mail recipients,
I found many ways to mail the graph from Excel but not from outlook macro.

here is what I have so far:

```<code>Sub MoveItems(Item As Outlook.MailItem)
'****************************************************************************
'* Find mail from sender and move them from the inbox to the rquests folder *
'****************************************************************************
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set myDestFolder = myInbox.Folders("Rquests")
Set myItem = myItems.Find("[SenderEmailAddress] = 'mail@domain.com'")
While TypeName(myItem) <> "Nothing"
    If myItem.UnRead = True Then
        myItem.Move myDestFolder
        Set myItem = myItems.FindNext
    End If
Wend
'*********************************************************
'* run the Process that extruct the number from the mail *
'*********************************************************
ProcessRequests
End Sub
---------------------------------------------------------------------------
Sub MoveItems2()
'*******************************************************************
'* Move the processed mail from the rquests to the  RQ_Done folder *
'*******************************************************************
Dim myNameSpace As Outlook.NameSpace
Dim mySourceFolder As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set mySourceFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Rquests")
Set myItems = mySourceFolder.Items
Set myDestFolder = mySourceFolder.Folders("RQ_Done")
Set myItem = myItems.Find("[SenderEmailAddress] = 'mail@domain.com'")
While TypeName(myItem) <> "Nothing"
    myItem.UnRead = False
    myItem.Move myDestFolder
    Set myItem = myItems.FindNext
Wend
End Sub
---------------------------------------------------------------------------
Sub ProcessRequests()
On Error Resume Next
Set myOlApp = Outlook.Application
Set myNameSpace = myOlApp.GetNamespace("mapi")
Dim msgtext As String
Dim TimeStamp As Date
'set the outlook folder to look at
Set myfolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Rquests")
'set excel parameters
Dim xlApp As Object
Dim xlWkb As Object
Dim xlSheet As Object
Dim rCount As Long
Set xlApp = CreateObject("excel.application.12")
xlApp.Visible = True
'Open existing excel
Set xlWkb = xlApp.Workbooks.Open("C:\pathtofile\QTYperday.xlsm")
Set xlSheet = xlWkb.Sheets("Data")
xlApp.Worksheets("Data").Activate
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
rCount = rCount + 1
'Search all mail items in current mail directory
For i = 1 To myfolder.Items.Count
    Set myItem = myfolder.Items(i)
    sender = myItem.SenderEmailAddress
    If sender = "mail@domain.com" Then
        msgtext = myItem.Body
        TimeStamp = myItem.SentOn
        'send the body of the mail message to the Function "onlyDigits" that will extract the numbers from it
        Dim myStr As String
        myStr = onlyDigits(msgtext)
        If myStr = "" Then
            myStr = "0"
        End If
        'get the date from date time
        mailDateY = DatePart("yyyy", TimeStamp) ' get Year
        MailDateM = DatePart("m", TimeStamp)    ' get Month
        MailDateD = DatePart("d", TimeStamp)    ' get Day
        MailDateW = DatePart("w", TimeStamp)    ' Get day of the week
        MailDate = (mailDateY & "/" & MailDateM & "/" & MailDateD)  ' Combine it to be a date again
        'set the day of the week
        If MailDateW = 1 Then
            MailDateW = "Sun"
        ElseIf MailDateW = 2 Then
            MailDateW = "Mon"
        ElseIf MailDateW = 3 Then
            MailDateW = "Tue"
        ElseIf MailDateW = 4 Then
            MailDateW = "Wed"
        ElseIf MailDateW = 5 Then
            MailDateW = "Thu"
        End If
        MailDay = MailDateW
        'write to excel
        xlSheet.Range("A" & rCount).value = myStr
        xlSheet.Range("B" & rCount).value = MailDate
        xlSheet.Range("C" & rCount).value = MailDateW
    Else
    End If
Next
xlApp.Worksheets("Sheet2").Activate
'Rerash and Save the excel
xlWkb.RefreshAll
xlWkb.Save
'************************
'mail the chart to list *
'************************
'Here I need the code to get the graph from excel and paste it to the email
'as an excel object or picture, It does not matter
'next is sending the mail with the graph (as attachement?)
Dim objMail As Outlook.MailItem
Set objMail = Application.CreateItem(olMailItem)
With objMail
        .To = "me@email.com"
        .CC = ""
        .BCC = ""
        .Subject = "Subject Line"
        .Body = "Body of mail"
        .Attachments.Add 'What, how?
        .Send
End With
xlWkb.Close 1
xlApp.Quit
' Mark processed mail as Read and move it to RQ_done folder
MoveItems2
End Sub
---------------------------------------------------------------------------
Function onlyDigits(s As String) As String
'************************************
'* extruct the number from the mail *
'************************************
Dim retval As String    ' This is the return string.      '
Dim i As Integer        ' Counter for character position. '
' Initialise return string to empty                       '
retval = ""
' For every character in input string, copy digits to     '
'   return string.                                        '
For i = 1 To Len(s)
    If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
        retval = retval + Mid(s, i, 1)
        If retval = "" Then
            retval = "0"
        End If
    End If
Next
' Then return the return string.                          '
onlyDigits = retval
End Function
</code>```

I have this piece of code that runs on the Excel, it saves the chart as gif file attach it and send it, is there a way to covert it to work from outlook?

```<code>Sub SaveSend_Embedded_Chart()
'Working in 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim Fname As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    'File path/name of the gif file
     Fname = Environ$("temp") & "\My_Sales1.gif"

    'Save Chart named "Chart 1" as gif file
    'If you hold down the CTRL key when you select the chart
    'in 2000-2013 you see the name in the Name box(formula bar)
     ActiveWorkbook.Worksheets("Sheet2").ChartObjects("Chart 3").Chart.Export _
            Filename:=Fname, FilterName:="GIF"

    On Error Resume Next
    With OutMail
        .To = "eeee@eeee.com"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hi there"
        .Attachments.Add Fname
        .Send   'or use .Display
     End With
     On Error GoTo 0

    'Delete the gif file
     Kill Fname

     Set OutMail = Nothing
     Set OutApp = Nothing
End Sub
</code>```

答:
You just have to reference Excel objects like you did in Sub ProcessRequests()

See :

```<code>Sub SaveSend_Embedded_Chart()
 'Working in 2000-2016
 'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
     Dim OutApp As Object
     Dim OutMail As Object
     Dim Fname As String

     Set OutApp = CreateObject("Outlook.Application")
     Set OutMail = OutApp.CreateItem(0)

     'File path/name of the gif file
     Fname = Environ$("temp") & "\My_Sales1.gif"

     Dim xlApp As Object
     Dim xlWkb As Object
     Dim xlSheet As Object

     Set xlApp = CreateObject("Excel.Application")
     xlApp.Visible = True
     'Open existing excel file
     Set xlWkb = xlApp.Workbooks.Open("C:\pathtofile\QTYperday.xlsm")
     Set xlSheet = xlWkb.Sheets("Sheet2")

     'Save Chart named "Chart 1" as gif file
     'If you hold down the CTRL key when you select the chart
     'in 2000-2013 you see the name in the Name box(formula bar)
      xlSheet.ChartObjects("Chart 3").Chart.Export _
             FileName:=Fname, FilterName:="GIF"

     On Error Resume Next
     With OutMail
         .To = "eitan@pitkit.co.il"
         .CC = ""
         .BCC = ""
         .Subject = "This is the Subject line"
         .Body = "Hi there"
         .Attachments.Add Fname
         .Send   'or use .Display
      End With
      On Error GoTo 0

     'Delete the gif file
      Kill Fname

      Set OutMail = Nothing
      Set OutApp = Nothing
 End Sub
</code>```

Body:
I got to the point where I run an outlook macro with rules and alerts.

The macro searches the inbox for a mail from mail address, when it finds it, it moves it to a sub folder, then extracts only the Number from the mail body, open an Excel, paste the number and mail date into the Excel on the next free row, updates the Excel, saves it and closes it.

last it moves the mail to the DONE directory and mark it as read.

In the Excel there is a pivot table that creates a graph (Chart 3).

Now I want to send that graph from the excel to mail recipients,
I found many ways to mail the graph from Excel but not from outlook macro.

here is what I have so far:

Sub MoveItems(Item As Outlook.MailItem)
'****************************************************************************
'* Find mail from sender and move them from the inbox to the rquests folder *
'****************************************************************************
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set myDestFolder = myInbox.Folders("Rquests")
Set myItem = myItems.Find("[SenderEmailAddress] = 'mail@domain.com'")
While TypeName(myItem) <> "Nothing"
    If myItem.UnRead = True Then
        myItem.Move myDestFolder
        Set myItem = myItems.FindNext
    End If
Wend
'*********************************************************
'* run the Process that extruct the number from the mail *
'*********************************************************
ProcessRequests
End Sub
---------------------------------------------------------------------------
Sub MoveItems2()
'*******************************************************************
'* Move the processed mail from the rquests to the  RQ_Done folder *
'*******************************************************************
Dim myNameSpace As Outlook.NameSpace
Dim mySourceFolder As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set mySourceFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Rquests")
Set myItems = mySourceFolder.Items
Set myDestFolder = mySourceFolder.Folders("RQ_Done")
Set myItem = myItems.Find("[SenderEmailAddress] = 'mail@domain.com'")
While TypeName(myItem) <> "Nothing"
    myItem.UnRead = False
    myItem.Move myDestFolder
    Set myItem = myItems.FindNext
Wend
End Sub
---------------------------------------------------------------------------
Sub ProcessRequests()
On Error Resume Next
Set myOlApp = Outlook.Application
Set myNameSpace = myOlApp.GetNamespace("mapi")
Dim msgtext As String
Dim TimeStamp As Date
'set the outlook folder to look at
Set myfolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Rquests")
'set excel parameters
Dim xlApp As Object
Dim xlWkb As Object
Dim xlSheet As Object
Dim rCount As Long
Set xlApp = CreateObject("excel.application.12")
xlApp.Visible = True
'Open existing excel
Set xlWkb = xlApp.Workbooks.Open("C:\pathtofile\QTYperday.xlsm")
Set xlSheet = xlWkb.Sheets("Data")
xlApp.Worksheets("Data").Activate
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
rCount = rCount + 1
'Search all mail items in current mail directory
For i = 1 To myfolder.Items.Count
    Set myItem = myfolder.Items(i)
    sender = myItem.SenderEmailAddress
    If sender = "mail@domain.com" Then
        msgtext = myItem.Body
        TimeStamp = myItem.SentOn
        'send the body of the mail message to the Function "onlyDigits" that will extract the numbers from it
        Dim myStr As String
        myStr = onlyDigits(msgtext)
        If myStr = "" Then
            myStr = "0"
        End If
        'get the date from date time
        mailDateY = DatePart("yyyy", TimeStamp) ' get Year
        MailDateM = DatePart("m", TimeStamp)    ' get Month
        MailDateD = DatePart("d", TimeStamp)    ' get Day
        MailDateW = DatePart("w", TimeStamp)    ' Get day of the week
        MailDate = (mailDateY & "/" & MailDateM & "/" & MailDateD)  ' Combine it to be a date again
        'set the day of the week
        If MailDateW = 1 Then
            MailDateW = "Sun"
        ElseIf MailDateW = 2 Then
            MailDateW = "Mon"
        ElseIf MailDateW = 3 Then
            MailDateW = "Tue"
        ElseIf MailDateW = 4 Then
            MailDateW = "Wed"
        ElseIf MailDateW = 5 Then
            MailDateW = "Thu"
        End If
        MailDay = MailDateW
        'write to excel
        xlSheet.Range("A" & rCount).value = myStr
        xlSheet.Range("B" & rCount).value = MailDate
        xlSheet.Range("C" & rCount).value = MailDateW
    Else
    End If
Next
xlApp.Worksheets("Sheet2").Activate
'Rerash and Save the excel
xlWkb.RefreshAll
xlWkb.Save
'************************
'mail the chart to list *
'************************
'Here I need the code to get the graph from excel and paste it to the email
'as an excel object or picture, It does not matter
'next is sending the mail with the graph (as attachement?)
Dim objMail As Outlook.MailItem
Set objMail = Application.CreateItem(olMailItem)
With objMail
        .To = "me@email.com"
        .CC = ""
        .BCC = ""
        .Subject = "Subject Line"
        .Body = "Body of mail"
        .Attachments.Add 'What, how?
        .Send
End With
xlWkb.Close 1
xlApp.Quit
' Mark processed mail as Read and move it to RQ_done folder
MoveItems2
End Sub
---------------------------------------------------------------------------
Function onlyDigits(s As String) As String
'************************************
'* extruct the number from the mail *
'************************************
Dim retval As String    ' This is the return string.      '
Dim i As Integer        ' Counter for character position. '
' Initialise return string to empty                       '
retval = ""
' For every character in input string, copy digits to     '
'   return string.                                        '
For i = 1 To Len(s)
    If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
        retval = retval + Mid(s, i, 1)
        If retval = "" Then
            retval = "0"
        End If
    End If
Next
' Then return the return string.                          '
onlyDigits = retval
End Function

I have this piece of code that runs on the Excel, it saves the chart as gif file attach it and send it, is there a way to covert it to work from outlook?

Sub SaveSend_Embedded_Chart()
'Working in 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim Fname As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    'File path/name of the gif file
     Fname = Environ$("temp") & "\My_Sales1.gif"

    'Save Chart named "Chart 1" as gif file
    'If you hold down the CTRL key when you select the chart
    'in 2000-2013 you see the name in the Name box(formula bar)
     ActiveWorkbook.Worksheets("Sheet2").ChartObjects("Chart 3").Chart.Export _
            Filename:=Fname, FilterName:="GIF"

    On Error Resume Next
    With OutMail
        .To = "eeee@eeee.com"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hi there"
        .Attachments.Add Fname
        .Send   'or use .Display
     End With
     On Error GoTo 0

    'Delete the gif file
     Kill Fname

     Set OutMail = Nothing
     Set OutApp = Nothing
End Sub

Body:
You just have to reference Excel objects like you did in Sub ProcessRequests()

See :

Sub SaveSend_Embedded_Chart()
 'Working in 2000-2016
 'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
     Dim OutApp As Object
     Dim OutMail As Object
     Dim Fname As String

     Set OutApp = CreateObject("Outlook.Application")
     Set OutMail = OutApp.CreateItem(0)

     'File path/name of the gif file
     Fname = Environ$("temp") & "\My_Sales1.gif"

     Dim xlApp As Object
     Dim xlWkb As Object
     Dim xlSheet As Object

     Set xlApp = CreateObject("Excel.Application")
     xlApp.Visible = True
     'Open existing excel file
     Set xlWkb = xlApp.Workbooks.Open("C:\pathtofile\QTYperday.xlsm")
     Set xlSheet = xlWkb.Sheets("Sheet2")

     'Save Chart named "Chart 1" as gif file
     'If you hold down the CTRL key when you select the chart
     'in 2000-2013 you see the name in the Name box(formula bar)
      xlSheet.ChartObjects("Chart 3").Chart.Export _
             FileName:=Fname, FilterName:="GIF"

     On Error Resume Next
     With OutMail
         .To = "eitan@pitkit.co.il"
         .CC = ""
         .BCC = ""
         .Subject = "This is the Subject line"
         .Body = "Hi there"
         .Attachments.Add Fname
         .Send   'or use .Display
      End With
      On Error GoTo 0

     'Delete the gif file
      Kill Fname

      Set OutMail = Nothing
      Set OutApp = Nothing
 End Sub


问:
Can a Go App dynamically compile Go code?
Say I have a Lua program that accepts user input which happens to be valid Lua source code. This is sanitized, compiled and executed while the program is still running. Is (or will) such a thing (be) possible with Go?</p>

答:
I think that the following two projects have enough meat between them to help me achieve what I want. Neither is a perfect drop-in replacement but both can be extended to deliver a service that is close enough to what I originally did with dynamic compilation in Lua.

https://github.com/Knetic/govaluate

https://github.com/japm/goScript


问:
Unable to select DropBox of an element which is a link and a dropbox
As part of work I have to automate a certain functionality But I am facing an issue in finding an element.

When I select the object and perform the operation. Selenium is performing operation link instead of selecting the dropbox.

Any suggestions would be appreciated.

```<code>Xapth=""//a[@id='TabBar:AccountTab']//span[contains(@class,'x-btn-wrap x-btn-split')] which I used to find the dropbox.
</code>```

HTML content for element 'ACCOUNT":

Des
k
top

A
c
count

```
</div>
</div>
</p>

<p>Element "Account" image:</p>

<p><img src="https://i.stack.imgur.com/xLXVz.png" alt="Element Account"></p>

<p>========================================================================</p>

<p><strong>HTML content for element to select from dropdown:</strong></p>

<h2>    New Account          </h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menu-1037-innerCt" class="x-box-inner x-vertical-box-overflow-body" role="presentation" style="height: 169px; width: 366px;">
<div id="menu-1037-targetEl" class="x-box-target" role="presentation" style="width: 366px;">
<div id="TabBar:AccountTab:AccountTab_NewAccount" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 0px; margin: 0px; width: 366px;">

<span id="TabBar:AccountTab:AccountTab_NewAccount-textEl" class="x-menu-item-text" unselectable="on">New Account</span>

</div>
<table id="TabBar:AccountTab:AccountTab_AccountNumberSearchItem" class="x-field x-table-plain x-form-item x-form-type-text x-box-item x-field-default x-vbox-form-item x-menu-item-cmp x-menu-item-indent" cellpadding="0" role="presentation" style="table-layout: auto; right: auto; left: 32px; top: 24px; width: 329px; margin: 0px;">
<div id="TabBar:AccountTab:0:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 49px; margin: 0px; width: 366px;">
<div id="TabBar:AccountTab:1:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 73px; margin: 0px; width: 366px;">
<div id="TabBar:AccountTab:2:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 97px; margin: 0px; width: 366px;">
<div id="TabBar:AccountTab:3:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 121px; margin: 0px; width: 366px;">
<div id="TabBar:AccountTab:4:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked x-menu-item-active" style="right: auto; left: 0px; top: 145px; margin: 0px; width: 366px;">
</div>
</div></code>```

Dropdown element "New Account" image:

Updated Element Image:
Element "New Account"

答:
From the html it is clearly seeing that it is not dropdown element.

Try to click on element using java-script executor method.

Note:- Provide wait before click on this below element, For wait use explicit wait method.

```<code>WebElement element = driver.findElement(By.xpath("//span[@id='TabBar:AccountTab-btnInnerEl']"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
</code>```

OR

```<code>driver.findElement(By.xpath("//span[@id='TabBar:AccountTab-btnInnerEl']")).click();
</code>```

Updated:-

Try this way.

```<code>driver.findElement(By.id("your_element_id")).click();    //Click on dropdown element first

WebDriverWait wait = new WebDriverWait(driver, 10);     //Explicit wait method, wait for web-element till 10 seconds so, your driver should able to find the web-element.
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//span[@id='TabBar:AccountTab-btnInnerEl']"))));

WebElement element = driver.findElement(By.xpath("//span[@id='TabBar:AccountTab-btnInnerEl']"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);      //After explicit wait method, click on element using java-script executor method.
</code>```

Body:
As part of work I have to automate a certain functionality But I am facing an issue in finding an element.

When I select the object and perform the operation. Selenium is performing operation link instead of selecting the dropbox.

Any suggestions would be appreciated.

Xapth=""//a[@id='TabBar:AccountTab']//span[contains(@class,'x-btn-wrap x-btn-split')] which I used to find the dropbox.

HTML content for element 'ACCOUNT":

Des
k
top

A
c
count

Element "Account" image:

========================================================================

HTML content for element to select from dropdown:

    New Account

New Account

Dropdown element "New Account" image:

Updated Element Image:
Element "New Account"

Body:
From the html it is clearly seeing that it is not dropdown element.

Try to click on element using java-script executor method.

Note:- Provide wait before click on this below element, For wait use explicit wait method.

WebElement element = driver.findElement(By.xpath("//span[@id='TabBar:AccountTab-btnInnerEl']"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);

OR

driver.findElement(By.xpath("//span[@id='TabBar:AccountTab-btnInnerEl']")).click();

Updated:-

Try this way.

driver.findElement(By.id("your_element_id")).click();    //Click on dropdown element first

WebDriverWait wait = new WebDriverWait(driver, 10);     //Explicit wait method, wait for web-element till 10 seconds so, your driver should able to find the web-element.
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//span[@id='TabBar:AccountTab-btnInnerEl']"))));

WebElement element = driver.findElement(By.xpath("//span[@id='TabBar:AccountTab-btnInnerEl']"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);      //After explicit wait method, click on element using java-script executor method.


问:
How to send log from Vagrant server to Graylog server
I'm quiet newbie with such problems, however I have to send log data from Vagrant server to my local machine where Graylog is installed. I have on my local machine docker tools installed where graylog, mongo and elasticsearch is up and running. Elasticsearch will be used to search specific logs. I have logs on first machine (Vagrant) and want to send them to another machine (where is graylog). Do you, guys, have some step by step tutorial or some hints, or etc.? I stuck with this issue and have no idea how to step further...</p>

答:
OK, I've got the solution. I needed just sending data to my graylog server and open port on graylog (Kitematic is great tool to see what's wrong with docker configuration i.e. ports). I sent logs by writing data to /dev/udp file like below:</p>

```<code>cd /home/iso/myAppFolder/myAppLogs; tail -f myAppLogs.log | grep totalTime > /dev/udp/[ip of my graylog]/[port] &
</code>```

Body:
OK, I've got the solution. I needed just sending data to my graylog server and open port on graylog (Kitematic is great tool to see what's wrong with docker configuration i.e. ports). I sent logs by writing data to /dev/udp file like below:

cd /home/iso/myAppFolder/myAppLogs; tail -f myAppLogs.log | grep totalTime > /dev/udp/[ip of my graylog]/[port] &


问:
How to decode emoji (unicode) in HBase using Java API?
In my HBase table, there are some encoded emoji, like \xF0\x9F\x8C\x8F and \xE2\x9A\xBE. I am trying to use Bytes.toString() to decode them. However, this method use utf-8 which can only decode three bytes code like \xE2\x9A\xBE and the four bytes code like \xF0\x9F\x8C\x8F appears to be a question mark (see below). So how can I decode the four bytes code to emoji and print them out? Anybody has an idea? Thanks in advance!

Example:

The result should be:

But I got

I am so sorry that I forgot to mention that I am using servlet to query HBase and write the content to response.

答:
When I read a file that contains the following character ""(F09F8C8F or U+1F30F) and it has a BOM which indicates UTF-8 encoding and I correctly convert it to UTF-8 by using

```<code>byte[] encoded = Files.readAllBytes(selectedFile.toPath());
String fileContents = new String(encoded, StandardCharsets.UTF_8);
</code>```

the resulting String is correctly converted and correctly displayed in my Java Swing application. But if I print the same String to the console I get a boxed question mark instead of the symbol. So the character is correctly converted, but it's just your output that gets it messed up.

To recreate this, you can use this:

```<code>public static void main(String[] args) throws Exception {
  byte[] encoded = { (byte) 0xF0, (byte) 0x9F, (byte) 0x8C, (byte) 0x8F };
  String convertedstring = new String(encoded, StandardCharsets.UTF_8);

  System.out.println("convertedstring: " + convertedstring);

  JDialog dialog = new JDialog();
  dialog.setSize(300, 100);
  dialog.setLocationRelativeTo(null);
  dialog.setTitle("encoding-test");
  dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
  JLabel label = new JLabel("convertedstring: " + convertedstring);
  dialog.add(label);

  dialog.setVisible(true);
}
</code>```

Console Output

JDialog Output

you might also wanna see Default character encoding for java console output and Java, UTF-8, and Windows console

Body:
When I read a file that contains the following character ""(F09F8C8F or U+1F30F) and it has a BOM which indicates UTF-8 encoding and I correctly convert it to UTF-8 by using

byte[] encoded = Files.readAllBytes(selectedFile.toPath());
String fileContents = new String(encoded, StandardCharsets.UTF_8);

the resulting String is correctly converted and correctly displayed in my Java Swing application. But if I print the same String to the console I get a boxed question mark instead of the symbol. So the character is correctly converted, but it's just your output that gets it messed up.

To recreate this, you can use this:

public static void main(String[] args) throws Exception {
  byte[] encoded = { (byte) 0xF0, (byte) 0x9F, (byte) 0x8C, (byte) 0x8F };
  String convertedstring = new String(encoded, StandardCharsets.UTF_8);

  System.out.println("convertedstring: " + convertedstring);

  JDialog dialog = new JDialog();
  dialog.setSize(300, 100);
  dialog.setLocationRelativeTo(null);
  dialog.setTitle("encoding-test");
  dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
  JLabel label = new JLabel("convertedstring: " + convertedstring);
  dialog.add(label);

  dialog.setVisible(true);
}

Console Output

JDialog Output

you might also wanna see Default character encoding for java console output and Java, UTF-8, and Windows console


问:
AngularJS slide transition
I'm trying to slide in a div and slide out another from left to right.

```<code><div class="moveleft" ng-switch="article">
    <div ng-switch-when="1">
    ...hi...
    </div>

    <div ng-switch-when="2">
    ...bye...
     </div>
</div>
</code>```

I want to do this sliding on a button click:

```<code><button ng-click="changeori()">Hi</button>
</code>```

In my AngularJS file:

```<code>$scope.article = 1;
$scope.changeori = function() {
    $scope.article = $scope.article == 1 ? 2 : 1;
}
</code>```

And for my moveleft class:

```<code>.moveleft, .moveright {
    transition: 2000ms cubic-bezier(0.420, 0.000, 0.580, 1.000) all;
}

.moveleft.ng-enter {
   left: 100%;
}
.moveleft.ng-enter-active {
    left: 0;
}
.moveleft.ng-leave {
    left: 0;
}
.moveleft.ng-leave-active {
    left: -100%;
}
</code>```

Problem: On clicking the button, the first div hides after 2 seconds and the second div comes on the click as expected, but the animations for slide are not happening.

答:
You are probably using the ng-animate wrong.

See this working demo

2 items(div) respond through animation css as below

```<code>.item {
    position: absolute;
    top: 35px;
    bottom: 0;
    right: 0;
    left: 0;
    animation-duration: 0.30s;
    animation-timing-function: ease-in-out;
    -webkit-animation-duration: 0.30s;
    -webkit-animation-timing-function: ease-in-out;
}

.item.ng-enter {
    animation-name: slideFromRight;
    -webkit-animation-name: slideFromRight;
}
.item.moveToLeft.ng-enter {
    animation-name: slideFromLeft;
    -webkit-animation-name: slideFromLeft;
}
.item.ng-leave {
    animation-name: slideFromLeft;
    animation-direction: reverse;
    -webkit-animation-name: slideFromLeft;
    -webkit-animation-direction: reverse;
}
.item.moveToLeft.ng-leave {
    animation-name: slideFromRight;
    animation-direction: reverse;
    -webkit-animation-name: slideFromRight;
    -webkit-animation-direction: reverse;
}
</code>```

Title: AngularJS slide transition

Body:
I'm trying to slide in a div and slide out another from left to right.

    ...hi...

    ...bye...

I want to do this sliding on a button click:

<button ng-click="changeori()">Hi</button>

In my AngularJS file:

$scope.article = 1;
$scope.changeori = function() {
    $scope.article = $scope.article == 1 ? 2 : 1;
}

And for my moveleft class:

.moveleft, .moveright {
    transition: 2000ms cubic-bezier(0.420, 0.000, 0.580, 1.000) all;
}

.moveleft.ng-enter {
   left: 100%;
}
.moveleft.ng-enter-active {
    left: 0;
}
.moveleft.ng-leave {
    left: 0;
}
.moveleft.ng-leave-active {
    left: -100%;
}

Problem: On clicking the button, the first div hides after 2 seconds and the second div comes on the click as expected, but the animations for slide are not happening.

Body:
You are probably using the ng-animate wrong.

See this working demo

2 items(div) respond through animation css as below

.item {
    position: absolute;
    top: 35px;
    bottom: 0;
    right: 0;
    left: 0;
    animation-duration: 0.30s;
    animation-timing-function: ease-in-out;
    -webkit-animation-duration: 0.30s;
    -webkit-animation-timing-function: ease-in-out;
}

.item.ng-enter {
    animation-name: slideFromRight;
    -webkit-animation-name: slideFromRight;
}
.item.moveToLeft.ng-enter {
    animation-name: slideFromLeft;
    -webkit-animation-name: slideFromLeft;
}
.item.ng-leave {
    animation-name: slideFromLeft;
    animation-direction: reverse;
    -webkit-animation-name: slideFromLeft;
    -webkit-animation-direction: reverse;
}
.item.moveToLeft.ng-leave {
    animation-name: slideFromRight;
    animation-direction: reverse;
    -webkit-animation-name: slideFromRight;
    -webkit-animation-direction: reverse;
}


问:
ASP.NET MVC Url.Action in JQuery is not recognized
I am trying to use Url.Action() method in my js file to define urls for my ajax calls. So far I have failed.

```<code> $.ajax(
 {
    type: "POST",
    url: '@Url.Action("SomeAction", "SomeController")',
    data: {
        fileID: rightClickedFileId
    },
    success: function (data) {

    }
 });
</code>```

If i define the url in this way, browser tries to post data to

```<code>http://localhost:5907/FileManager/@Url.Action(%22SomeAction%22,%20%22SomeController%22)
</code>```

and as a result my ajax call fails.

However, If I use '/SomeController/SomeAction' instead, everythings works fine.

Second works ok, but I am wondering the problem with first one ? Could it be due to routing configuration ?

Thanks.

答:
you can write it like this way  just  </p>

```<code>url:'/controllername/Actionname',
</code>```

Body:
I am trying to use Url.Action() method in my js file to define urls for my ajax calls. So far I have failed.

 $.ajax(
 {
    type: "POST",
    url: '@Url.Action("SomeAction", "SomeController")',
    data: {
        fileID: rightClickedFileId
    },
    success: function (data) {

    }
 });

If i define the url in this way, browser tries to post data to

http://localhost:5907/FileManager/@Url.Action(%22SomeAction%22,%20%22SomeController%22)

and as a result my ajax call fails.

However, If I use '/SomeController/SomeAction' instead, everythings works fine.

Second works ok, but I am wondering the problem with first one ? Could it be due to routing configuration ?

Thanks.

Body:
you can write it like this way  just

url:'/controllername/Actionname',


问:
Get html input type value in lightning JS controller
I am stuck with one issue regarding lightning components, I am using

<input type="date" aura.id="Wellness Visit" class="inpText" format="MM/dd/yyyy" value="{!v.visitDate}" /> element

Calendar is appearing but not able to get the value in controller.

```<code>var inputDate = component.find("Wellness Visit").get("v.value");
console.log('*****inputDate****'+inputDate);
</code>```

Getting undefined in the log

Please suggest any other way i can get the html elament value.

Thanks in advance!

答:
You should use Aura input component instead of html tag,

```<code>    <ui:inputDate aura.id="Wellness Visit" class="inpText" format="MM/dd/yyyy" value="{!v.visitDate}" />
</code>```

For more you can read here https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_ui_inputDate.htm

Body:
I am stuck with one issue regarding lightning components, I am using

<input type="date" aura.id="Wellness Visit" class="inpText" format="MM/dd/yyyy" value="{!v.visitDate}" /> element

Calendar is appearing but not able to get the value in controller.

var inputDate = component.find("Wellness Visit").get("v.value");
console.log('*****inputDate****'+inputDate);

Getting undefined in the log

Please suggest any other way i can get the html elament value.

Thanks in advance!

Body:
You should use Aura input component instead of html tag,

    <ui:inputDate aura.id="Wellness Visit" class="inpText" format="MM/dd/yyyy" value="{!v.visitDate}" />

For more you can read here https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_ui_inputDate.htm


问:
Woocommerce Variations Displayed on Archive Pages
I've got some code working perfectly on my single product pages. For some reason, it will not function the same in archive/list view.

First, I used a plugin to make the variations radio buttons instead of the dropdown. Then I modified that and made it display the price of each variation. Like I said, works great on product page.

I'm new at this google and compile until my eyes bleed and eventually it works. No such luck this time.

Here is the product page: http://pchdelivery.com/product/star-wars-kush/
Here is archive: http://pchdelivery.com/menu/

I don't need any of the cart functionality, only to display the variations and respective price with each product in categories.

Thanks in advance

答:
As per I can understand the issue, you may need to change the settings from the attribute options for the product where you will have to choose the option to not shown in product archive pages.

Screenshot : http://www.awesomescreenshot.com/image/2352336/b6552a6b4d83f8c16efd5935046728c4

Hope it helps.


问:
How does the new automatic reference counting mechanism work?
Can someone briefly explain to me how ARC works? I know it's different from Garbage Collection, but I was just wondering exactly how it worked.

Also, if ARC does what GC does without hindering performance, then why does Java use GC? Why doesn't it use ARC as well?

答:
Very well explained by Apple developer documentation. Read "How ARC Works"

To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

To know Diff. between Garbage collection and ARC: Read this


问:
my output CSV file is not copying the data
I am comparing 2 CSV files, one is already there other one is prodcued by running this piece of code. Basically, it is supposed to go through the newest sheet and see if there is new row added (column A only) and make a diff file and copy the newly added row from newest file to the diff file. her eis the code i am using:

```<code>import os, csv, time, glob

timestr = time.strftime("%Y%m%d-%H%M%S")

f=open("B:/Test_folder/parse_file1_"+timestr+'.csv', 'w+', newline='' )
w=csv.writer(f)
for dirs in os.listdir("B:/folder1"):
        w.writerow([dirs])

newest = max(glob.iglob('B:/Test_folder/parse_file1_*.csv'), key=os.path.getctime)
oldest = min(glob.iglob('B:/Test_folder/parse_file1_*.csv'), key=os.path.getctime)
with open(oldest, 'r') as t1, open(newest, 'r') as t2:
    fileone = t1.readlines()
    filetwo = t2.readlines()
with open('B:/Test_folder/file1_diff.csv', 'w') as outFile:
    for line in filetwo:
        if line not in fileone:
            outFile.write(line)
outFile.close()
</code>```

oldest file (already exist) = parse_file1_20170328_currentime

```<code>A
B
C
</code>```

and
newest file = parse_file2_20170329_currentime

```<code>A
B
C
D
</code>```

expected output should be:
file1_diff

```<code>D
</code>```

my problem is, even though it is creating a diff file, it is not copying D to the CSV file.
I am screwing something with the logic here, please help

Thanks

答:
Maybe removing whitespace will help:
    for line in filetwo:
        if line.strip() not in fileone:
            outFile.write(line.strip())</p>

Body:
I am comparing 2 CSV files, one is already there other one is prodcued by running this piece of code. Basically, it is supposed to go through the newest sheet and see if there is new row added (column A only) and make a diff file and copy the newly added row from newest file to the diff file. her eis the code i am using:

import os, csv, time, glob

timestr = time.strftime("%Y%m%d-%H%M%S")

f=open("B:/Test_folder/parse_file1_"+timestr+'.csv', 'w+', newline='' )
w=csv.writer(f)
for dirs in os.listdir("B:/folder1"):
        w.writerow([dirs])

newest = max(glob.iglob('B:/Test_folder/parse_file1_*.csv'), key=os.path.getctime)
oldest = min(glob.iglob('B:/Test_folder/parse_file1_*.csv'), key=os.path.getctime)
with open(oldest, 'r') as t1, open(newest, 'r') as t2:
    fileone = t1.readlines()
    filetwo = t2.readlines()
with open('B:/Test_folder/file1_diff.csv', 'w') as outFile:
    for line in filetwo:
        if line not in fileone:
            outFile.write(line)
outFile.close()

oldest file (already exist) = parse_file1_20170328_currentime

A
B
C

and
newest file = parse_file2_20170329_currentime

A
B
C
D

expected output should be:
file1_diff

D

my problem is, even though it is creating a diff file, it is not copying D to the CSV file.
I am screwing something with the logic here, please help

Thanks


问:
How to update the logo of an android app in playstore?
How to update app logo as play store app icon? I changed in the app manifest, but its not changing while i am updating the app.I use this code in Android Manifest Application tag

android:icon="@mipmap/ic_app_logo"
android:logo="@mipmap/ic_app_logo"

答:
Ok then you should change your app icon in developer console which is 512*512

go to store listing in developer console and change Hi-res icon (app icon) as it will override your icon in app.


问:
Passing large text-data through intent. How to cache it?
I'm passing some data to DatabaseService through an Intent.
However there is a corner case of one user when this data is really huuuge. And I get

E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!

Bummer.

Normally people assume that I try to pass a bitmap to (though?) a LruCache. Okay, can I use if for like an array list of objects? As I said - in fact this is a response from server, which is a JSON.

Any ideas how to solve this?
Is there a special class for this that I'm not aware of?

答:
Option 1. Store json data in db and then access data from db in your activity

Option 2. Store data in a centralized object (singleton etc) & then access that object in Activity.

Let say you have a single class AppData.
Store data in AppData.
Access data using AppData in your activity directly.

Option 3. Parse json to corresponding entities/models, make them Parcelable, then Store parcelable data in preference.

How to make entity parcelable with just copy paste


问:
If I got many to many relationship data first, how do I insert them to my table?
Say I have a customer table, a product table and an order table to record who buys what, the order table basically has 2 foreign keys, customer_id & product_id.

Now I got the order information first, within in it I can't find the customer information in my local database. As it turns out this is a new customer, whose information will come later from another thread/queue. To make things even worse the customer id I got from the order information is not the same one I used locally. My local customer id is INTEGER PRIMARY KEY (I do record that "true customer id" as another column and set index on it)

So how I do record this order information? I can come up with some clumsy solution, e.g. if I can't find contact info, I insert a record for it first. Later after I get the real information for this customer, I update customer & order table. But I was wondering is there any "standard" way for the situation like this?

答:
Inserting NULL values, and then updating with the real values later, is simple and will work (if you don't have a NOT NULL constraint).
You should use a transaction so that concurrent users don't see the incomplete data.

You could use deferred foreign key constraints:

If a statement modifies the contents of the database such that a deferred foreign key constraint is violated, the violation is not reported immediately. Deferred foreign key constraints are not checked until the transaction tries to COMMIT. For as long as the user has an open transaction, the database is allowed to exist in a state that violates any number of deferred foreign key constraints.

However, deferred foreign key constraints are useful only if you are inserting values that violate the constraint; a NULL value is not considered a FK violation.


问:
5 boxes not centering correctly in the center of the page
I am totally new into programming. I've aligned 5 boxed horizontally , but what I want is to center the boxes. The boxes should also be responsive what they are right now. I am searching and searching for how to center a div, but as result I get
 margin: 0 auto; width: 800px;. When I adjust my browser to 100%, the 5th box get under the other boxes.

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="outside">
  <div class="square">
   <span>2.1</span>
  </div>
  <div class="square">
   <span>2.3</span>
  </div>
  <div class="square">
   <span>2.5</span>
  </div>
  <div class="square">
   <span>2.6</span>
  </div>
  <div class="square">
   <span>2.7</span>
  </div>
 </div></code>```

答:
I didn't understand your requirement entirely but try the following. It will center your boxes and also won't allow them to wrap to next line on reducing the resolution.

Replace your css with:

```<code>.square {
    float: left;
    width: 19%;
    height: 12.5vw;
    margin-right: 1%;
    position: relative;
    border: 0.5px solid red;
    text-align: center;
    box-sizing: border-box;
}

.square span {
    font-size: 3vw;
}

.outside {
    width: 100%;
}

.inside {
    width: 69%;
    margin: 0 auto;
    overflow: auto;
}
</code>```

Html with:

```<code><div class="outside">
  <div class="inside">
        <div class="square">
            <span>2.1</span>
        </div>
        <div class="square">
            <span>2.3</span>
        </div>
        <div class="square">
            <span>2.5</span>
        </div>
        <div class="square">
            <span>2.6</span>
        </div>
        <div class="square">
            <span>2.7</span>
        </div>
   </div>
</div>
</code>```

Body:
I am totally new into programming. I've aligned 5 boxed horizontally , but what I want is to center the boxes. The boxes should also be responsive what they are right now. I am searching and searching for how to center a div, but as result I get
 margin: 0 auto; width: 800px;. When I adjust my browser to 100%, the 5th box get under the other boxes.

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}

   2.1

   2.3

   2.5

   2.6

   2.7

Body:
I didn't understand your requirement entirely but try the following. It will center your boxes and also won't allow them to wrap to next line on reducing the resolution.

Replace your css with:

.square {
    float: left;
    width: 19%;
    height: 12.5vw;
    margin-right: 1%;
    position: relative;
    border: 0.5px solid red;
    text-align: center;
    box-sizing: border-box;
}

.square span {
    font-size: 3vw;
}

.outside {
    width: 100%;
}

.inside {
    width: 69%;
    margin: 0 auto;
    overflow: auto;
}

Html with:

<div class="outside">
  <div class="inside">
        <div class="square">
            <span>2.1</span>
        </div>
        <div class="square">
            <span>2.3</span>
        </div>
        <div class="square">
            <span>2.5</span>
        </div>
        <div class="square">
            <span>2.6</span>
        </div>
        <div class="square">
            <span>2.7</span>
        </div>
   </div>
</div>