问:
My function Java didn't work with DB (MySQL) using Struts 2
I have some problem with my code it didn't work I think this problem in my class UserService but I'm not sure. When I run my program my console shows:

Stacktraces:

```<code>java.lang.NullPointerException
    com.web.actions.UtlisateurAction.listUsers(UtlisateurAction.java:67)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:139)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:151)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

You are seeing this page because development mode is enabled. Development mode, or devMode, enables extra debugging behaviors and reports to assist developers. To disable this mode, set:

  struts.devMode=false
in your WEB-INF/classes/struts.properties file.
</code>```

UtlisateurAction.java:

```<code>package com.web.actions;

import java.util.List;

import com.app.business.bo.security.Role;
import com.app.business.bo.security.Utlisateur;
import com.app.business.services.UtlisateurService;
import com.app.exceptions.DuplicateLoginException;
import com.web.BaseAction;

public class UtlisateurAction extends BaseAction {

    private UtlisateurService userService;

    private List<Utlisateur> listUsers;

    private Utlisateur utilisateur;

    private List<Role> listRoles;

    private Long selectedRole;

    public String passage(){
        System.out.println("Passage");
    return SUCCESS;
    }
    public String showMenu(){
        System.out.println("User Access");
        return SUCCESS;
    }

    public String initFormAddUser() {
        listRoles = userService.getAllRoles();

        return SUCCESS;
    }

    public String addUser() {

        try {
            utilisateur.setRole(userService.getRoleById(selectedRole));
            userService.addUtilisateur(utilisateur);

        } catch (DuplicateLoginException ex) {
            addActionError("Operation non effectuee a  cause d'une erreur");

            ex.printStackTrace();
            return "error";

        } catch (Exception ex) {
            addActionError("Operation non effectuee Ã  cause d'une erreur");

            ex.printStackTrace();
            return "error";

        }
        // on affiche une page d'erreur
        addActionMessage("Utilisateur ajoutée avec succées");
        return SUCCESS;
    }

    public String listUsers() {
        System.out.println("On train de detecter");
        listUsers = userService.getAllUsers();
        System.out.println("GET ALL USERS");
        return SUCCESS;
    }

    public List<Utlisateur> getListUsers() {
        return listUsers;
    }

    public void setListUsers(List<Utlisateur> listUsers) {
        this.listUsers = listUsers;
    }

    public UtlisateurService getUserService() {
        return userService;
    }

    public void setUserService(UtlisateurService userService) {
        this.userService = userService;
    }

    public Utlisateur getUtilisateur() {
        return utilisateur;
    }

    public void setUtilisateur(Utlisateur utilisateur) {
        this.utilisateur = utilisateur;
    }

    public List<Role> getListRoles() {
        return listRoles;
    }

    public void setListRoles(List<Role> listRoles) {
        this.listRoles = listRoles;
    }

    public Long getSelectedRole() {
        return selectedRole;
    }

    public void setSelectedRole(Long selectedRole) {
        this.selectedRole = selectedRole;
    }

}
</code>```

UtlisateurServiceImpl.java:

```<code>package com.services.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.bo.security.Role;
import com.bo.security.Utilisateur;
import com.boudaa.dao.exceptions.EntityNotFoundException;
import com.dao.RoleDao;
import com.dao.UtilisateurDao;
import com.exceptions.DuplicateLoginException;
import com.services.UtilisateurService;

public class UtilisateurServiceImpl implements UtilisateurService, UserDetailsService {

    private UtilisateurDao userDao;
    private RoleDao roleDao;

    protected final Log log = LogFactory.getLog(getClass());

    public UserDetails loadUserByUsername(String pLogin) throws UsernameNotFoundException {
        Utilisateur lUser = null;
        Collection<GrantedAuthority> arrayAuths = new ArrayList<GrantedAuthority>();

        // On rÃ©cupÃ¨re un objet de domaine de type User ayant comme login pLogin
        try {
            lUser = userDao.getUserByLogin(pLogin);

        } catch (ObjectRetrievalFailureException ex) {
            ex.printStackTrace();

            // nous relanÃ§ons une UsernameNotFoundException si aucun utilisateur
            // ne correspond Ã  cet login
            log.debug("Erreur d'authentification avec le login : " + pLogin);
            throw new UsernameNotFoundException("User " + pLogin + " not exists", ex);

        }

        // Si un utilisateur correspond Ã  cet identifiant, nous en profitons
        // pour mettre Ã  jour sa date de derniÃ¨re connexion
        lUser.setLastAccessDate(Calendar.getInstance().getTime());
        userDao.update(lUser);
        // Il faut ensuite rÃ©cupÃ©rer les rÃ´les de lâ€™utilisateur et les
        // mettre
        // sous la forme de SimpleGrantedAuthority, une interface propre Ã
        // Spring
        // Security*

        Role role = lUser.getRole();
        arrayAuths.add(new SimpleGrantedAuthority(role.getRoleName()));
        // /un User (classe Spring Security) est crÃ©Ã©
        System.out.println("oui");
        return new User(pLogin, lUser.getPassword(), lUser.isEnabled(), lUser.isAccountNotExpired(), true,
                lUser.isAccountNotLocked(), arrayAuths);
    }

    public Utilisateur getUserByLogin(String pLogin) throws EntityNotFoundException {

        List<Utilisateur> users;
        try {
            users = userDao.getEntityByColumn("Utilisateur", "login", pLogin);

        } catch (ObjectRetrievalFailureException ex) {

            throw new EntityNotFoundException("Aucun utilisateur avec le login : " + pLogin);
        }

        if (users.size() != 1) {
            // TODO : Ecrire le code pour ajouter des log fatal
            // TODO : ecrire le code envoyant un mail d'erreur fatal Ã
            // l'administrateur

            throw new RuntimeException("Erreur inconnue dans le systeme");
        }

        return users.get(0);
    }
    public void addUtilisateur(Utilisateur user) throws DuplicateLoginException {

        // pour hacher avec SHA1
        ShaPasswordEncoder encoder = new ShaPasswordEncoder();

        // Hachage du mot de passe avec un gain de sel variable = login
        String cryptedPassword = encoder.encodePassword(user.getPassword(),
                user.getLogin());

        // affecter le mot de passe hachÃ©
        user.setPassword(cryptedPassword);

        // stockage de l'utilisateur dans la base de donnÃ©es
        try {
            userDao.create(user);

        } catch (DataIntegrityViolationException ex) {
            log.error("erreur d'ajout d'un utilisateur Ã  cause de l'exception " + ex
                    + " . un utilisateur avec le login " + user.getLogin() + " existe dÃ©jÃ  dans la base de donnÃ©es");
            throw new DuplicateLoginException("Erreur d'inscription, login existe dÃ©jÃ ", ex);
        }

    }

    public Role getRoleByName(String roleName) {
        return roleDao.getRoleByName(roleName);
    }

    public Role getRoleById(Long pRoleId) throws EntityNotFoundException {
        return roleDao.findById(pRoleId);
    }

    public List<Utilisateur> getAllUsers() {
        return userDao.getAll();
    }

    public List<Role> getAllRoles() {
        return roleDao.getAll();
    }

    public void deleteUser(Utilisateur u) throws EntityNotFoundException {

        userDao.delete(u.getIdUtilisateur());

    }

    public UtilisateurDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UtilisateurDao userDao) {
        this.userDao = userDao;
    }

    public RoleDao getRoleDao() {
        return roleDao;
    }

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

}
</code>```

