问:
Cannot get rid of "An Authentication object was not found in the SecurityContext" in a Spring Boot application without @WithMockUser
I have spent a few whole days already trying to figure out what I'm doing wrong, but have no clue why it's not working. First of all, I would like to say that the following configuration is mostly copied from another projects I'm working on, and those projects can work without any issues (however they are configured slightly differently and use older Spring/Spring Boot versions). I cannot provide less code because I believe these classes are misconfigured and I'm unable to see a typo or whatever else in the following configuration classes. I would love to rewrite from scratch, but not this time. (Components whose names start with I are mine, not parts of the Spring Framework).

So the exception here is:

```<code>org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:379) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:223) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) ~[spring-aop-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at FOO.BAR.AuthenticationController$$EnhancerBySpringCGLIB$$b4949cda.getSelf(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at FOO.BAR.AbstractControllerTest.get(AbstractControllerTest.java:55) [web-test-0-SNAPSHOT.jar:na]
    at FOO.BAR.AuthenticationControllerOkTest.testAuthenticate(AuthenticationControllerOkTest.java:31) [test-classes/:na]
    <...JUnit stuff...>
</code>```

The only similar question I found in the Web is this one. But it seems to describe a slightly different case, if I'm not wrong. Worth nothing, of course: adding @WithMockUser to the tests does not cause the exception, but since I'm testing the authentication controller, I cannot use this annotation (and it's impossible in the production mode, of course).

AbstractCustomTypesGlobalMethodSecurityConfiguration

This is a boilerplate class I use to add some custom types support to @PreAuthorize. Pretty easy I think, and this one does not look suspicious:

public abstract class AbstractCustomTypesGlobalMethodSecurityConfiguration
        extends GlobalMethodSecurityConfiguration {

    @Nonnull
    protected abstract ApplicationContext applicationContext();

    @Nonnull
    protected abstract ConversionService conversionService();

    @Nonnull
    protected abstract PermissionEvaluator permissionEvaluator();

    @Nonnull
    @SuppressWarnings("DesignForExtension")
    protected Object filter(@Nonnull final MethodSecurityExpressionHandler handler, @Nonnull final Object filterTarget,
            @Nonnull final Expression filterExpression, @Nonnull final EvaluationContext context) {
        return handler.filter(filterTarget, filterExpression, context);
    }

    @Override
    protected final MethodSecurityExpressionHandler createExpressionHandler() {
        final ApplicationContext applicationContext = applicationContext();
        final TypeConverter typeConverter = new StandardTypeConverter(conversionService());
        final DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler() {
            @Override
            public StandardEvaluationContext createEvaluationContextInternal(final Authentication authentication, final MethodInvocation methodInvocation) {
                final StandardEvaluationContext decoratedStandardEvaluationContext = super.createEvaluationContextInternal(authentication, methodInvocation);
                return new ForwardingStandardEvaluationContext() {
                    @Override
                    protected StandardEvaluationContext standardEvaluationContext() {
                        return decoratedStandardEvaluationContext;
                    }

                    @Override
                    public TypeConverter getTypeConverter() {
                        return typeConverter;
                    }
                };
            }

            @Override
            public Object filter(final Object filterTarget, final Expression filterExpression, final EvaluationContext context) {
                return AbstractCustomTypesGlobalMethodSecurityConfiguration.this.filter(this, filterTarget, filterExpression, context);
            }
        };
        handler.setApplicationContext(applicationContext);
        handler.setPermissionEvaluator(permissionEvaluator());
        return handler;
    }

}
```

<h3>SecurityConfiguration</h3>

<p>Basically the following configuration just extends the latter configuration providing required beans using the template method design pattern. Nothing suspicious, I guess except <code>@EnableGlobalMethodSecurity</code>, however the annotation seems to work and enabling/disabling its flags affect the overall behavior too. (Moving the annotation to another configuration does not work either as it might work for some cases.)</p>

<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
class SecurityConfiguration
        extends AbstractCustomTypesGlobalMethodSecurityConfiguration {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ConversionService conversionService;

    @Nonnull
    @Override
    protected ApplicationContext applicationContext() {
        return applicationContext;
    }

    @Nonnull
    @Override
    protected ConversionService conversionService() {
        return conversionService;
    }

    @Nonnull
    @Override
    protected final PermissionEvaluator permissionEvaluator() {
        return getAlwaysPermittedPermissionEvaluator();
    }

    @Nonnull
    @Override
    protected final Object filter(@Nonnull final MethodSecurityExpressionHandler handler, @Nonnull final Object filterTarget,
            @Nonnull final Expression filterExpression, @Nonnull final EvaluationContext context) {
        final MethodSecurityExpressionOperations operations = (MethodSecurityExpressionOperations) context.getRootObject().getValue();
        operations.setFilterObject(filterTarget);
        return filterExpression.getValue(context, Object.class);
    }

}
</code>```

WebSecurityConfiguration

More or less trivial Web security configuration that defines some rules to access the service endpoints. Please note that the filter "beaned" with authenticationTokenProcessingFilter is not being invoked, because the exception occurs first.

@Configuration
@EnableWebSecurity
class WebSecurityConfiguration
        extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private ITokenAuthenticationService tokenAuthenticationService;

    @Override
    protected final void configure(final HttpSecurity httpSecurity)
            throws Exception {
        httpSecurity
                .authorizeRequests()
                .antMatchers(POST, "/api/v0/authentication").permitAll()
                .antMatchers("/api/v0/**").fullyAuthenticated()
                .antMatchers("/**").permitAll();
        httpSecurity
                .csrf().disable()
                .httpBasic()
                .authenticationEntryPoint(customAuthenticationEntryPoint());
        httpSecurity
                .sessionManagement()
                .sessionCreationPolicy(STATELESS);
        httpSecurity
                .addFilterBefore(authenticationTokenProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    AuthenticationEntryPoint customAuthenticationEntryPoint() {
        return getCustomAuthenticationEntryPoint();
    }

    @Bean
    GenericFilterBean authenticationTokenProcessingFilter() {
        return getAuthenticationTokenProcessingFilter(tokenAuthenticationService);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    void registerGlobalAuthentication(final AuthenticationManagerBuilder managerBuilder)
            throws Exception {
        managerBuilder
                .userDetailsService(userDetailsService)
                .and()
                .eraseCredentials(false);
    }

}
```

<p>That is pretty much and hopefully complete code that might require diagnostics, I think. It does not look broken or so, but I still cannot figure out the reason of why I'm getting the exception. I'm starting to feel my hair is becoming gray.</p>

<p>Any help is greatly appreciated!</p>

<p>Dependencies:</p>

<ul>
<li>org.springframework.boot:spring-boot-dependencies:1.4.3.RELEASE:pom</li>
<li>org.springframework.boot:spring-boot-starter-web:1.4.3.RELEASE</li>
<li>org.springframework.security:spring-security-config:4.2.1.RELEASE</li>
<li>org.springframework.security:spring-security-core:4.2.1.RELEASE</li>
<li>org.springframework.security:spring-security-web:4.2.1.RELEASE</li>
</ul>

<h2>Edit 1</h2>

<pre class="lang-java prettyprint-override"><code>@Test
@DatabaseSetup(DATASET)
// @WithMockUser is commented out -- we're authenticating as Alice ourselves to obtain the authentication token
public void testAuthenticate()
        throws Exception {
    final MockHttpServletResponse response = post("/authentication", asJson(), identityWithKeyGsonIncomingDto("Alice", "alice123"))
            // Here is where it fails: the exception causes HTTP 500 rather than HTTP 201
            .andExpect(status().isCreated())
            .andReturn()
            .getResponse();
    @SuppressWarnings("unchecked")
    final Map<String, Object> responseMap = gson.fromJson(response.getContentAsString(), Map.class);
    final String token = (String) responseMap.get("token");
    get("/users/self", headers("Authorization", token))
            .andExpect(status().isOk());
}
</code>```

Edit 2

public final class AuthenticationTokenProcessingFilter
        extends GenericFilterBean {

...

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {
        @Nullable
        final String authenticationToken = getAuthenticationToken(request);
        if ( authenticationToken != null ) {
            try {
                final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                final Authentication authentication = tokenAuthenticationService.authenticate(authenticationToken, httpServletRequest);
                setCurrentAuthentication(authentication);
            } catch ( final AuthenticationException ex ) {
                ...
            }
        }
        chain.doFilter(request, response);
    }

}
```

Unfortunately, the exception happens before the filter above can take control for some reason. Please note that this filter is intended to set current user authentication only under certain circumstances, but never -- anonymous. At least this is how it works in my other modules.

答:
I'm sorry that tons of code I provided do not reveal the real cause of the issue. After some more experiments with it I've been suggested to run the use case in production mode (I've forgotten it totally because of tests first), and it works in production mode without any issues. Narrowing down to the tests, I checked the tests annotations first to make sure that it has all annotations including @WithSecurityContextTestExecutionListener like what other modules have. And then I figured out that I missed a totally crucial thing: the smallest scope listeners can affect is a single test, and probably the mocked MVC object (MockMvc that I didn't include to the original question because I did believe it's just a configuration issue) is not configured well. And yes, MockMvc instances were initialized in the following way (a @Before method in one of the test super classes):

mvc = webAppContextSetup(webApplicationContext)
        .build();
```

<p>This is why it didn't work to me, because <code>MockMvc</code> instances must be configured as well.</p>

<pre class="lang-java prettyprint-override"><code>mvc = webAppContextSetup(webApplicationContext)
        .apply(springSecurity()) // this is the key
        .build();
</code>```

A good example of not trusting "annotations can do everything you need themselves". Unfortunately, I wasted a lot of time, but I'm glad I could finally find the very cause.

Body:
I have spent a few whole days already trying to figure out what I'm doing wrong, but have no clue why it's not working. First of all, I would like to say that the following configuration is mostly copied from another projects I'm working on, and those projects can work without any issues (however they are configured slightly differently and use older Spring/Spring Boot versions). I cannot provide less code because I believe these classes are misconfigured and I'm unable to see a typo or whatever else in the following configuration classes. I would love to rewrite from scratch, but not this time. (Components whose names start with I are mine, not parts of the Spring Framework).

So the exception here is:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:379) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:223) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65) ~[spring-security-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) ~[spring-aop-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at FOO.BAR.AuthenticationController$$EnhancerBySpringCGLIB$$b4949cda.getSelf(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
    at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at FOO.BAR.AbstractControllerTest.get(AbstractControllerTest.java:55) [web-test-0-SNAPSHOT.jar:na]
    at FOO.BAR.AuthenticationControllerOkTest.testAuthenticate(AuthenticationControllerOkTest.java:31) [test-classes/:na]
    <...JUnit stuff...>

The only similar question I found in the Web is this one. But it seems to describe a slightly different case, if I'm not wrong. Worth nothing, of course: adding @WithMockUser to the tests does not cause the exception, but since I'm testing the authentication controller, I cannot use this annotation (and it's impossible in the production mode, of course).

AbstractCustomTypesGlobalMethodSecurityConfiguration

This is a boilerplate class I use to add some custom types support to @PreAuthorize. Pretty easy I think, and this one does not look suspicious:

public abstract class AbstractCustomTypesGlobalMethodSecurityConfiguration
        extends GlobalMethodSecurityConfiguration {

    @Nonnull
    protected abstract ApplicationContext applicationContext();

    @Nonnull
    protected abstract ConversionService conversionService();

    @Nonnull
    protected abstract PermissionEvaluator permissionEvaluator();

    @Nonnull
    @SuppressWarnings("DesignForExtension")
    protected Object filter(@Nonnull final MethodSecurityExpressionHandler handler, @Nonnull final Object filterTarget,
            @Nonnull final Expression filterExpression, @Nonnull final EvaluationContext context) {
        return handler.filter(filterTarget, filterExpression, context);
    }

    @Override
    protected final MethodSecurityExpressionHandler createExpressionHandler() {
        final ApplicationContext applicationContext = applicationContext();
        final TypeConverter typeConverter = new StandardTypeConverter(conversionService());
        final DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler() {
            @Override
            public StandardEvaluationContext createEvaluationContextInternal(final Authentication authentication, final MethodInvocation methodInvocation) {
                final StandardEvaluationContext decoratedStandardEvaluationContext = super.createEvaluationContextInternal(authentication, methodInvocation);
                return new ForwardingStandardEvaluationContext() {
                    @Override
                    protected StandardEvaluationContext standardEvaluationContext() {
                        return decoratedStandardEvaluationContext;
                    }

                    @Override
                    public TypeConverter getTypeConverter() {
                        return typeConverter;
                    }
                };
            }

            @Override
            public Object filter(final Object filterTarget, final Expression filterExpression, final EvaluationContext context) {
                return AbstractCustomTypesGlobalMethodSecurityConfiguration.this.filter(this, filterTarget, filterExpression, context);
            }
        };
        handler.setApplicationContext(applicationContext);
        handler.setPermissionEvaluator(permissionEvaluator());
        return handler;
    }

}

SecurityConfiguration

Basically the following configuration just extends the latter configuration providing required beans using the template method design pattern. Nothing suspicious, I guess except @EnableGlobalMethodSecurity, however the annotation seems to work and enabling/disabling its flags affect the overall behavior too. (Moving the annotation to another configuration does not work either as it might work for some cases.)

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
class SecurityConfiguration
        extends AbstractCustomTypesGlobalMethodSecurityConfiguration {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ConversionService conversionService;

    @Nonnull
    @Override
    protected ApplicationContext applicationContext() {
        return applicationContext;
    }

    @Nonnull
    @Override
    protected ConversionService conversionService() {
        return conversionService;
    }

    @Nonnull
    @Override
    protected final PermissionEvaluator permissionEvaluator() {
        return getAlwaysPermittedPermissionEvaluator();
    }

    @Nonnull
    @Override
    protected final Object filter(@Nonnull final MethodSecurityExpressionHandler handler, @Nonnull final Object filterTarget,
            @Nonnull final Expression filterExpression, @Nonnull final EvaluationContext context) {
        final MethodSecurityExpressionOperations operations = (MethodSecurityExpressionOperations) context.getRootObject().getValue();
        operations.setFilterObject(filterTarget);
        return filterExpression.getValue(context, Object.class);
    }

}

WebSecurityConfiguration

More or less trivial Web security configuration that defines some rules to access the service endpoints. Please note that the filter "beaned" with authenticationTokenProcessingFilter is not being invoked, because the exception occurs first.

@Configuration
@EnableWebSecurity
class WebSecurityConfiguration
        extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private ITokenAuthenticationService tokenAuthenticationService;

    @Override
    protected final void configure(final HttpSecurity httpSecurity)
            throws Exception {
        httpSecurity
                .authorizeRequests()
                .antMatchers(POST, "/api/v0/authentication").permitAll()
                .antMatchers("/api/v0/**").fullyAuthenticated()
                .antMatchers("/**").permitAll();
        httpSecurity
                .csrf().disable()
                .httpBasic()
                .authenticationEntryPoint(customAuthenticationEntryPoint());
        httpSecurity
                .sessionManagement()
                .sessionCreationPolicy(STATELESS);
        httpSecurity
                .addFilterBefore(authenticationTokenProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    AuthenticationEntryPoint customAuthenticationEntryPoint() {
        return getCustomAuthenticationEntryPoint();
    }

    @Bean
    GenericFilterBean authenticationTokenProcessingFilter() {
        return getAuthenticationTokenProcessingFilter(tokenAuthenticationService);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    void registerGlobalAuthentication(final AuthenticationManagerBuilder managerBuilder)
            throws Exception {
        managerBuilder
                .userDetailsService(userDetailsService)
                .and()
                .eraseCredentials(false);
    }

}

That is pretty much and hopefully complete code that might require diagnostics, I think. It does not look broken or so, but I still cannot figure out the reason of why I'm getting the exception. I'm starting to feel my hair is becoming gray.

Any help is greatly appreciated!

Dependencies:

org.springframework.boot:spring-boot-dependencies:1.4.3.RELEASE:pom

org.springframework.boot:spring-boot-starter-web:1.4.3.RELEASE

org.springframework.security:spring-security-config:4.2.1.RELEASE

org.springframework.security:spring-security-core:4.2.1.RELEASE

org.springframework.security:spring-security-web:4.2.1.RELEASE

Edit 1

@Test
@DatabaseSetup(DATASET)
// @WithMockUser is commented out -- we're authenticating as Alice ourselves to obtain the authentication token
public void testAuthenticate()
        throws Exception {
    final MockHttpServletResponse response = post("/authentication", asJson(), identityWithKeyGsonIncomingDto("Alice", "alice123"))
            // Here is where it fails: the exception causes HTTP 500 rather than HTTP 201
            .andExpect(status().isCreated())
            .andReturn()
            .getResponse();
    @SuppressWarnings("unchecked")
    final Map<String, Object> responseMap = gson.fromJson(response.getContentAsString(), Map.class);
    final String token = (String) responseMap.get("token");
    get("/users/self", headers("Authorization", token))
            .andExpect(status().isOk());
}

Edit 2

public final class AuthenticationTokenProcessingFilter
        extends GenericFilterBean {

...

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {
        @Nullable
        final String authenticationToken = getAuthenticationToken(request);
        if ( authenticationToken != null ) {
            try {
                final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                final Authentication authentication = tokenAuthenticationService.authenticate(authenticationToken, httpServletRequest);
                setCurrentAuthentication(authentication);
            } catch ( final AuthenticationException ex ) {
                ...
            }
        }
        chain.doFilter(request, response);
    }

}

Unfortunately, the exception happens before the filter above can take control for some reason. Please note that this filter is intended to set current user authentication only under certain circumstances, but never -- anonymous. At least this is how it works in my other modules.

Body:
I'm sorry that tons of code I provided do not reveal the real cause of the issue. After some more experiments with it I've been suggested to run the use case in production mode (I've forgotten it totally because of tests first), and it works in production mode without any issues. Narrowing down to the tests, I checked the tests annotations first to make sure that it has all annotations including @WithSecurityContextTestExecutionListener like what other modules have. And then I figured out that I missed a totally crucial thing: the smallest scope listeners can affect is a single test, and probably the mocked MVC object (MockMvc that I didn't include to the original question because I did believe it's just a configuration issue) is not configured well. And yes, MockMvc instances were initialized in the following way (a @Before method in one of the test super classes):

mvc = webAppContextSetup(webApplicationContext)
        .build();

This is why it didn't work to me, because MockMvc instances must be configured as well.

mvc = webAppContextSetup(webApplicationContext)
        .apply(springSecurity()) // this is the key
        .build();

A good example of not trusting "annotations can do everything you need themselves". Unfortunately, I wasted a lot of time, but I'm glad I could finally find the very cause.


来源: stackexchange

问:
Show/Hide events on fullcalendar using javascript
I'm making a religious calendar for a project that shows different events for all major religions. I'm using full calendar, and I have a "religion key" at the top of the calendar, and I want to make it so that when I click, for example, Jewish, it will hide all religious events/holidays on the calendar that don't pertain to the Jewish faith. I'm having some trouble. My thinking was that I would set the ".fc-event" class in css to display:none" and then have a class called .show that would be display:block. and toggle that class / remove that class when the user clicks the menu item that pertains to the holiday. Is there a better / easier way to do this? would love some guidance/tips/help :) thank you.

Here is my code for the calendar js (using made up dates obviously):

```<code>events: [
        {
            title: 'xmas',
            start: '2017-03-19',
            className: 'catholic show',
            description: 'blablablablabla'
        },
        {
            title: 'Hanukkah',
            start: '2017-03-19',
            className: 'jewish show',
            description: 'blablablabla'
        },
        {
            title: 'Hindu Holiday',
            start: '2017-03-24',
            end: '2017-03-27',
            className: 'hindu show',
            description: 'blablablabla'
        }
    ]
});

$('.calendar-nav a').each(function() {

    $(this).on('click', function(e) {
        e.preventDefault();

        var x = $(this).attr('rel');

        $('.fc-event-container').each(function() {

            $(this).removeClass('show');

            if($(this).hasClass(x)) {

                $(this).addClass('show');
            }
        });
    })
});

$('.show-all a').on('click', function() {
    $('.fc-event-container').each(function() {
        if(!$(this).hasClass('show')) {
            $(this).toggleClass('show');
        }
    });
});
});
</code>```

And the php code for the calendar and calendar-key:

```<code><nav class="calendar-nav">
<ul class="menu">
    <li class="christianity-text"><a href="#" rel="christian">><img src="/images/calendar/christianity.png" />CHRISTIAN</a>
        <ul class="sub-menu">
            <li><a href="#">Catholic</a></li>
            <li><a href="#">Protestant</a></li>
            <li><a href="#">Coptic</a></li>
            <li><a href="#">Mormon</a></li>
            <li><a href="#">Neo</a></li>
            <li><a href="#">Anglican</a></li>
            <li><a href="#">Celtic</a></li>
            <li><a href="#">Jehova's Witness</a></li>
        </ul>
    </li>
    <li class="buddhist-text"><a  href="#" rel="buddhist"><img src="/images/calendar/buddhism.png" />BUDDHIST</a></li>
    <li class="hindu-text"><a  href="#" rel="hindu"><img src="/images/calendar/hindu.png" />HINDU</a></li>
    <li class="jewish-text"><a  href="#" rel="jewish"><img src="/images/calendar/jewish.png" />JEWISH</a></li>
    <li class="islam-text"><a  href="#" rel="islam"><img src="/images/calendar/islam.png" />ISLAM</a></li>
    <li class="sikh-text"><a  href="#" rel="sikh"><img src="/images/calendar/sikh.png" />SIKH</a></li>

    <li class="pagan-text"><a  href="#" rel="pagan"><img src="/images/calendar/pagan.png" />PAGAN</a></li>
    <li class="wiccan-text"><a  href="#" rel="wiccan"><img src="/images/calendar/wiccan.png" />WICCAN</a></li>
    <li class="other-text"><a  href="#" rel="other"><img src="/images/calendar/other.png" />OTHER</a></li>
    <li class="all-text"><a href="#" rel="all">ALL</a></li>