答:
It looks like if the bean id is available in applicationContext.xml then it will be injected to the action bean. Otherwise null values expected when beans remains uninitialized.

For integration struts with spring you need struts-spring-plugin.

Spring is a lightweight container, providing centralized, automated
  configuration and wiring of your application objects, using a
  technique called "Dependency Injection"

The Spring Plugin works by overriding the Struts ObjectFactory to
  enhance the creation of core framework objects. When an object is to
  be created, it uses the class attribute in the Struts configuration to
  correspond to the id attribute in the Spring configuration. If not
  found, the class will try to be created as usual, then be autowired by
  Spring. In the case of Actions, Spring 2's bean scope feature can be
  used to scope an Action instance to the session, application, or a
  custom scope, providing advanced customization above the default
  per-request scoping.

Spring Actions are Optional!

ContentLicense: CC BY-SA 4.0

Body:
I have some problem with my code it didn't work I think this problem in my class UserService but I'm not sure. When I run my program my console shows:

Stacktraces:

java.lang.NullPointerException
    com.web.actions.UtlisateurAction.listUsers(UtlisateurAction.java:67)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:139)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:151)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

You are seeing this page because development mode is enabled. Development mode, or devMode, enables extra debugging behaviors and reports to assist developers. To disable this mode, set:

  struts.devMode=false
in your WEB-INF/classes/struts.properties file.

UtlisateurAction.java:

package com.web.actions;

import java.util.List;

import com.app.business.bo.security.Role;
import com.app.business.bo.security.Utlisateur;
import com.app.business.services.UtlisateurService;
import com.app.exceptions.DuplicateLoginException;
import com.web.BaseAction;

public class UtlisateurAction extends BaseAction {

    private UtlisateurService userService;

    private List<Utlisateur> listUsers;

    private Utlisateur utilisateur;

    private List<Role> listRoles;

    private Long selectedRole;

    public String passage(){
        System.out.println("Passage");
    return SUCCESS;
    }
    public String showMenu(){
        System.out.println("User Access");
        return SUCCESS;
    }

    public String initFormAddUser() {
        listRoles = userService.getAllRoles();

        return SUCCESS;
    }

    public String addUser() {

        try {
            utilisateur.setRole(userService.getRoleById(selectedRole));
            userService.addUtilisateur(utilisateur);

        } catch (DuplicateLoginException ex) {
            addActionError("Operation non effectuee a  cause d'une erreur");

            ex.printStackTrace();
            return "error";

        } catch (Exception ex) {
            addActionError("Operation non effectuee Ã  cause d'une erreur");

            ex.printStackTrace();
            return "error";

        }
        // on affiche une page d'erreur
        addActionMessage("Utilisateur ajoutée avec succées");
        return SUCCESS;
    }

    public String listUsers() {
        System.out.println("On train de detecter");
        listUsers = userService.getAllUsers();
        System.out.println("GET ALL USERS");
        return SUCCESS;
    }

    public List<Utlisateur> getListUsers() {
        return listUsers;
    }

    public void setListUsers(List<Utlisateur> listUsers) {
        this.listUsers = listUsers;
    }

    public UtlisateurService getUserService() {
        return userService;
    }

    public void setUserService(UtlisateurService userService) {
        this.userService = userService;
    }

    public Utlisateur getUtilisateur() {
        return utilisateur;
    }

    public void setUtilisateur(Utlisateur utilisateur) {
        this.utilisateur = utilisateur;
    }

    public List<Role> getListRoles() {
        return listRoles;
    }

    public void setListRoles(List<Role> listRoles) {
        this.listRoles = listRoles;
    }

    public Long getSelectedRole() {
        return selectedRole;
    }

    public void setSelectedRole(Long selectedRole) {
        this.selectedRole = selectedRole;
    }

}

UtlisateurServiceImpl.java:

package com.services.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.bo.security.Role;
import com.bo.security.Utilisateur;
import com.boudaa.dao.exceptions.EntityNotFoundException;
import com.dao.RoleDao;
import com.dao.UtilisateurDao;
import com.exceptions.DuplicateLoginException;
import com.services.UtilisateurService;

public class UtilisateurServiceImpl implements UtilisateurService, UserDetailsService {

    private UtilisateurDao userDao;
    private RoleDao roleDao;

    protected final Log log = LogFactory.getLog(getClass());

    public UserDetails loadUserByUsername(String pLogin) throws UsernameNotFoundException {
        Utilisateur lUser = null;
        Collection<GrantedAuthority> arrayAuths = new ArrayList<GrantedAuthority>();

        // On rÃ©cupÃ¨re un objet de domaine de type User ayant comme login pLogin
        try {
            lUser = userDao.getUserByLogin(pLogin);

        } catch (ObjectRetrievalFailureException ex) {
            ex.printStackTrace();

            // nous relanÃ§ons une UsernameNotFoundException si aucun utilisateur
            // ne correspond Ã  cet login
            log.debug("Erreur d'authentification avec le login : " + pLogin);
            throw new UsernameNotFoundException("User " + pLogin + " not exists", ex);

        }

        // Si un utilisateur correspond Ã  cet identifiant, nous en profitons
        // pour mettre Ã  jour sa date de derniÃ¨re connexion
        lUser.setLastAccessDate(Calendar.getInstance().getTime());
        userDao.update(lUser);
        // Il faut ensuite rÃ©cupÃ©rer les rÃ´les de lâ€™utilisateur et les
        // mettre
        // sous la forme de SimpleGrantedAuthority, une interface propre Ã
        // Spring
        // Security*

        Role role = lUser.getRole();
        arrayAuths.add(new SimpleGrantedAuthority(role.getRoleName()));
        // /un User (classe Spring Security) est crÃ©Ã©
        System.out.println("oui");
        return new User(pLogin, lUser.getPassword(), lUser.isEnabled(), lUser.isAccountNotExpired(), true,
                lUser.isAccountNotLocked(), arrayAuths);
    }

    public Utilisateur getUserByLogin(String pLogin) throws EntityNotFoundException {

        List<Utilisateur> users;
        try {
            users = userDao.getEntityByColumn("Utilisateur", "login", pLogin);

        } catch (ObjectRetrievalFailureException ex) {

            throw new EntityNotFoundException("Aucun utilisateur avec le login : " + pLogin);
        }

        if (users.size() != 1) {
            // TODO : Ecrire le code pour ajouter des log fatal
            // TODO : ecrire le code envoyant un mail d'erreur fatal Ã
            // l'administrateur

            throw new RuntimeException("Erreur inconnue dans le systeme");
        }

        return users.get(0);
    }
    public void addUtilisateur(Utilisateur user) throws DuplicateLoginException {

        // pour hacher avec SHA1
        ShaPasswordEncoder encoder = new ShaPasswordEncoder();

        // Hachage du mot de passe avec un gain de sel variable = login
        String cryptedPassword = encoder.encodePassword(user.getPassword(),
                user.getLogin());

        // affecter le mot de passe hachÃ©
        user.setPassword(cryptedPassword);

        // stockage de l'utilisateur dans la base de donnÃ©es
        try {
            userDao.create(user);

        } catch (DataIntegrityViolationException ex) {
            log.error("erreur d'ajout d'un utilisateur Ã  cause de l'exception " + ex
                    + " . un utilisateur avec le login " + user.getLogin() + " existe dÃ©jÃ  dans la base de donnÃ©es");
            throw new DuplicateLoginException("Erreur d'inscription, login existe dÃ©jÃ ", ex);
        }

    }

    public Role getRoleByName(String roleName) {
        return roleDao.getRoleByName(roleName);
    }

    public Role getRoleById(Long pRoleId) throws EntityNotFoundException {
        return roleDao.findById(pRoleId);
    }

    public List<Utilisateur> getAllUsers() {
        return userDao.getAll();
    }

    public List<Role> getAllRoles() {
        return roleDao.getAll();
    }

    public void deleteUser(Utilisateur u) throws EntityNotFoundException {

        userDao.delete(u.getIdUtilisateur());

    }

    public UtilisateurDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UtilisateurDao userDao) {
        this.userDao = userDao;
    }

    public RoleDao getRoleDao() {
        return roleDao;
    }

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

}


来源: stackexchange

问:
Detect Graphical Login In Bash
I am managing computers and accounts in my classroom, which is a CentOS 5.5 environment.  I am trying to figure out how to use the .bashrc file (or similar) to ensure that a task runs when a user logs in via Gnome/GDM, that is, logs into a GUI session, but that that task does not run when a user logs in via SSH or other terminal logins.  How can I accomplish this?</p>

答: You should probably take a look at the XDG autostart specification, which allows you to have applications start upon desktop login.  Since bash and other shells do not follow the XDG specs (obviously, they are UNIX shells, not DEs), you essentially achieve what you're looking for, but without worrying about shells at all.</p>

ContentLicense: CC BY-SA 2.5

Title: Detect Graphical Login In Bash


问:
Parse Server: logging specific functions
Is there a way to turn off logging on a specific cloud function but not for all of them? My issue is that the result of my cloud function contains a base64 image, and Parse Server by default output the base64 string to the log, which makes my daily log files extremely large and hard to maintain.

setting logLevel = 'warn' instead of 'info' solves this problem but then I lost the I/O information of other cloud functions which I also need..

thanks.

答: Can you open an issue in the repo with the specifics about your use case? We'll be probably able to slim down the logging for long base64 strings</p>

ContentLicense: CC BY-SA 3.0


问:
JavaScript updating iframe src via a loop to download multiple files
My objective is to simultaneously download multiple files via php in one request. I cannot use the 'zip' solution to zip the files. So the solution I came up with was to have an empty iframe and dynamically update the source so the iframe downloads multiple files.

I have a basic page with an iframe and when a user clicks the files they download it runs a script which loops through the selected files and update the iframe source to a php page which downloads a single file:

page which sends request:

```<code><script>
function download_files(){
    // assume this is a loop which finds out all the files which were selected by the user
    for (var i = 0, len = selected_fileids.length; i < len; i++) {

        var fileid_single2 = selected_fileids[i].split("select_");
        fileid_splitted = fileid_single2[1];

        document.getElementById('iframe_downloader').src = "/index.php?page=download&fileid=" + id;

    }
}
</script>

<iframe src="" style="width:0;height:0;border:0; border:none;" id="iframe_downloader"></iframe>";

<!-- assume there will be checkboxes here which lets the user pick their files -->

<p onclick="download_files();">download</p>
</code>```

php download script, assume $filepath and $filename have correct values:

```<code>header("Pragma: ");
        header("Cache-Control: ");
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=\"{$row_filename}.xls\"");
        header("Content-Transfer-Encoding: binary");
        readfile($filepath);
</code>```

So basically, the script loops through all selected files and keeps changing the source to try and download all the files via the iframe.

The problem I am having is that it appears to only actually download the last file. I have tried debugging it and I can see that it is being looped through all items as I can console.log the process. However only the last file is actually being triggered by the iframe.

I have tried adding setInterval, that is no good either. I have looked at fiddler and I can confirm only the last file is being triggered.

答:
You can create an iframe for each download. This is the solution in Javascript:

```<code><script>

function createFrame(url) {
    var frame = document.createElement("iframe");
    frame.setAttribute("src",url);
    frame.style.width  = "0";
    frame.style.height = "0";
    frame.style.border = "none";
    document.body.appendChild(frame);
}

function download_files() {
    var len = selected_fileids.length;
    for (var i = 0; i < len; i++) {
        var id = ....<incomplete original code>....;
        createFrame("/index.php?page=download&fileid="+id);
    }
}

</script>

<a href="#" onclick="download_files();return false;">download</a>
</code>```

I must warn that this code is untested, it just shows the idea.

Body:
My objective is to simultaneously download multiple files via php in one request. I cannot use the 'zip' solution to zip the files. So the solution I came up with was to have an empty iframe and dynamically update the source so the iframe downloads multiple files.

I have a basic page with an iframe and when a user clicks the files they download it runs a script which loops through the selected files and update the iframe source to a php page which downloads a single file:

page which sends request:

";

download

php download script, assume $filepath and $filename have correct values:

header("Pragma: ");
        header("Cache-Control: ");
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=\"{$row_filename}.xls\"");
        header("Content-Transfer-Encoding: binary");
        readfile($filepath);

So basically, the script loops through all selected files and keeps changing the source to try and download all the files via the iframe.

The problem I am having is that it appears to only actually download the last file. I have tried debugging it and I can see that it is being looped through all items as I can console.log the process. However only the last file is actually being triggered by the iframe.

I have tried adding setInterval, that is no good either. I have looked at fiddler and I can confirm only the last file is being triggered.

Body:
You can create an iframe for each download. This is the solution in Javascript:

<script>

function createFrame(url) {
    var frame = document.createElement("iframe");
    frame.setAttribute("src",url);
    frame.style.width  = "0";
    frame.style.height = "0";
    frame.style.border = "none";
    document.body.appendChild(frame);
}

function download_files() {
    var len = selected_fileids.length;
    for (var i = 0; i < len; i++) {
        var id = ....<incomplete original code>....;
        createFrame("/index.php?page=download&fileid="+id);
    }
}

</script>

<a href="#" onclick="download_files();return false;">download</a>

I must warn that this code is untested, it just shows the idea.


问:
How do you count the elements of an array in java
Say i have the array