</ul>
</nav>

<div id='calendar'></div>
</code>```

答:
Another solution could be add a custom attribute 'religion' to events and save it to the database. Fetch the events from the database which has the religion that you want to show:

JavaScript:

```<code>...
$.ajax({
        url: 'process.php',
        type: 'POST',
        data: 'religion=1",
        async: false,
        success: function(response){
            json_events = response;

        }
});
$(#calendar).fullCalendar({
    events: JSON.parse(JSON.stringify(json_events)),

});
</code>```

process.php

```<code>$religion = $_POST['religion'];
$query = "SELECT * FROM calendar WHERE religion='$religion'";
...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm making a religious calendar for a project that shows different events for all major religions. I'm using full calendar, and I have a "religion key" at the top of the calendar, and I want to make it so that when I click, for example, Jewish, it will hide all religious events/holidays on the calendar that don't pertain to the Jewish faith. I'm having some trouble. My thinking was that I would set the ".fc-event" class in css to display:none" and then have a class called .show that would be display:block. and toggle that class / remove that class when the user clicks the menu item that pertains to the holiday. Is there a better / easier way to do this? would love some guidance/tips/help :) thank you.

Here is my code for the calendar js (using made up dates obviously):

events: [
        {
            title: 'xmas',
            start: '2017-03-19',
            className: 'catholic show',
            description: 'blablablablabla'
        },
        {
            title: 'Hanukkah',
            start: '2017-03-19',
            className: 'jewish show',
            description: 'blablablabla'
        },
        {
            title: 'Hindu Holiday',
            start: '2017-03-24',
            end: '2017-03-27',
            className: 'hindu show',
            description: 'blablablabla'
        }
    ]
});