```<code>int theArray = new int[20];
</code>```

The length of the array is 20 but the count is 0. How can i get the count?

答:
If you wish to have an Array in which you will not be allocating all of the elements, you will have to do your own bookkeeping to ensure how many elements you have placed in it via some other variable.  If you'd like to avoid doing this while also getting an "Array" that can grow capacities after its initial instantiation, you can create an ArrayList

```<code>ArrayList<Integer> theArray = new ArrayList<Integer>();
theArray.add(5); // places at index 0
theArray.size(); // returns length of 1
int answer = theArray.get(0); // index 0 = 5
</code>```

Don't forget to import it at the top of the file:

```<code>import java.util.ArrayList;
</code>```

Body:
Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?

Body:
If you wish to have an Array in which you will not be allocating all of the elements, you will have to do your own bookkeeping to ensure how many elements you have placed in it via some other variable.  If you'd like to avoid doing this while also getting an "Array" that can grow capacities after its initial instantiation, you can create an ArrayList

ArrayList<Integer> theArray = new ArrayList<Integer>();
theArray.add(5); // places at index 0
theArray.size(); // returns length of 1
int answer = theArray.get(0); // index 0 = 5

Don't forget to import it at the top of the file:

import java.util.ArrayList;


问:
Angular ui-router 1.0.3 reloadOnSearch equivalent
I recently upgraded to UI-router v1.0.3 from v0.3.2.  It seems as though reloadOnSearch has been removed from the stateConfig.

What is the equivalent of reloadOnSearch in v1.0.3?  I can't seem to find anything in the documentation.

The documentation seems to indicate it was removed in v0.2.5 (but I was using it in v0.3.2)

reloadOnSearch v0.2.5

Boolean (default true). If false will not retrigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload.

答:
You can use dynamic params.

https://ui-router.github.io/ng1/docs/latest/interfaces/params.paramdeclaration.html

From the doc

When dynamic is true, changes to the parameter value will not cause the state to be entered/exited. The resolves will not be re-fetched, nor will views be reloaded.

Normally, if a parameter value changes, the state which declared that the parameter will be reloaded (entered/exited). When a parameter is dynamic, a transition still occurs, but it does not cause the state to exit/enter.

This can be useful to build UI where the component updates itself when the param values change. A common scenario where this is useful is searching/paging/sorting.


问:
Objective C: How to fit the image inside the imageview
I am using the UIImagePickerController to select images for my app. But I am facing a issue with the aspect ratio of the selected images.The image is showing larger than its original size and the complete image is not shown.I have tried changing UIViewContentMode property to all possible values still no use.Can anyone guide me how to make it work in?

Here is the implementation of UIImagePickerController delegate

```<code>- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo {

     self.imageProfile.contentMode = UIViewContentModeScaleAspectFit;
     self.imageProfile.image = image;
     [picker dismissViewControllerAnimated:YES completion:nil];

}
</code>```

答:
Well as you are using autolayouts, first define an outlet with your image height constraint will called imageHeightConstraint and then modify your code with this one

```<code>- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo {

     float aspectRatio = image.size.height/image.size.width
     self.imageProfile.contentMode = UIViewContentModeScaleAspectFit;
     self.imageProfile.image = image;
     [self.imageHeightConstraint setConstant: self.imageProfile.frame.size.width * aspectRatio];
     [picker dismissViewControllerAnimated:YES completion:nil];
}
</code>```

EDITED

this is my code

```<code>#import "ViewController.h"

@interface ViewController () <UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageProfile;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageConstraintHeigth;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)selectImage:(id)sender {

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:picker animated:YES completion:NULL];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{

    float aspectRatio = image.size.height/image.size.width;
    self.imageProfile.contentMode = UIViewContentModeScaleAspectFit;
    self.imageProfile.image = image;
    //this if you need adjust heigth according to width
    [self.imageConstraintHeigth setConstant: self.imageProfile.frame.size.width * aspectRatio];

    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
</code>```

and this are my constraints

I hope this help, for me works just fine

Body:
I am using the UIImagePickerController to select images for my app. But I am facing a issue with the aspect ratio of the selected images.The image is showing larger than its original size and the complete image is not shown.I have tried changing UIViewContentMode property to all possible values still no use.Can anyone guide me how to make it work in?

Here is the implementation of UIImagePickerController delegate

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo {

     self.imageProfile.contentMode = UIViewContentModeScaleAspectFit;
     self.imageProfile.image = image;
     [picker dismissViewControllerAnimated:YES completion:nil];

}

Body:
Well as you are using autolayouts, first define an outlet with your image height constraint will called imageHeightConstraint and then modify your code with this one

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo {

     float aspectRatio = image.size.height/image.size.width
     self.imageProfile.contentMode = UIViewContentModeScaleAspectFit;
     self.imageProfile.image = image;
     [self.imageHeightConstraint setConstant: self.imageProfile.frame.size.width * aspectRatio];
     [picker dismissViewControllerAnimated:YES completion:nil];
}

EDITED

this is my code

#import "ViewController.h"

@interface ViewController () <UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageProfile;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageConstraintHeigth;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)selectImage:(id)sender {

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:picker animated:YES completion:NULL];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{

    float aspectRatio = image.size.height/image.size.width;
    self.imageProfile.contentMode = UIViewContentModeScaleAspectFit;
    self.imageProfile.image = image;
    //this if you need adjust heigth according to width
    [self.imageConstraintHeigth setConstant: self.imageProfile.frame.size.width * aspectRatio];

    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end

and this are my constraints

I hope this help, for me works just fine


问:
Code First Does not work
I am trying to add code first,but the App_Data folder is empty.

Web.config

```<code><connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Movie-20170604111514.mdf;Initial Catalog=aspnet-Movie-20170604111514;Integrated Security=True"
          providerName="System.Data.SqlClient" />
    <add name="MovieDBContext" connectionString="Data Source=(localDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
          providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

Model

```<code>public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}
</code>```

Can anyone help me ? Thanks in advance.

答:
You need to add a constructor in your MovieDBContext class as following:

```<code>public class MovieDBContext : DbContext
{
    public MovieDBContext () : base("Name=MovieDBContext")
    {
    }

    public DbSet<Movie> Movies { get; set; }
}
</code>```

For more detail you can read following link:
http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx

Title: Code First Does not work

Body:
I am trying to add code first,but the App_Data folder is empty.

Web.config

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Movie-20170604111514.mdf;Initial Catalog=aspnet-Movie-20170604111514;Integrated Security=True"
          providerName="System.Data.SqlClient" />
    <add name="MovieDBContext" connectionString="Data Source=(localDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
          providerName="System.Data.SqlClient" />
</connectionStrings>

Model

public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}

Can anyone help me ? Thanks in advance.

Body:
You need to add a constructor in your MovieDBContext class as following:

public class MovieDBContext : DbContext
{
    public MovieDBContext () : base("Name=MovieDBContext")
    {
    }

    public DbSet<Movie> Movies { get; set; }
}

For more detail you can read following link:
http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx


问:
Compare products in magento without logging in
I am not able to compare products in magento until i login into my account. I tried searching for solution of this, but couldn't find anything.

Thanks in advance.

答:
1) Enabled from admin side   system->configuration->advanced->system
   Here set enabled the log only for visitors.

If this part is disabled then '$this->_logCondition->isVisitorLogEnabled()' return 0.And that's why in table 'catalog_compare_item' no data is inserted.

2) Enable the below events from .xml files  (app/etc/local)

```<code>      <controller_action_predispatch>
            <observers><log><type>enabled</type></log></observers>
        </controller_action_predispatch>
        <controller_action_postdispatch>
            <observers><log><type>enabled</type></log></observers>
        </controller_action_postdispatch>
        <customer_login>
            <observers><log><type>enabled</type></log></observers>
        </customer_login>
        <customer_logout>
            <observers><log><type>enabled</type></log></observers>
        </customer_logout>
        <sales_quote_save_after>
            <observers><log><type>enabled</type></log></observers>
        </sales_quote_save_after>
        <checkout_quote_destroy>
            <observers><log><type>enabled</type></log></observers>
        </checkout_quote_destroy>
</code>```

Body:
1) Enabled from admin side   system->configuration->advanced->system
   Here set enabled the log only for visitors.

If this part is disabled then '$this->_logCondition->isVisitorLogEnabled()' return 0.And that's why in table 'catalog_compare_item' no data is inserted.

2) Enable the below events from .xml files  (app/etc/local)

      <controller_action_predispatch>
            <observers><log><type>enabled</type></log></observers>
        </controller_action_predispatch>
        <controller_action_postdispatch>
            <observers><log><type>enabled</type></log></observers>
        </controller_action_postdispatch>
        <customer_login>
            <observers><log><type>enabled</type></log></observers>
        </customer_login>
        <customer_logout>
            <observers><log><type>enabled</type></log></observers>
        </customer_logout>
        <sales_quote_save_after>
            <observers><log><type>enabled</type></log></observers>
        </sales_quote_save_after>
        <checkout_quote_destroy>
            <observers><log><type>enabled</type></log></observers>
        </checkout_quote_destroy>


答:
Look for the presence of the DISPLAY environment variable</p>

```<code>if [ x$DISPLAY != x ] ; then
  #graphical
fi
</code>```

Title: Detect Graphical Login In Bash

Body: I am managing computers and accounts in my classroom, which is a CentOS 5.5 environment.  I am trying to figure out how to use the .bashrc file (or similar) to ensure that a task runs when a user logs in via Gnome/GDM, that is, logs into a GUI session, but that that task does not run when a user logs in via SSH or other terminal logins.  How can I accomplish this?

Body:
Look for the presence of the DISPLAY environment variable

if [ x$DISPLAY != x ] ; then
  #graphical
fi


问:
Maven: Non Resolvable parent POM for com.example.speech:speech-google-cloud-samples
I tried using speech to text using google speech client from github:

https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/speech/cloud-client

In pom.xml it shows the following issue:

 Description    Resource    Path    Location    Type
Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-compiler-plugin:3.3:testCompile (execution: default-testCompile, phase: test-compile)   pom.xml /speech-google-cloud-samples    line 23 Maven Project Build Lifecycle Mapping Problem

How do i fix this problem? Sorry for the long code..

```<code><project>
 <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.speech</groupId>
  <artifactId>speech-google-cloud-samples</artifactId>
  <packaging>jar</packaging>

  <!-- Parent defines config for testing & linting. -->
 <parent>
    <artifactId>doc-samples</artifactId>
    <groupId>com.google.cloud</groupId>
    <version>1.0.0</version>
  <relativePath>../..</relativePath>
  </parent>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <!-- FIXME(lesv) - temp to fix an issue w/ GA Datastore -->
<!--
  <dependencyManagement>
    <dependencies>
      <dependency>
          <groupId>io.grpc</groupId>
          <artifactId>grpc-core</artifactId>
          <version>1.2.0</version>
      </dependency>
    </dependencies>
  </dependencyManagement>
 -->

  <dependencies>
    <!-- [START dependencies] -->
 <!-- https://mvnrepository.com/artifact/com.google.cloud/google-cloud-speech -->
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-speech</artifactId>
    <version>0.17.2-alpha</version>
</dependency>

    <dependency>
      <groupId>com.google.api</groupId>
      <artifactId>gax</artifactId>
      <version>1.1.0</version>
      <exclusions>
        <exclusion> <!-- exclude an old version of Guava -->
          <groupId>com.google.guava</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.8.Final</version>
</dependency>

    <!-- https://mvnrepository.com/artifact/io.grpc/grpc-core -->
    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-core</artifactId>
        <version>1.2.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.8.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java-util -->
    <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java-util</artifactId>
        <version>3.2.0</version>
    </dependency>

    <dependency>
      <groupId>com.google.api</groupId>
      <artifactId>gax-grpc</artifactId>
      <version>0.17.0</version>
      <exclusions>
        <exclusion> <!-- exclude an old version of Guava -->
          <groupId>com.google.guava</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <!-- [END dependencies] -->

    <!-- Test dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.truth</groupId>
      <artifactId>truth</artifactId>
      <version>0.32</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.example.language.QuickstartSample</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
`
</code>```

答:
Your title, and the content of your post show two different problems. I'm going to respond to the one described by the content of your post.

Your problem is a classic eclipse-integration problem; that is, you need to instruct eclipse what to do with various plugins that your pom references (you probably want to ignore them).

So in your situation, you need to copy/paste the below code in your pom; this will have effect only in Eclipse, and be ignored otherwise. Please note that you are likely to get the same error for other plugins as well, so you need to repeat/adapt the process for any similar errors you might get.

```<code>    <pluginManagement>
        <plugins>
            <!--This plugin's configuration is used to store Eclipse m2e settings
                only. It has no influence on the Maven build itself. -->
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-compiler-plugin</artifactId>
                                    <versionRange>[0.0.0,)</versionRange>
                                    <goals>
                                        <goal>testCompile</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore></ignore>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</code>```

Body:
I tried using speech to text using google speech client from github:

https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/speech/cloud-client

In pom.xml it shows the following issue:

 Description    Resource    Path    Location    Type
Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-compiler-plugin:3.3:testCompile (execution: default-testCompile, phase: test-compile)   pom.xml /speech-google-cloud-samples    line 23 Maven Project Build Lifecycle Mapping Problem

How do i fix this problem? Sorry for the long code..

<project>
 <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.speech</groupId>
  <artifactId>speech-google-cloud-samples</artifactId>
  <packaging>jar</packaging>

 <parent>
    <artifactId>doc-samples</artifactId>
    <groupId>com.google.cloud</groupId>
    <version>1.0.0</version>
  <relativePath>../..</relativePath>
  </parent>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-speech</artifactId>
    <version>0.17.2-alpha</version>