$('.calendar-nav a').each(function() {

    $(this).on('click', function(e) {
        e.preventDefault();

        var x = $(this).attr('rel');

        $('.fc-event-container').each(function() {

            $(this).removeClass('show');

            if($(this).hasClass(x)) {

                $(this).addClass('show');
            }
        });
    })
});

$('.show-all a').on('click', function() {
    $('.fc-event-container').each(function() {
        if(!$(this).hasClass('show')) {
            $(this).toggleClass('show');
        }
    });
});
});

And the php code for the calendar and calendar-key:

>CHRISTIAN

Catholic

Protestant

Coptic

Mormon

Neo

Anglican

Celtic

Jehova's Witness

BUDDHIST

HINDU

JEWISH

ISLAM

SIKH

PAGAN

WICCAN

OTHER

ALL

Body:
Another solution could be add a custom attribute 'religion' to events and save it to the database. Fetch the events from the database which has the religion that you want to show:

JavaScript:

...
$.ajax({
        url: 'process.php',
        type: 'POST',
        data: 'religion=1",
        async: false,
        success: function(response){
            json_events = response;

        }
});
$(#calendar).fullCalendar({
    events: JSON.parse(JSON.stringify(json_events)),

});

process.php

$religion = $_POST['religion'];
$query = "SELECT * FROM calendar WHERE religion='$religion'";
...


问:
Is it possible to name play evolution sql scripts?
evolution sql scripts should be named

1.sql,

2.sql,

XXX.sql

according to documentation.
https://www.playframework.com/documentation/2.5.x/Evolutions#Running-evolutions-using-compile-time-DI

Is there any possibility to change naming convention to

1_create__customers.sql

2_create__orders.sql

3_alter__customers__add__home_address.sql

like it RoR:
http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration

Yes, I evaluated https://github.com/flyway/flyway-play
and we can switch to it.

Right now I'm looking for default play functionality.

答:
No, it's not possible, the source code:

```<code>def fileName(db: String, revision: Int): String = s"${directoryName(db)}/${revision}.sql"
</code>```

https://github.com/playframework/playframework/blob/2.5.x/framework/src/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala#L103

```<code>def resourceName(db: String, revision: Int): String = s"evolutions/${db}/${revision}.sql"
</code>```

https://github.com/playframework/playframework/blob/2.5.x/framework/src/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala#L108

```<code>@Singleton
class EnvironmentEvolutionsReader @Inject() (environment: Environment) extends ResourceEvolutionsReader {

  def loadResource(db: String, revision: Int) = {
    environment.getExistingFile(Evolutions.fileName(db, revision)).map(new FileInputStream(_)).orElse {
      environment.resourceAsStream(Evolutions.resourceName(db, revision))
    }
  }
}
</code>```

https://github.com/playframework/playframework/blob/2.5.x/framework/src/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala#L471-L479

So, as it describet in the documentation, you can only use the number {revision}.sql

Body:
No, it's not possible, the source code:

def fileName(db: String, revision: Int): String = s"${directoryName(db)}/${revision}.sql"

https://github.com/playframework/playframework/blob/2.5.x/framework/src/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala#L103

def resourceName(db: String, revision: Int): String = s"evolutions/${db}/${revision}.sql"

https://github.com/playframework/playframework/blob/2.5.x/framework/src/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala#L108

@Singleton
class EnvironmentEvolutionsReader @Inject() (environment: Environment) extends ResourceEvolutionsReader {

  def loadResource(db: String, revision: Int) = {
    environment.getExistingFile(Evolutions.fileName(db, revision)).map(new FileInputStream(_)).orElse {
      environment.resourceAsStream(Evolutions.resourceName(db, revision))
    }
  }
}

https://github.com/playframework/playframework/blob/2.5.x/framework/src/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala#L471-L479

So, as it describet in the documentation, you can only use the number {revision}.sql


问:
Infinite $digest() loop AngularJS with filter expression on html attribute
When I try to pass a filter expression inside a component's attribute, e.g. (see this Plunker example as well, and the possible solutions listed below).

```<code><todo-list todos="$ctrl.todos | filter:{type:1}"></todo-list>
</code>```

I get an error on the infinite digest loop, I don't understand why:

```<code>Error: [$rootScope:infdig] http://errors.angularjs.org/1.6.3/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…e%2C%22type%22%3A1%2C%22%24%24hashKey%22%3A%22object%3A5%22%7D%5D%7D%5D%5D
    at eval (angular.js:38)
    at m.$digest (angular.js:18048)
    at m.$apply (angular.js:18280)
    at eval (angular.js:1912)
    at Object.invoke (angular.js:5003)
    at c (angular.js:1910)
    at Object.Pc [as bootstrap] (angular.js:1930)
    at execute (VM877 main.ts!transpiled:21)
    at f (system.js:5)
    at Object.execute (system.js:5)
</code>```

Code, see Plnkr: http://plnkr.co/edit/JdiLEIyji2pHd3eeNMUL?p=preview

Screenshot / Image:

Workaround/solution:
I have several workarounds/solutions:

In the repo where I had the problem at first: I did <todo-list todo-items="$ctrl.todoItems" filter-by="{completed:true}"></todo-list>. For full source see here: https://github.com/aredfox/todo-angularjs-typescript/commit/e71900b96173b63ebcebb8e6c1fba00fe3997971. But I feel it's working around the problem, plus I don't understand why this triggers a $digest() cycle and why it shouldn't just work.

Answer by @Mistalis https://stackoverflow.com/a/43120388/1155847 whogave a somehwat similar solution.

答:
There's an open issue at the angular.js repo you can follow up on in order to see the evolution regarding this problem:
https://github.com/angular/angular.js/issues/14039

As a temporary solution, you could change your binding to use a shallow two way binding by changing < to =* as mentioned here: https://github.com/angular/angular.js/issues/14039#issue-133588717
Il8PNgcE?p=preview

Body:
When I try to pass a filter expression inside a component's attribute, e.g. (see this Plunker example as well, and the possible solutions listed below).

<todo-list todos="$ctrl.todos | filter:{type:1}"></todo-list>

I get an error on the infinite digest loop, I don't understand why:

Error: [$rootScope:infdig] http://errors.angularjs.org/1.6.3/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…e%2C%22type%22%3A1%2C%22%24%24hashKey%22%3A%22object%3A5%22%7D%5D%7D%5D%5D
    at eval (angular.js:38)
    at m.$digest (angular.js:18048)
    at m.$apply (angular.js:18280)
    at eval (angular.js:1912)
    at Object.invoke (angular.js:5003)
    at c (angular.js:1910)
    at Object.Pc [as bootstrap] (angular.js:1930)
    at execute (VM877 main.ts!transpiled:21)
    at f (system.js:5)
    at Object.execute (system.js:5)

Code, see Plnkr: http://plnkr.co/edit/JdiLEIyji2pHd3eeNMUL?p=preview

Screenshot / Image:

Workaround/solution:
I have several workarounds/solutions:

In the repo where I had the problem at first: I did <todo-list todo-items="$ctrl.todoItems" filter-by="{completed:true}"></todo-list>. For full source see here: https://github.com/aredfox/todo-angularjs-typescript/commit/e71900b96173b63ebcebb8e6c1fba00fe3997971. But I feel it's working around the problem, plus I don't understand why this triggers a $digest() cycle and why it shouldn't just work.

Answer by @Mistalis https://stackoverflow.com/a/43120388/1155847 whogave a somehwat similar solution.


问:
When to read a .properties file in a Java Web Application
I'm developing a web application using Java EE6 and JSF 2.0. I have a .properties file in which I am storing a few constants, which I need to change easily before deploying the app. I know how to read a properties file, but the question is when?

This is the class I'm using to access the properties called CLIENT_ID and CLIENT_SECRET:

```<code>public class FConnectProperties {

    Properties properties;

    public FConnectProperties() throws FileNotFoundException, IOException{
        properties = new Properties();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream stream = classLoader.getResourceAsStream("/FConnect/FConnect.properties");
        properties.load(stream);
        stream.close();
    }

    public String getClientID(){
        return properties.getProperty("CLIENT_ID");
    }

    public String getClientSecret(){
        return properties.getProperty("CLIENT_SECRET");
    }
</code>```

Since this class reads the properties file from disk, is it ok to instantiate it every time I need to access them? Or should I instantiate it once during application startup, (possibly from a Singleton Bean) and access it from there? What is the best way to go about doing this?

The properties don't change once the application is launched. I'm only reading them, never updating them.

答:
I would suggest reading the file once at startup, and as you say holding them in a singleton. Since I'm guessing your properties are a selection of key/value pairs, that aren't all that large, I'd say they should do well in a map-type data structure.

Depending on how often you need to access them, then reading them from disk could become costly.

ContentLicense: CC BY-SA 2.5

Body:
I'm developing a web application using Java EE6 and JSF 2.0. I have a .properties file in which I am storing a few constants, which I need to change easily before deploying the app. I know how to read a properties file, but the question is when?

This is the class I'm using to access the properties called CLIENT_ID and CLIENT_SECRET:

public class FConnectProperties {

    Properties properties;

    public FConnectProperties() throws FileNotFoundException, IOException{
        properties = new Properties();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream stream = classLoader.getResourceAsStream("/FConnect/FConnect.properties");
        properties.load(stream);
        stream.close();
    }

    public String getClientID(){
        return properties.getProperty("CLIENT_ID");
    }

    public String getClientSecret(){
        return properties.getProperty("CLIENT_SECRET");
    }

Since this class reads the properties file from disk, is it ok to instantiate it every time I need to access them? Or should I instantiate it once during application startup, (possibly from a Singleton Bean) and access it from there? What is the best way to go about doing this?

The properties don't change once the application is launched. I'm only reading them, never updating them.


问:
Javascript / jQuery how to filter object with retaining its keys?
I want to have something like this: getting another object without some properties. I already have a working solution:

```<code>var s = {
 a: 3,
 b: 2,
 c: -1,
 d: 8,
 e: -1
};

var f = {};
jQuery.map(s, function(v,k) {
    if (v != -1)
    {
        f[k] = v;
    }
});

output is:
     a: 3,
     b: 2,
     d: 8,
</code>```

its fine but isnt there more simpler sollution? Maybe with jQuery but neither .map, .filter, .grep methods helped me so far!

答:
This may help</p>

```<code>var s = {
 a: 3,
 b: 2,
 c: -1,
 d: 8,
 e: -1
};
for(var k in s){
  if(s[k] == -1){
    delete(s[k]);
  }
}
console.log(s);
</code>```

Body:
I want to have something like this: getting another object without some properties. I already have a working solution:

var s = {
 a: 3,
 b: 2,
 c: -1,
 d: 8,
 e: -1
};

var f = {};
jQuery.map(s, function(v,k) {
    if (v != -1)
    {
        f[k] = v;
    }
});

output is:
     a: 3,
     b: 2,
     d: 8,

its fine but isnt there more simpler sollution? Maybe with jQuery but neither .map, .filter, .grep methods helped me so far!

Body:
This may help

var s = {
 a: 3,
 b: 2,
 c: -1,
 d: 8,
 e: -1
};
for(var k in s){
  if(s[k] == -1){
    delete(s[k]);
  }
}
console.log(s);


问:
Laravel: How to change default login error message: 'these credentials do not match our records'
I want to change the default login validation error message like:

```<code>Username & Password doesn't match
</code>```

instead of

```<code>these credentials do not match our records
</code>```

How to do this ?

答:
do one thing make new file message.php in lang folder then enter the error message in that and access in the controller and where you want to use like this
in Authonticateduser.php

```<code>protected function sendLoginResponse(Request $request) {
    $request->session()->regenerate();
    $this->clearLoginAttempts($request);
    return $this->authenticated($request, $this->guard()->user())
            ? : redirect()->intended($this->redirectPath())->with('status', Lang::get('messege.login_success'));
}
</code>```

and you get the perfect mesege you want instead of system mesege and without any change in default message.

Body:
I want to change the default login validation error message like:

Username & Password doesn't match

instead of

these credentials do not match our records

How to do this ?

Body:
do one thing make new file message.php in lang folder then enter the error message in that and access in the controller and where you want to use like this
in Authonticateduser.php

protected function sendLoginResponse(Request $request) {
    $request->session()->regenerate();
    $this->clearLoginAttempts($request);
    return $this->authenticated($request, $this->guard()->user())
            ? : redirect()->intended($this->redirectPath())->with('status', Lang::get('messege.login_success'));
}

and you get the perfect mesege you want instead of system mesege and without any change in default message.


问:
Powershell Export-CSV error
Just wondered if you can help me please.  I receive the following error:

```<code>Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.
At C:\PSScripts\CompassADStaff.ps1:33 char:20
+ $Staff | Export-Csv <<<<  CompassADStaff.csv -NoTypeInformation
+ CategoryInfo          : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand
</code>```

My code seems OK but I can't seem to detect why export-csv generates the above error:

```<code>Import-Module ActiveDirectory

#-------- Object variables ----------------------------------------------

#OU's to search
$searchbase = "ou=staff1,ou=users,dc=home,dc=local","ou=staff2,ou=users,dc=home,dc=local"

$Staff = @()

#------------------------------------------------------------------------

foreach ($ou in $searchbase) {
$Staff += get-aduser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" -SearchBase $ou -properties * | select-object employeeID,givenName,sn,sAMAccountName,mail
}
$Staff | Export-Csv CompassADStaff.csv -NoTypeInformation
</code>```

Any help or pointers would be great :)

Thanks

答:
This consistently resolved the same problem for me:</p>