</dependency>

    <dependency>
      <groupId>com.google.api</groupId>
      <artifactId>gax</artifactId>
      <version>1.1.0</version>
      <exclusions>
        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.8.Final</version>
</dependency>

    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-core</artifactId>
        <version>1.2.0</version>
    </dependency>

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.8.Final</version>
    </dependency>

    <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java-util</artifactId>
        <version>3.2.0</version>
    </dependency>

    <dependency>
      <groupId>com.google.api</groupId>
      <artifactId>gax-grpc</artifactId>
      <version>0.17.0</version>
      <exclusions>
        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.truth</groupId>
      <artifactId>truth</artifactId>
      <version>0.32</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.example.language.QuickstartSample</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
`

Body:
Your title, and the content of your post show two different problems. I'm going to respond to the one described by the content of your post.

Your problem is a classic eclipse-integration problem; that is, you need to instruct eclipse what to do with various plugins that your pom references (you probably want to ignore them).

So in your situation, you need to copy/paste the below code in your pom; this will have effect only in Eclipse, and be ignored otherwise. Please note that you are likely to get the same error for other plugins as well, so you need to repeat/adapt the process for any similar errors you might get.

    <pluginManagement>
        <plugins>
            <!--This plugin's configuration is used to store Eclipse m2e settings
                only. It has no influence on the Maven build itself. -->
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-compiler-plugin</artifactId>
                                    <versionRange>[0.0.0,)</versionRange>
                                    <goals>
                                        <goal>testCompile</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore></ignore>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>


问:
SQL to find a string in another string
I have 2 tables:

tblFoo:

```<code>Id | MessageId | SenderName
</code>```

tblBar:

```<code>MessageId | Name
</code>```

I need to update all the rows in tblFoo with the MessageId from tblBar where SenderName starts with Name. e.g.

tblFoo:

```<code>Id     | MessageId | SenderName
-------+-----------+--------------------
365175 | NULL      | x.y.z.abc.def.ghi
535646 | NULL      | a.b.c.fjdkf.dsfjdsf:a
535647 | NULL      | a.b.c.sdjskfj.dsfjds:b
</code>```

tblBar:

```<code>MessageId                             | Name
--------------------------------------+--------
9B30FCD1-F063-4B7F-887B-65288C3681D3  | x.y.z
56FBEF0F-8C29-4614-8894-4F64A515659A  | a.b.c
</code>```

So in tblFoo Id=365175 would end up with MessageId = 9B30FCD1-F063-4B7F-887B-65288C3681D3 and Id=535646 would end up with MessageId = 56FBEF0F-8C29-4614-8894-4F64A515659A and Id=535647 would also end up with MessageId=
56FBEF0F-8C29-4614-8894-4F64A515659A

So far I have

```<code>begin transaction
    update tblFoo
    set MessageId =
    (
        select MessageId
        from tblBar
        where [Name] ???
    );
    rollback transaction
</code>```

I can't do

```<code>where [Name] like
</code>```

as [Name] is a substring of SenderName.

Or do I need to use a temp table?

答:
Your code looks like SQL Server.  You can do this using something like:

```<code>update h
    set MessageDefinitionId = (select MessageDefinitionId
                               from Sentilan2.msg.tblMessageDefinition md
                               where h.SenderName like md.[Name] + '%'
                              );
    from h;
</code>```

Your code is rather hard to follow because you define tables tblFoo and tblBar, but the sample code uses different table names.

Also note that this assumes that there is only one match.  You might want top 1 in the subquery to avoid run-time errors.

Title: SQL to find a string in another string

Body:
I have 2 tables:

tblFoo:

Id | MessageId | SenderName

tblBar:

MessageId | Name

I need to update all the rows in tblFoo with the MessageId from tblBar where SenderName starts with Name. e.g.

tblFoo:

Id     | MessageId | SenderName
-------+-----------+--------------------
365175 | NULL      | x.y.z.abc.def.ghi
535646 | NULL      | a.b.c.fjdkf.dsfjdsf:a
535647 | NULL      | a.b.c.sdjskfj.dsfjds:b

tblBar:

MessageId                             | Name
--------------------------------------+--------
9B30FCD1-F063-4B7F-887B-65288C3681D3  | x.y.z
56FBEF0F-8C29-4614-8894-4F64A515659A  | a.b.c

So in tblFoo Id=365175 would end up with MessageId = 9B30FCD1-F063-4B7F-887B-65288C3681D3 and Id=535646 would end up with MessageId = 56FBEF0F-8C29-4614-8894-4F64A515659A and Id=535647 would also end up with MessageId=
56FBEF0F-8C29-4614-8894-4F64A515659A

So far I have

begin transaction
    update tblFoo
    set MessageId =
    (
        select MessageId
        from tblBar
        where [Name] ???
    );
    rollback transaction

I can't do

where [Name] like

as [Name] is a substring of SenderName.

Or do I need to use a temp table?

Body:
Your code looks like SQL Server.  You can do this using something like:

update h
    set MessageDefinitionId = (select MessageDefinitionId
                               from Sentilan2.msg.tblMessageDefinition md
                               where h.SenderName like md.[Name] + '%'
                              );
    from h;

Your code is rather hard to follow because you define tables tblFoo and tblBar, but the sample code uses different table names.

Also note that this assumes that there is only one match.  You might want top 1 in the subquery to avoid run-time errors.


问:
Best practice for using date parameters in Spring controllers?
After written several backend APIs, I found that the following code duplicates in almost every method which needs to filter data by dates:

@GetMapping(value="/api/test")
@ResponseBody
public Result test(@RequestParam(value = "since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
                   @RequestParam(value = "until", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate until) {
    // Date validation code I want to eliminate
    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }

    // Do stuff
}
```

Obviously this is some kind of code smell. But, since I do need to validate since and until before using them to query the service/DAO, I am not sure where should I extract these code to?

Any advice?

答:
Implement org.springframework.core.convert.converter.Converter; interface.

Register with spring conversion service.

Use in you controller
Sharing sample code below :

```<code>public class MyCustomDateTypeConverter implements Converter<String, LocalDate> {

  @Override
  public LocalDate convert(String param) {
      //convert string to DateTime
      return dateTiemObjectCreatedfromParam;
  }

}
</code>```

```<code><bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">  <property name="converters">    <list>
        <bean class="com.x.y.z.web.converters.MyCustomDateTypeConverter"/>  </list>     </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService">

</mvc:annotation-driven>

public Result test(LocalDate since,LocalDate until) {

    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }

    // Do stuff
}
</code>```

Body:
After written several backend APIs, I found that the following code duplicates in almost every method which needs to filter data by dates:

@GetMapping(value="/api/test")
@ResponseBody
public Result test(@RequestParam(value = "since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
                   @RequestParam(value = "until", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate until) {
    // Date validation code I want to eliminate
    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }

    // Do stuff
}

Obviously this is some kind of code smell. But, since I do need to validate since and until before using them to query the service/DAO, I am not sure where should I extract these code to?

Any advice?

Body:
Implement org.springframework.core.convert.converter.Converter; interface.

Register with spring conversion service.

Use in you controller
Sharing sample code below :

public class MyCustomDateTypeConverter implements Converter<String, LocalDate> {

  @Override
  public LocalDate convert(String param) {
      //convert string to DateTime
      return dateTiemObjectCreatedfromParam;
  }

}

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">  <property name="converters">    <list>
        <bean class="com.x.y.z.web.converters.MyCustomDateTypeConverter"/>  </list>     </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService">

</mvc:annotation-driven>

public Result test(LocalDate since,LocalDate until) {

    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }

    // Do stuff
}


问:
Custom sort in iOS, want to show default(All Group) title on top from Coredata
I am using core data with NSFetchedResultController. In this case, I have an n number of user groups and a user can select a particular group or select all group. So manually I added All group title, static ID and relevant content to the database.

```<code>NSFetchRequest <IRSUserAssetGroup *> *fetchRequest = [NSFetchRequest fetchRequestWithEntityName: [IRSUserAssetGroup entityName]];

NSSortDescriptor *nameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey: NSStringFromSelector(@selector(assetGroupName))
                                                                     ascending: YES
                                                                      selector: @selector(localizedCaseInsensitiveCompare:)];

[fetchRequest setSortDescriptors: @[nameSortDescriptor]];

[fetchRequest setFetchBatchSize: 4];

NSManagedObjectContext *mainContext = [[IRSCoreDataManager sharedManager] managedObjectContext];

NSFetchedResultsController <IRSUserAssetGroup *> *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest: fetchRequest
                                                                                managedObjectContext: mainContext
                                                                                sectionNameKeyPath: nil
                                                                                cacheName: nil];

NSError *fetchError = nil;

if (![fetchedResultsController performFetch: &fetchError])
    FCALog(@"fetch error: %@", fetchError);

[self setUserAssetGroupFetchedResultsController: fetchedResultsController];
</code>```

This is my FRC code. I am using sort by name. Some group name has start with the number. Because of this All group not place in first place.

Is that possible All group place always top on sort?

Extra: I am using table view with search option

Example: @[@1, @5, @"text", @"aaaaaaa", @"All group"]. Here All group show always on top of the list. How can I sort like that.

Output: @[@"All group", @1, @5,  @"aaaaaaa", @"text"]

答:
You and I know that 'All group' is special because we read and understand the word, but core data has no way of knowing that the 'All group' is special; all it sees it that it starts with an "A".  You could add another property to your Entity isAllGroup and first sort by that, and then by assetGroupName.

Or you can have a property 'groupOrder' which is 0 for the "all Group" and 100 for every other groups. This allows you to have more room to have other special group ordering without creating a new property.

An even more general approach would be to add a property assetGroupNameForSort and sort by that instead of assetGroupName which is used for display only.  For most group the values are identical but for the "All Group" it is "__All Group" or something like that. This can also be used fix issue that can happen with names that are in difference languages that are sorted in ways you don't expect.

I would recommend the first approach, just add an 'isAllGroup' property.  It is the simplest and the data is readily understandable.

Also: minor issue - a fetchedResultsController does not respect FetchBatchSize so you can remove it.

Body:
I am using core data with NSFetchedResultController. In this case, I have an n number of user groups and a user can select a particular group or select all group. So manually I added All group title, static ID and relevant content to the database.

NSFetchRequest <IRSUserAssetGroup *> *fetchRequest = [NSFetchRequest fetchRequestWithEntityName: [IRSUserAssetGroup entityName]];

NSSortDescriptor *nameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey: NSStringFromSelector(@selector(assetGroupName))
                                                                     ascending: YES
                                                                      selector: @selector(localizedCaseInsensitiveCompare:)];

[fetchRequest setSortDescriptors: @[nameSortDescriptor]];

[fetchRequest setFetchBatchSize: 4];

NSManagedObjectContext *mainContext = [[IRSCoreDataManager sharedManager] managedObjectContext];

NSFetchedResultsController <IRSUserAssetGroup *> *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest: fetchRequest
                                                                                managedObjectContext: mainContext
                                                                                sectionNameKeyPath: nil
                                                                                cacheName: nil];

NSError *fetchError = nil;

if (![fetchedResultsController performFetch: &fetchError])
    FCALog(@"fetch error: %@", fetchError);

[self setUserAssetGroupFetchedResultsController: fetchedResultsController];

This is my FRC code. I am using sort by name. Some group name has start with the number. Because of this All group not place in first place.

Is that possible All group place always top on sort?

Extra: I am using table view with search option

Example: @[@1, @5, @"text", @"aaaaaaa", @"All group"]. Here All group show always on top of the list. How can I sort like that.

Output: @[@"All group", @1, @5,  @"aaaaaaa", @"text"]


问:
Center Input box and Font Awesome icons
Others have asked something similar but I seem to be struggling vertical aligning the font awesome icon with an input box.  It works okay when you don`t use the sizing to increase the font awesome icons, but as soon as you enter the fa-3x or something like that the margin-top gets added.

Does anybody have any ideas ?

Simple example would be:

```<code><div>
    <i class='icon icon-3x icon-camera'></i>
    <span id="inputfield">
      <input type="text" value="input here">
    </span>
</div>

div {
    border: 1px solid #ccc;
    height: 30px;
    margin: 60px;
    padding: 4px;
    vertical-align: middle;
}
i{
    float: left;
}
#inputfield{
    line-height: 30px;
    float: left;
}
</code>```

答:
can be achived with this
html

```<code><div class="input-group">
    <i class='fa fa-3x fa-camera'></i>
      <input type="text" value="input here">
</div>
</code>```

css

```<code>div.input-group
{
  display:table;
  margin:30px;
}

.input-group > input[type=text],
.input-group > i.fa
{
  display:table-cell;
  vertical-align:middle;
}

.input-group > i.fa
{
  line-height:20px;
}
</code>```

here is link for reference codepen link

i have added margin to div element to make it visible.

hope this helps....

Title: Center Input box and Font Awesome icons

Body:
Others have asked something similar but I seem to be struggling vertical aligning the font awesome icon with an input box.  It works okay when you don`t use the sizing to increase the font awesome icons, but as soon as you enter the fa-3x or something like that the margin-top gets added.

Does anybody have any ideas ?

Simple example would be:

      <input type="text" value="input here">

div {
    border: 1px solid #ccc;
    height: 30px;
    margin: 60px;
    padding: 4px;
    vertical-align: middle;
}
i{
    float: left;
}
#inputfield{
    line-height: 30px;
    float: left;
}

Body:
can be achived with this
html

<div class="input-group">
    <i class='fa fa-3x fa-camera'></i>
      <input type="text" value="input here">
</div>

css

div.input-group
{
  display:table;
  margin:30px;
}

.input-group > input[type=text],
.input-group > i.fa
{
  display:table-cell;
  vertical-align:middle;
}

.input-group > i.fa
{
  line-height:20px;
}

here is link for reference codepen link

i have added margin to div element to make it visible.

hope this helps....


问:
Reasons for using Ant Properties files over "Properties Tasks"
I'm currently working with some developers who like to set up Ant tasks that define environment specific variables rather than using properties files.  It seems they prefer to do this because it's easier to type:

```<code>ant <environment task> dist
</code>```

Than it is to type:

```<code>ant -propertyfile <environment property file> dist
</code>```

So for example:

```<code><project name="whatever" default="dist">

<target name="local">
    <property name="webXml" value="WebContent/WEB-INF/web-local.xml"/>
</target>

<target name="remote">
    <property name="webXml" value="WebContent/WEB-INF/web-remote.xml"/>
</target>

<target name="build">
    <!-- build tasks here --->
</target>

<target name="dist" depends="build">
    <war destfile="/dist/foo.war" webxml="${webXml}">
         <!-- rest of war tasks here -->
    </war>
</target>
</code>```

I am finding it hard to convince them that properties files are they right way to go.  I believe properties files are better because:

They provides more flexibility - if you need a new environment just add a new properties file

It's clearer what's going on - You have to know about this little "trick" to realize what they're accomplishing

Doesn't provide default values and the ability to use overrides - if they used property files they could provide defaults at the top of the project but have the ability to override them with a file

Script won't break if an environment task isn't supplied on command line

Of course all they hear is that they need to change their Ant script and have to type more on the command line.

Can you provide any additional arguments in favor of properties files over "property tasks"?

答:
The arguments you have are already pretty compelling. If those arguments haven't worked, then arguing isn't going to solve the problem. In fact, nothing is going to solve the problem. Don't assume that people are rational and will do the most practical thing. Their egos are involved.

Stop arguing. Even if you win, the resentment and irritation you create will not be worth it. Winning an argument can be worse than losing.

Make your case, then let it go. It's possible that after a while they will decide to switch to your way (because it actually is better). If that happens, they will act like it was their own idea. There will be no mention of your having proposed it.

On the other hand, they may never switch.

The only solution is to work towards a position of authority, where you can say how things are to be done.

OwnerDisplayName: spilth

Body:
I'm currently working with some developers who like to set up Ant tasks that define environment specific variables rather than using properties files.  It seems they prefer to do this because it's easier to type:

ant <environment task> dist

Than it is to type:

ant -propertyfile <environment property file> dist

So for example:

<project name="whatever" default="dist">

<target name="local">
    <property name="webXml" value="WebContent/WEB-INF/web-local.xml"/>
</target>

<target name="remote">
    <property name="webXml" value="WebContent/WEB-INF/web-remote.xml"/>
</target>

<target name="build">

</target>

<target name="dist" depends="build">
    <war destfile="/dist/foo.war" webxml="${webXml}">

    </war>
</target>

I am finding it hard to convince them that properties files are they right way to go.  I believe properties files are better because:

They provides more flexibility - if you need a new environment just add a new properties file

It's clearer what's going on - You have to know about this little "trick" to realize what they're accomplishing

Doesn't provide default values and the ability to use overrides - if they used property files they could provide defaults at the top of the project but have the ability to override them with a file

Script won't break if an environment task isn't supplied on command line

Of course all they hear is that they need to change their Ant script and have to type more on the command line.

Can you provide any additional arguments in favor of properties files over "property tasks"?

OwnerDisplayName: Ethan


问:
How to create a wrapping table in GTK#
I'm trying to make a table of square buttons in GTK# with the following properties:

Buttons will be added and removed one at a time.

Buttons should be laid out like text on a page - left to right until no more can fit on a row, then wrapping onto the next row.

If there are more buttons than will fit in the window, there should be a vertical scroll-bar.

The table should be resizable. Resizing should reflow the buttons as necessary.

Buttons should be of fixed size.

I started off trying to use a Table with Homogenous==true. I added a handler for SizeAllocated and in it I check if the width of the table has changed enough to add or remove a column. If it has, I removed all the buttons, updated NColumns and re-attached the buttons in the correct places. This seemed to work, but the buttons were not fixed size - they would expand to fill the horizontal space.

Next I tried turning off Homogenous and setting preferred dimensions for the buttons. A minor problem is that ideally I want to put a known-size bitmap on each button, and I would like to get the layout correct regardless of how many pixels the button adds around the bitmap, but I'm not sure how to find out the total size of the buttons to do my calculations. A more serious problem is that my application now redraws inconsistently - sometimes the button labels are off-centre or not drawn at all. I am wondering if this is because I am changing the layout in response to the wrong signal.

How should I do this instead? Is Table the right container for the job? Is there something that will do what I want out of the box? (Perhaps something more akin to "icon" or "thumbnail" view in a file browser?)  What is the correct way to manipulate the layout of the window in response to changes in size?

答:
I don't believe that what you describe exists in GTK+. You might want to look into writing your own container widget though, it's not too difficult.

A good starting point might be this tutorial(link updated).

Title: How to create a wrapping table in GTK#


问:
JQuery can't get input value from dynamically created field
Receiving  value from static field when keyup based on input field class(.inputclass) method, but once add field dynamically its not get the value.

Below the sample code, Please help.

$(function(){
 $(document).ready(function(){
  $(".inputclass").keyup(function() {
     alert($(this).val());
  });
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
  <tr>
    <td>Field 1</td>
    <td><input type="text" class="inputclass" /></td>
  </tr>
  <script>
 var counter =1;
 $(function(){
  $('#addNew').click(function(){
   counter += 1;
   $('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
  });
 });
</script>
</table><br/>
<input type="button" id="addNew" value=" ± Add New Field"/>
</form></code>```

答:
$(function(){
 $(document).ready(function(){
    $(document).on('keyup', '.inputclass', function(){
     alert($(this).val());
  });
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
  <tr>
    <td>Field 1</td>
    <td><input type="text" class="inputclass" /></td>
  </tr>
  <script>
 var counter =1;
 $(function(){
  $('#addNew').click(function(){
   counter += 1;
   $('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
  });
 });
</script>
</table><br/>
<input type="button" id="addNew" value=" ± Add New Field"/>
</form></code>```

Body:
Receiving  value from static field when keyup based on input field class(.inputclass) method, but once add field dynamically its not get the value.

Below the sample code, Please help.

$(function(){
 $(document).ready(function(){
  $(".inputclass").keyup(function() {
     alert($(this).val());
  });
 });
});

<form>

    Field 1
    <input type="text" class="inputclass" />

<input type="button" id="addNew" value=" ± Add New Field"/>
</form>

Body:
$(function(){
 $(document).ready(function(){
    $(document).on('keyup', '.inputclass', function(){
     alert($(this).val());
  });
 });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
  <tr>
    <td>Field 1</td>
    <td><input type="text" class="inputclass" /></td>
  </tr>
  <script>
 var counter =1;
 $(function(){
  $('#addNew').click(function(){
   counter += 1;
   $('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
  });
 });
</script>
</table><br/>
<input type="button" id="addNew" value=" &plusmn; Add New Field"/>
</form>