```<code>$Staff | Where {$_} | Export-Csv CompassADStaff.csv -NoTypeInformation
</code>```

Title: Powershell Export-CSV error

Body:
Just wondered if you can help me please.  I receive the following error:

Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.
At C:\PSScripts\CompassADStaff.ps1:33 char:20
+ $Staff | Export-Csv <<<<  CompassADStaff.csv -NoTypeInformation
+ CategoryInfo          : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand

My code seems OK but I can't seem to detect why export-csv generates the above error:

Import-Module ActiveDirectory

#-------- Object variables ----------------------------------------------

#OU's to search
$searchbase = "ou=staff1,ou=users,dc=home,dc=local","ou=staff2,ou=users,dc=home,dc=local"

$Staff = @()

#------------------------------------------------------------------------

foreach ($ou in $searchbase) {
$Staff += get-aduser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" -SearchBase $ou -properties * | select-object employeeID,givenName,sn,sAMAccountName,mail
}
$Staff | Export-Csv CompassADStaff.csv -NoTypeInformation

Any help or pointers would be great :)

Thanks

Body:
This consistently resolved the same problem for me:

$Staff | Where {$_} | Export-Csv CompassADStaff.csv -NoTypeInformation


答:
You can so something like this

var s = {
 a: 3,
 b: 2,
 c: -1,
 d: 8,
 e: -1
};

for (var property in s) {
    if (s[property]!=-1) {
      console.log(property+":"+s[property]);
    }
}```

Title: Javascript / jQuery how to filter object with retaining its keys?


答:
You could use delete operator for deleting a property of an object.

var s = { a: 3, b: 2, c: -1, d: 8, e: -1 }

Object.keys(s).forEach(function (k) {
    if (s[k] === -1) {
        delete s[k];
    }
});
console.log(s);```


问:
Is this recommended to use private static Dictionary<string, string> for caching?
I am using a private and static, Dictionary to cache the menu name.

```<code>private static Dictionary<string, string> menuItemCache = new Dictionary<string, string>();
</code>```

and the cache is updated by my [POST] action method for any new menu item added. And the dictionary is holding menu names all the time, and are being consumed by other [GET] action methods.

My question is about using static dictionary instead of any other caching technique, if it is recommended to do so.

答:
You should be very careful with static variables. Static variables are shared across all sessions. If you intend to keep a cache per-user, you should use the Session object instead.

On itself, there is nothing wrong in keeping a cache stored in a dictionary. The dictionary has fast lookups, so when using a dictionary over a list you will probably benefit from that performance-wise.

Body:
I am using a private and static, Dictionary to cache the menu name.

private static Dictionary<string, string> menuItemCache = new Dictionary<string, string>();

and the cache is updated by my [POST] action method for any new menu item added. And the dictionary is holding menu names all the time, and are being consumed by other [GET] action methods.

My question is about using static dictionary instead of any other caching technique, if it is recommended to do so.


问:
UNET Client Cant Send Server Commands, Host Can
So as the title suggests, I'm having a problem where commands being sent by the client are not triggered.

The basic functionality I'm trying to get working is that when an enemy is in front of the player and I click, that player will be momentarily stunned. Works fine if I'm host, and both sides perfectly register.

If I'm playing as client, I get to the point where the command "should" be sent, but I notice I get a warning that says "Trying to send command for non-local player". As well, nothing happens on either end. Obviously I must be doing something wrong client side, but have no idea what other way to go about this.

The "problem" code.

```<code>            if (Input.GetButtonDown("Fire1")) {
            Ray ray = new Ray(transform.position, transform.forward);
            RaycastHit hit = new RaycastHit();
            Physics.Raycast(ray, out hit, 20f);
            if (hit.transform != null) {
                if (hit.rigidbody != null) {
                    PlayerController controller = hit.rigidbody.GetComponent<PlayerController>();
                    if (controller != null) {
                        if (!controller.stunned) {
                            // Send the stun command to the server
                            controller.CmdStun();
                        }
                    }
                }
            }
        }
</code>```

The method calls

```<code>[Command]
public void CmdStun() {
    // Report that the stun was sent
    UnityEngine.Debug.Log("Stun Sent");
    RpcStun();
}

[ClientRpc]
public void RpcStun() {
    // Activate the stun timer.
    stunTimer.Start();
    // Track the players original color.
    normalColor = manager.color;
    // Make the players bot look like its shut down.
    manager.InitiateColorChange(Color.black);
    // Other code will check against this before trying to send another stun command.
    stunned = true;
}
</code>```

Edit:
Upon request heres the two scripts in their entirety.

http://pastebin.com/mr4A9ZgH

http://pastebin.com/Qg0AjCCD

Player configuration in unity:

https://gyazo.com/400c5b3a95c1a58f9b6e930b0c3c853b

https://gyazo.com/c17a7317767a00e2150ff34b03a03e8f

https://gyazo.com/322731aefbe69f9567d2b395523b8f2a

Full Warning Message

Trying to send command for non-local player.
  UnityEngine.Networking.NetworkBehaviour:SendCommandInternal(NetworkWriter,
  Int32, String) PlayerController:CallCmdStun()
  ObjectInteractor:Update() (at Assets/Scripts/ObjectInteractor.cs:58)

答:
As you said:

warning that says "Trying to send command for non-local player".

You can send commands from non-player objects as unity docs stated:

Commands are sent from player objects on the client to player objects
  on the server. For security, Commands can only be sent from YOUR
  player object, so you cannot control the objects of other players.

BUT

Starting with Unity release 5.2 it is possible to send commands from
  non-player objects that have client authority. These objects must have
  been spawned with NetworkServer.SpawnWithClientAuthority or have
  authority set with NetworkIdentity.AssignClientAuthority. Commands
  sent from these object are run on the server instance of the object,
  not on the associated player object for the client.

Body:
So as the title suggests, I'm having a problem where commands being sent by the client are not triggered.

The basic functionality I'm trying to get working is that when an enemy is in front of the player and I click, that player will be momentarily stunned. Works fine if I'm host, and both sides perfectly register.

If I'm playing as client, I get to the point where the command "should" be sent, but I notice I get a warning that says "Trying to send command for non-local player". As well, nothing happens on either end. Obviously I must be doing something wrong client side, but have no idea what other way to go about this.

The "problem" code.

            if (Input.GetButtonDown("Fire1")) {
            Ray ray = new Ray(transform.position, transform.forward);
            RaycastHit hit = new RaycastHit();
            Physics.Raycast(ray, out hit, 20f);
            if (hit.transform != null) {
                if (hit.rigidbody != null) {
                    PlayerController controller = hit.rigidbody.GetComponent<PlayerController>();
                    if (controller != null) {
                        if (!controller.stunned) {
                            // Send the stun command to the server
                            controller.CmdStun();
                        }
                    }
                }
            }
        }

The method calls

[Command]
public void CmdStun() {
    // Report that the stun was sent
    UnityEngine.Debug.Log("Stun Sent");
    RpcStun();
}

[ClientRpc]
public void RpcStun() {
    // Activate the stun timer.
    stunTimer.Start();
    // Track the players original color.
    normalColor = manager.color;
    // Make the players bot look like its shut down.
    manager.InitiateColorChange(Color.black);
    // Other code will check against this before trying to send another stun command.
    stunned = true;
}

Edit:
Upon request heres the two scripts in their entirety.

http://pastebin.com/mr4A9ZgH

http://pastebin.com/Qg0AjCCD

Player configuration in unity:

https://gyazo.com/400c5b3a95c1a58f9b6e930b0c3c853b

https://gyazo.com/c17a7317767a00e2150ff34b03a03e8f

https://gyazo.com/322731aefbe69f9567d2b395523b8f2a

Full Warning Message

Trying to send command for non-local player.
  UnityEngine.Networking.NetworkBehaviour:SendCommandInternal(NetworkWriter,
  Int32, String) PlayerController:CallCmdStun()
  ObjectInteractor:Update() (at Assets/Scripts/ObjectInteractor.cs:58)


问:
Android DatePicker dialog, date should come from tomorrow
```<code> Calendar calender = Calendar.getInstance();
    final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(LabCheckOutActivity.this,
    myDateListener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
    calender.get(Calendar.DAY_OF_MONTH)+1);
    pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
    pickerDialog.show();
</code>```

by Using this code, in dialog date is pointed to tomorrow but user can also select todays date.I want user can select date from tomorrow not today.

public class CustomDatePickerDialog extends DatePickerDialog {

```<code>int maxYear;
int maxMonth;
int maxDay;

public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
    super(context, callBack, year, monthOfYear, dayOfMonth);
}

public void setMaxDate(long maxDate) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getDatePicker().setMaxDate(System.currentTimeMillis());
    } else {
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(maxDate);
        maxYear = c.get(Calendar.YEAR);
        maxMonth = c.get(Calendar.MONTH);
        maxDay = c.get(Calendar.DAY_OF_MONTH);
    }
}

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        super.onDateChanged(view, year, monthOfYear, dayOfMonth);
    } else {
        if (year > maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (monthOfYear > maxMonth && year == maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
            view.updateDate(maxYear, maxMonth, maxDay);
    }
}

}
</code>```

答:
Use

```<code>pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()+24*60*60*1000);//where 24*60*60*1000 represents the total timestamp for one day
</code>```

instead of

```<code>  pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
 Calendar calender = Calendar.getInstance();
    final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(LabCheckOutActivity.this,
    myDateListener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
    calender.get(Calendar.DAY_OF_MONTH)+1);
    pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
    pickerDialog.show();

by Using this code, in dialog date is pointed to tomorrow but user can also select todays date.I want user can select date from tomorrow not today.

public class CustomDatePickerDialog extends DatePickerDialog {

int maxYear;
int maxMonth;
int maxDay;

public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
    super(context, callBack, year, monthOfYear, dayOfMonth);
}

public void setMaxDate(long maxDate) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getDatePicker().setMaxDate(System.currentTimeMillis());
    } else {
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(maxDate);
        maxYear = c.get(Calendar.YEAR);
        maxMonth = c.get(Calendar.MONTH);
        maxDay = c.get(Calendar.DAY_OF_MONTH);
    }
}

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        super.onDateChanged(view, year, monthOfYear, dayOfMonth);
    } else {
        if (year > maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (monthOfYear > maxMonth && year == maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
            view.updateDate(maxYear, maxMonth, maxDay);
    }
}

}

Body:
Use

pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()+24*60*60*1000);//where 24*60*60*1000 represents the total timestamp for one day

instead of

  pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);


问:
How can I schedule code to run every few hours in Elixir or Phoenix framework?
So let's say I want to send a bunch of emails or recreate sitemap or whatever every 4 hours, how would I do that in Phoenix or just with Elixir? </p>

答:
I used Quantum library Quantum- Elixir.

Follow below instructions.

#your_app/mix.exs
defp deps do
  [{:quantum, ">= 1.9.1"},
  #rest code
end

#your_app/mix.exs
def application do
  [mod: {AppName, []},
   applications: [:quantum,
   #rest code
 ]]
end

#your_app/config/dev.exs
config :quantum, :your_app, cron: [
  # Every minute
  "* * * * *": fn -> IO.puts("Hello QUANTUM!") end
]
```

<p>All set. Start the server by running below command.</p>

<pre class="lang-ex prettyprint-override"><code>iex -S mix phoenix.server
</code>```

Body:
I used Quantum library Quantum- Elixir.

Follow below instructions.

#your_app/mix.exs
defp deps do
  [{:quantum, ">= 1.9.1"},
  #rest code
end

#your_app/mix.exs
def application do
  [mod: {AppName, []},
   applications: [:quantum,
   #rest code
 ]]
end

#your_app/config/dev.exs
config :quantum, :your_app, cron: [
  # Every minute
  "* * * * *": fn -> IO.puts("Hello QUANTUM!") end
]

All set. Start the server by running below command.

iex -S mix phoenix.server


问:
Jquery chekbox select all except disabled
I have this jsp code as a header to toggle all checkbox:

```<code><th><input name="checkAll" type="checkbox" onClick="toggleCheck(this, this.form.poFulfill);"/></th>
</code>```

Each row reads the record whether that checkbox will be disabled or not:

```<code><input type="checkbox" name="poFulfill" value='<%=row.poId.toString()%>'
<%=(row.qtyIn.compareTo(row.qtyOut) == 0))?"disabled":""%>>
</code>```

I want to select all checkbox that is ENABLED only.  I read I need to use jquery so I modified my header to:

```<code><th><input id="chkSelectAll" name="checkAll" type="checkbox"/></th>
</code>```

And added this:

```<code><script type="text/javascript">
$('#chkSelectAll').click(function () {
var checked_status = this.checked;
$('div#item input[type=checkbox]').not(":disabled").prop("checked", checked_status);
});
</script>
</code>```

Not working and nothing happens when I click checkbox to select all.  Any idea?

答:
$('#chkSelectAll').click(function () {
var checked_status = this.checked;
$('div#item input[type=checkbox]:enabled').prop("checked", checked_status);
});```
<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>

<th><input id="chkSelectAll" name="checkAll" type="checkbox"/>check all</th>
<br/>
<br/>
<div id='item'>
<th><input id="chk1" name="chk1" type="checkbox" disabled/>abc</th><br/>
<th><input id="chk2" name="chk2" type="checkbox"/>a</th><br/>
<th><input id="chk4" name="chk4" type="checkbox"/>b</th><br/>
<th><input id="chk5" name="chk5" type="checkbox" disabled/>c</th><br/>
<th><input id="chk6" name="chk6" type="checkbox"/>d</th>
</div></code>```

Body:
I have this jsp code as a header to toggle all checkbox:

<input name="checkAll" type="checkbox" onClick="toggleCheck(this, this.form.poFulfill);"/>

Each row reads the record whether that checkbox will be disabled or not:

<input type="checkbox" name="poFulfill" value='<%=row.poId.toString()%>'
<%=(row.qtyIn.compareTo(row.qtyOut) == 0))?"disabled":""%>>

I want to select all checkbox that is ENABLED only.  I read I need to use jquery so I modified my header to:

<input id="chkSelectAll" name="checkAll" type="checkbox"/>

And added this:

Not working and nothing happens when I click checkbox to select all.  Any idea?

Body:
$('#chkSelectAll').click(function () {
var checked_status = this.checked;
$('div#item input[type=checkbox]:enabled').prop("checked", checked_status);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<th><input id="chkSelectAll" name="checkAll" type="checkbox"/>check all</th>
<br/>
<br/>
<div id='item'>
<th><input id="chk1" name="chk1" type="checkbox" disabled/>abc</th><br/>
<th><input id="chk2" name="chk2" type="checkbox"/>a</th><br/>
<th><input id="chk4" name="chk4" type="checkbox"/>b</th><br/>
<th><input id="chk5" name="chk5" type="checkbox" disabled/>c</th><br/>
<th><input id="chk6" name="chk6" type="checkbox"/>d</th>
</div>


问:
remove array from multidimensional array
Javascript problem.
I currently have this array and I want to remove all sub arrays that contain 0's.

For example I have this array:

```<code>var changeReg = [
["PENNY", 0],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 0],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 100]
];
</code>```

The end result should be this:

```<code>var changeReg = [["ONE HUNDRED", 100]];
</code>```

My code:

```<code>  for(var i = 0; i < changeReg.length; i++) {
    for(var j = changeReg[i].length-1; j >= 0; j--) {
        if(changeReg[i][1] === 0) {
           changeReg.splice(i--, 1);
        }
    }
  }
</code>```

Problem:
When I execute my code it gives me this error:
TypeError: Cannot read property '1' of undefined.

答:
the functional way would be :</p>

```<code>changeReg = changeReg.filter( function(item){
    return item[1] > 1;
})
</code>```

Body:
Javascript problem.
I currently have this array and I want to remove all sub arrays that contain 0's.

For example I have this array:

var changeReg = [
["PENNY", 0],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 0],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 100]
];

The end result should be this:

var changeReg = [["ONE HUNDRED", 100]];

My code:

  for(var i = 0; i < changeReg.length; i++) {
    for(var j = changeReg[i].length-1; j >= 0; j--) {
        if(changeReg[i][1] === 0) {
           changeReg.splice(i--, 1);
        }
    }
  }

Problem:
When I execute my code it gives me this error:
TypeError: Cannot read property '1' of undefined.

Body:
the functional way would be :

changeReg = changeReg.filter( function(item){
    return item[1] > 1;
})


问:
List docker database with local databases
i have two docker containers running, following the instructions given here: https://github.com/swri-robotics/bag-database.

I can now look at the database in the browser using: localhost:8080, so it's set up properly and running fine.

So my question is, how can I get the other container that is running on port 5432 to list the database with all the other databases that I have locally using psql - l?
Right now I can only look at it if I open the container first.

I run it like this:

docker run -d -p 5432:5432 --name bagdb-postgres -v /var/lib/bagdb-postgres:/var/lib/postgresql/data -h 127.0.0.1 -e POSTGRES_PASSWORD=password -e POSTGRES_USER=user -e POSTGRES_DB=bag_database mdillon/postgres:lastest

Thanks!

答: The programm is executed in a container. The intention of containers is to create a environment capsuled off your host operating system. You added some flags like -p and -v which define some connections between the host and the container. These are the only connections you have and you can use docker commands to connect to your container. It is not intended that you can execute code inside a container as if it was not inside a container. It is not exposed to your operating system and as far as I know there is no way to change that.</p>


问:
Why is Crystal automatically adding Guidelines whenever I expand a section?
I'm using Crystal 9, and whenever I add a new section to a report, and attempt to expand it, Crystal adds a BUNCH of horizontal guidelines.

It's really irritating. I figure there's got to be some setting I've tripped, but I can't figure out which one.

Any ideas?

答: I had the same issue and to solve it I just open File>Option and change the GridSize.  After this each time I added new section no Guidelines was added automatically.</p>


问:
Boolean != false
In Java, you would usually say that

if(someBool != false)

is the same as

if(someBool)

But what if someBool is not of type boolean but  Boolean, and its value is null?

答: Use ApacheCommons BooleanUtils.isTrue() or .isFalse()</p>

Title: Boolean != false


问:
Deleting index in elasticsearch
I want to delete an entire index of elastic search which i had created using the following code in python notebook.

```<code>es.index(index='para', doc_type='people', id=1, body={
    "name":"Farid ullah",
    "height":"160",
    "age":"23",
    "gender":"male",
    "date of birth":"04/02/1994",
    "Qualification":"BS in Software engineering"

})
</code>```

the delete command is as follows,

es.delete(index='para', doc_type='people'),
but I get the following error

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-7-26c24345ae23> in <module>()
----> 1 es.delete(index='para', doc_type='people')

C:\Users\Farid ullah\Anaconda3\lib\site-packages\elasticsearch\client\utils.py in _wrapped(*args, **kwargs)
     71                 if p in kwargs:
     72                     params[p] = kwargs.pop(p)
---> 73             return func(*args, params=params, **kwargs)
     74         return _wrapped
     75     return _wrapper

TypeError: delete() missing 1 required positional argument: 'id'
</code>```

Can I not be able to delete entire index?
Is there any way to delete it without specifying the id of a particular one?

答:
In your case, 'people' is not an index, it's a type. The index name is 'para'.
I don't know the python API, but your should try something like :

```<code>es.delete(index='para')
</code>```

In this doc :
http://elasticsearch-py.readthedocs.io/en/master/api.html

It is suggested to use something like :

```<code>es.indices.delete(index='para')
</code>```

Title: Deleting index in elasticsearch

Body:
I want to delete an entire index of elastic search which i had created using the following code in python notebook.

es.index(index='para', doc_type='people', id=1, body={
    "name":"Farid ullah",
    "height":"160",
    "age":"23",
    "gender":"male",
    "date of birth":"04/02/1994",
    "Qualification":"BS in Software engineering"

})

the delete command is as follows,

es.delete(index='para', doc_type='people'),
but I get the following error

TypeError                                 Traceback (most recent call last)
<ipython-input-7-26c24345ae23> in <module>()
----> 1 es.delete(index='para', doc_type='people')

C:\Users\Farid ullah\Anaconda3\lib\site-packages\elasticsearch\client\utils.py in _wrapped(*args, **kwargs)
     71                 if p in kwargs:
     72                     params[p] = kwargs.pop(p)
---> 73             return func(*args, params=params, **kwargs)
     74         return _wrapped
     75     return _wrapper

TypeError: delete() missing 1 required positional argument: 'id'

Can I not be able to delete entire index?
Is there any way to delete it without specifying the id of a particular one?

Body:
In your case, 'people' is not an index, it's a type. The index name is 'para'.
I don't know the python API, but your should try something like :

es.delete(index='para')

In this doc :
http://elasticsearch-py.readthedocs.io/en/master/api.html

It is suggested to use something like :

es.indices.delete(index='para')


问:
My form won't post any text or images
Here's my code, at first I had an undefined index notice for "postimg" (the input variable in the form) in the foreach loop, I debugged my code and got rid of the notice by checking if postimg was set, however now my posts and images won't show up, I believe the problem still lies with the use of postimg in the for each loop, I just don't know what exactly it is.

```<code><?php
include("connect.php");
include("check.php");
include("image.php");

$posts = "";
//$postimg = "";

                if (isset($_POST['post'])) {
                            //  $time = connect::query('SELECT posted_at FROM dry_posts WHERE id=:postid', array(':postid'=>$_GET['id']));
                        //$postimg = $_POST['postimg'];
                    //if(isset($_POST['postimg']))
                    //{

                            //  $id = connect::query('SELECT id FROM dry_posts WHERE id=:id', array(':id'=>$_GET['id']));

                        if ($_FILES['postimg']['size'] == 0)
                        {

                                $postbody = $_POST['postbody'];
                                $loggedInUserId = check::isLoggedIn();
                                if (strlen($postbody) > 160 || strlen($postbody) < 1)
                                {
                                    die('Incorrect length!');
                                }

                                connect::query('INSERT INTO dry_posts VALUES (null, :postbody, NOW(), 0)', array(':postbody'=>$postbody));

                        }
                        else
                        {
                                //$postid = Post::createImgPost($_POST['postbody']);
                            if (strlen($postbody) > 160) {
                                die('Incorrect length!');
                            }
                            connect::query('INSERT INTO dry_posts VALUES (null, :postbody, NOW(), 0)', array(':postbody'=>$postbody));
                            $postid = connect::query('SELECT id FROM dry_posts ORDER BY ID DESC LIMIT 1');
                            Image::uploadImage('postimg', "UPDATE dry_posts SET postimg=:postimg WHERE id=:postid", array(':postid'=>$postid));
                        }
                   // }
                }
                if (isset($_GET['postid']))
                {

                        //Post::likePost($_GET['postid']);
                    if (!connect::query('SELECT post_id FROM post_likes WHERE post_id=:postid', array(':postid'=>$_GET['postid'])))
                    {
                           connect::query('UPDATE dry_posts SET likes=likes+1 WHERE id=:postid', array(':postid'=>$_GET['postid']));
                           connect::query('INSERT INTO post_likes VALUES (null, :postid)', array(':postid'=>$_GET['postid']));
                    }
                    else
                    {
                          connect::query('UPDATE dry_posts SET likes=likes-1 WHERE id=:postid', array(':postid'=>$_GET['postid']));
                          connect::query('DELETE FROM post_likes WHERE post_id=:postid', array(':postid'=>$_GET['postid']));
                    }
                }

                // $posts = Post::displayPosts();
                $dbposts = connect::query('SELECT * FROM dry_posts ORDER BY id DESC');
                $posts = "";
                if(isset($_POST['postimg'])){
                foreach($dbposts as $p) {
                        if (!connect::query('SELECT post_id FROM post_likes WHERE post_id=:postid', array(':postid'=>$p['id']))) {
                                $posts .="<img src='".$p['postimg']."'>".htmlspecialchars($p['body'])."
                                <form action='dry.php?postid=".$p['id']."' method='post'>
                                        <input type='submit' name='like' value='Like'>
                                        <span>".$p['likes']." likes</span>
                                </form>
                                <hr /></br />
                                ";
                        } else {
                                $posts .="<img src='".$p['postimg']."'>".htmlspecialchars($p['body'])."
                                <form action='dry.php?postid=".$p['id']."' method='post'>
                                        <input type='submit' name='unlike' value='Unlike'>
                                        <span>".$p['likes']." likes</span>
                                </form>
                                <hr /></br />
                                ";
                        }
                }
         }
?>
</code>```

Here's the header file,"image.php", where I upload images using imgur, I don't believe I have any errors here, any suggestions?

```<code><?php

    class Image
    {
        public static function uploadImage($query,$params)
        {
            $image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
            $options = array('http'=>array(
                'method'=>"POST",
                'header'=>"Authorization: Bearer 813d9b0ee1b108a3383f6bd016dd9260873fa681\n".
                "Content-Type: application/x-www-form-urlencoded",
                'content'=>$image
            ));
            $context = stream_context_create($options);
            $imgurURL = "https://api.imgur.com/3/image";
            if ($_FILES['profileimg']['size'] > 10240000) {
                die('Image too big, must be 10MB or less!');
            }
            $response = file_get_contents($imgurURL, false, $context);
            $response = json_decode($response);

            $preparams = array($formname=>$response->$data->$link);
            $params = $preparams + $params;

            connect::query($query,$params);

        }

    }

?>
</code>```

答: There's a lot of stuff in here to go through, but I will tell you that if you do not have enctype="multipart/form-data" in your form tag after method='post', your image won't post.</p>

Title: My form won't post any text or images

Body:
Here's my code, at first I had an undefined index notice for "postimg" (the input variable in the form) in the foreach loop, I debugged my code and got rid of the notice by checking if postimg was set, however now my posts and images won't show up, I believe the problem still lies with the use of postimg in the for each loop, I just don't know what exactly it is.

<?php
include("connect.php");
include("check.php");
include("image.php");

$posts = "";
//$postimg = "";

                if (isset($_POST['post'])) {
                            //  $time = connect::query('SELECT posted_at FROM dry_posts WHERE id=:postid', array(':postid'=>$_GET['id']));
                        //$postimg = $_POST['postimg'];
                    //if(isset($_POST['postimg']))
                    //{

                            //  $id = connect::query('SELECT id FROM dry_posts WHERE id=:id', array(':id'=>$_GET['id']));

                        if ($_FILES['postimg']['size'] == 0)
                        {

                                $postbody = $_POST['postbody'];
                                $loggedInUserId = check::isLoggedIn();
                                if (strlen($postbody) > 160 || strlen($postbody) < 1)
                                {
                                    die('Incorrect length!');
                                }

                                connect::query('INSERT INTO dry_posts VALUES (null, :postbody, NOW(), 0)', array(':postbody'=>$postbody));

                        }
                        else
                        {
                                //$postid = Post::createImgPost($_POST['postbody']);
                            if (strlen($postbody) > 160) {
                                die('Incorrect length!');
                            }
                            connect::query('INSERT INTO dry_posts VALUES (null, :postbody, NOW(), 0)', array(':postbody'=>$postbody));
                            $postid = connect::query('SELECT id FROM dry_posts ORDER BY ID DESC LIMIT 1');
                            Image::uploadImage('postimg', "UPDATE dry_posts SET postimg=:postimg WHERE id=:postid", array(':postid'=>$postid));
                        }
                   // }
                }
                if (isset($_GET['postid']))
                {

                        //Post::likePost($_GET['postid']);
                    if (!connect::query('SELECT post_id FROM post_likes WHERE post_id=:postid', array(':postid'=>$_GET['postid'])))
                    {
                           connect::query('UPDATE dry_posts SET likes=likes+1 WHERE id=:postid', array(':postid'=>$_GET['postid']));
                           connect::query('INSERT INTO post_likes VALUES (null, :postid)', array(':postid'=>$_GET['postid']));
                    }
                    else
                    {
                          connect::query('UPDATE dry_posts SET likes=likes-1 WHERE id=:postid', array(':postid'=>$_GET['postid']));
                          connect::query('DELETE FROM post_likes WHERE post_id=:postid', array(':postid'=>$_GET['postid']));
                    }
                }

                // $posts = Post::displayPosts();
                $dbposts = connect::query('SELECT * FROM dry_posts ORDER BY id DESC');
                $posts = "";
                if(isset($_POST['postimg'])){
                foreach($dbposts as $p) {
                        if (!connect::query('SELECT post_id FROM post_likes WHERE post_id=:postid', array(':postid'=>$p['id']))) {
                                $posts .="".htmlspecialchars($p['body'])."
                                <form action='dry.php?postid=".$p['id']."' method='post'>
                                        <input type='submit' name='like' value='Like'>
                                        ".$p['likes']." likes
                                </form>

                                ";
                        } else {
                                $posts .="".htmlspecialchars($p['body'])."
                                <form action='dry.php?postid=".$p['id']."' method='post'>
                                        <input type='submit' name='unlike' value='Unlike'>
                                        ".$p['likes']." likes
                                </form>

                                ";
                        }
                }
         }
?>

Here's the header file,"image.php", where I upload images using imgur, I don't believe I have any errors here, any suggestions?

<?php

    class Image
    {
        public static function uploadImage($query,$params)
        {
            $image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
            $options = array('http'=>array(
                'method'=>"POST",
                'header'=>"Authorization: Bearer 813d9b0ee1b108a3383f6bd016dd9260873fa681\n".
                "Content-Type: application/x-www-form-urlencoded",
                'content'=>$image
            ));
            $context = stream_context_create($options);
            $imgurURL = "https://api.imgur.com/3/image";
            if ($_FILES['profileimg']['size'] > 10240000) {
                die('Image too big, must be 10MB or less!');
            }
            $response = file_get_contents($imgurURL, false, $context);
            $response = json_decode($response);

            $preparams = array($formname=>$response->$data->$link);
            $params = $preparams + $params;

            connect::query($query,$params);

        }

    }

?>


问:
Add Captured Images in an Array and show in Collection View and upload to server iOS
I need to captured multiple images one by one and store them in an array, show stored images in a collection view and later upload them to server.

I searched a lot about this concept but none of those solutions worked for me, array is null.

I tried below code:

```<code> - (IBAction)CaptureClicked:(id)sender {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:NULL];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
 if (info[UIImagePickerControllerMediaType] == (NSString *) kUTTypeImage) {

    [self.videoController.view removeFromSuperview];
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self->ImageView.image = chosenImage;
    [picker dismissViewControllerAnimated:YES completion:NULL];

     NSData *imageData =[NSData dataWithData:UIImagePNGRepresentation(chosenImage)];

     [imageArray addObject:imageData];
     [_ImageCollectionVIew reloadData];
 }
</code>```

答:
First you need to make a structure of dictionary set the values in a dictionary and add this dict in an array in this way:

```<code>let imageData = UIImageJPEGRepresentation(image, 0.0)!
 dict.setObject(imageData, forKey: MediaFilesMetaDataConstants.FileData as NSCopying)
  dict.setObject(IMAGENAME, forKey: MediaFilesMetaDataConstants.FileName as NSCopying)
  dict.setObject(MediaFilesMetaDataConstants.FileType_Image, forKey: MediaFilesMetaDataConstants.FileType as NSCopying)
  dict.setObject(thumbData, forKey: MediaFilesMetaDataConstants.Thumbnail as NSCopying)

kAppDelegate.arrMediaFiles.addObjects(from: [dict as Any])
</code>```

This is used in func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

Now you can show image on collection view on the basis of NSdata.

Now in webservice I am passing the image data in this way:

```<code>for i in 0 ..< arrImages.count {
            let dictImage = arrImages[i] as! NSDictionary
            let fileData = dictImage[MediaFilesMetaDataConstants.FileData] as! NSData
            let thumbData = dictImage[MediaFilesMetaDataConstants.Thumbnail] as! NSData
            let type = dictImage[MediaFilesMetaDataConstants.FileType] as! String
            if(type == MediaFilesMetaDataConstants.FileType_Image) {
                mimetype = "application/octet-stream"
            } else {
                mimetype = "video/mov"
            }

if(i == 0) {
                if(fileData.length > 0) {
                    body.appendString(string: "--\(boundary)\r\n")
                    body.appendString(string: "Content-Disposition: form-data; name=\"file_name0\"; filename=\"\(dictImage[MediaFilesMetaDataConstants.FileName] as! String)\"\r\n")
                    body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
                    body.append(fileData as Data)
                    body.appendString(string: "\r\n")
                }

                    if(thumbData.length > 0) {
                        body.appendString(string: "--\(boundary)\r\n")
                        body.appendString(string: "Content-Disposition: form-data; name=\"thumbnail0\"; filename=\"thumbImage.png\"\r\n")
                        body.appendString(string: "Content-Type: application/octet-stream\r\n\r\n")
                        body.append(thumbData as Data)
                        body.appendString(string: "\r\n")
                    }

            }

request.httpBody = body as Data
</code>```

You can add this code snippet in your webservice, as I show you that loop is used for calculating images, on that basis you can sent multiples images.

Body:
I need to captured multiple images one by one and store them in an array, show stored images in a collection view and later upload them to server.

I searched a lot about this concept but none of those solutions worked for me, array is null.

I tried below code:

 - (IBAction)CaptureClicked:(id)sender {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:NULL];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
 if (info[UIImagePickerControllerMediaType] == (NSString *) kUTTypeImage) {

    [self.videoController.view removeFromSuperview];
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self->ImageView.image = chosenImage;
    [picker dismissViewControllerAnimated:YES completion:NULL];

     NSData *imageData =[NSData dataWithData:UIImagePNGRepresentation(chosenImage)];

     [imageArray addObject:imageData];
     [_ImageCollectionVIew reloadData];
 }

Body:
First you need to make a structure of dictionary set the values in a dictionary and add this dict in an array in this way:

let imageData = UIImageJPEGRepresentation(image, 0.0)!
 dict.setObject(imageData, forKey: MediaFilesMetaDataConstants.FileData as NSCopying)
  dict.setObject(IMAGENAME, forKey: MediaFilesMetaDataConstants.FileName as NSCopying)
  dict.setObject(MediaFilesMetaDataConstants.FileType_Image, forKey: MediaFilesMetaDataConstants.FileType as NSCopying)
  dict.setObject(thumbData, forKey: MediaFilesMetaDataConstants.Thumbnail as NSCopying)

kAppDelegate.arrMediaFiles.addObjects(from: [dict as Any])

This is used in func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

Now you can show image on collection view on the basis of NSdata.

Now in webservice I am passing the image data in this way:

for i in 0 ..< arrImages.count {
            let dictImage = arrImages[i] as! NSDictionary
            let fileData = dictImage[MediaFilesMetaDataConstants.FileData] as! NSData
            let thumbData = dictImage[MediaFilesMetaDataConstants.Thumbnail] as! NSData
            let type = dictImage[MediaFilesMetaDataConstants.FileType] as! String
            if(type == MediaFilesMetaDataConstants.FileType_Image) {
                mimetype = "application/octet-stream"
            } else {
                mimetype = "video/mov"
            }

if(i == 0) {
                if(fileData.length > 0) {
                    body.appendString(string: "--\(boundary)\r\n")
                    body.appendString(string: "Content-Disposition: form-data; name=\"file_name0\"; filename=\"\(dictImage[MediaFilesMetaDataConstants.FileName] as! String)\"\r\n")
                    body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
                    body.append(fileData as Data)
                    body.appendString(string: "\r\n")
                }

                    if(thumbData.length > 0) {
                        body.appendString(string: "--\(boundary)\r\n")
                        body.appendString(string: "Content-Disposition: form-data; name=\"thumbnail0\"; filename=\"thumbImage.png\"\r\n")
                        body.appendString(string: "Content-Type: application/octet-stream\r\n\r\n")
                        body.append(thumbData as Data)
                        body.appendString(string: "\r\n")
                    }

            }

request.httpBody = body as Data

You can add this code snippet in your webservice, as I show you that loop is used for calculating images, on that basis you can sent multiples images.


问:
Qt5: show notification popups
I'm writing an image viewer which allows me to do some actions. As a visual feedback to some actions (like copy/move/delete/..) I'd like to have a decent popup in the middle of my application window which informs about what has been done and which disappears after about a second.

Of course I can just use a Widget and and modify it to fit my needs:

placed in the middle/on top of application window (regardless of layout)

disappears after a given time

no interaction/focus possible - clicking on the notification should be like clicking on what's behind of it

decent style (e.g. transparent and easily readable)

.. I'm just wondering if there's something dedicated for this purpose

(I'm NOT talking about tray notifications which appear near to some task barof the window manager)

答:
Dont know if you are in python or C, but may have a look to this:
http://doc.qt.io/qt-4.8/qmessagebox.html

Nevertheless, I would go for a new window (QWidget) and modify it. Its only a couple of lines, and the automatic close you can do by a Qtimer.

Title: Qt5: show notification popups


问:
SQL Query Help on finding Extended ASCII
How can I make a select statement to seaqrch for HI-ASCII characters for ex..chinese charatcres

Thanx

答:
Here is a solution

just add N before any value you want to search for for example

select * from [Table] where [Name]like N'% 的 %'

N= for search extended ascii characters