问:
Why is my Spring oauth server always returning the same access token?
I'm using Spring 4.3.8.RELEASE and spring-boot 1.5.3.RELEASE.  I want to serve oauth access tokens to applications with the proper credentials.  I'm using the org.springframework.security.oauth2.provider.token.store.JdbcTokenStore class to do this.  However, I'm noticing that each time I connect with a client to my server that I have set up with OAuth, the server repeatedly returns the same access token, even after server restarts.  My OAuth server configuration is below

```<code><?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
    xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
        <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
        <anonymous enabled="false" />
        <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
        <!-- include this only if you need to authenticate clients via request parameters -->
        <custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <!-- The OAuth2 protected resources are separated out into their own block
        so we can deal with authorization and error handling separately. This isn't
        mandatory, but it makes it easier to control the behaviour. -->
    <http pattern="/oauth/(users|clients)/.*" request-matcher="regex"
        create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
        use-expressions="true" xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/oauth/users/([^/].*?)/tokens/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')"
            method="DELETE" />
        <intercept-url pattern="/oauth/users/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')"
            method="GET" />
        <intercept-url pattern="/oauth/clients/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')"
            method="GET" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
        <expression-handler ref="oauthWebExpressionHandler" />
    </http>

    <!-- The OAuth2 protected resources are separated out into their own block
        so we can deal with authorization and error handling separately. This isn't
        mandatory, but it makes it easier to control the behaviour. -->
    <http pattern="/me/**" create-session="never"
        entry-point-ref="oauthAuthenticationEntryPoint"
        access-decision-manager-ref="accessDecisionManager"
        xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/me" access="ROLE_USER,SCOPE_READ" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <bean id="oauthAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="sparklr2" />
    </bean>

    <bean id="clientAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="sparklr2/client" />
        <property name="typeName" value="Basic" />
    </bean>

    <bean id="oauthAccessDeniedHandler"
        class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

    <bean id="clientCredentialsTokenEndpointFilter"
        class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <property name="authenticationManager" ref="clientAuthenticationManager" />
    </bean>

    <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
        xmlns="http://www.springframework.org/schema/beans">
        <constructor-arg>
            <list>
                <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
                <bean class="org.springframework.security.access.vote.RoleVoter" />
                <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
            </list>
        </constructor-arg>
    </bean>

    <authentication-manager id="clientAuthenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider user-service-ref="clientDetailsUserService" />
    </authentication-manager>

    <authentication-manager alias="authenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider>
            <user-service id="userDetailsService">
                <user name="marissa" password="koala" authorities="ROLE_USER" />
                <user name="paul" password="emu" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <bean id="clientDetailsUserService"
        class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <constructor-arg ref="clientDetails" />
    </bean>

    <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
        <constructor-arg ref="dataSource" />
        <property name="authenticationKeyGenerator">
            <bean class="org.springframework.security.oauth2.UniqueAuthenticationKeyGenerator" />
        </property>
    </bean>

    <bean id="tokenServices"
        class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <property name="tokenStore" ref="tokenStore" />
        <property name="tokenEnhancer" ref="tokenEnhancer" />
        <property name="supportRefreshToken" value="true" />
        <property name="clientDetailsService" ref="clientDetails" />
    </bean>

    <bean id="tokenEnhancer"
        class="org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter" />

    <bean id="requestFactory"
        class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
        <constructor-arg name="clientDetailsService" ref="clientDetails" />
    </bean>

    <bean id="approvalStore"
        class="org.springframework.security.oauth2.provider.approval.TokenApprovalStore">
        <property name="tokenStore" ref="tokenStore" />
    </bean>

    <oauth:authorization-server
        client-details-service-ref="clientDetails" token-services-ref="tokenServices">
        <oauth:client-credentials />
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter" entry-point-ref="entry"
        resource-id="myclientAssignment" token-services-ref="tokenServices" />

    <bean id="entry" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <constructor-arg value="/assignment" />
    </bean>

    <context:property-placeholder location="classpath:application.properties"/>
    <oauth:client-details-service id="clientDetails">
        <oauth:client client-id="${myclient.client.id}"
            authorized-grant-types="client_credentials" authorities="ROLE_CLIENT"
        access-token-validity="30"
            scope="read,write" secret="${myclient.client.secret}" />
    </oauth:client-details-service>

    <mvc:default-servlet-handler />

    <oauth:expression-handler id="oauthExpressionHandler" />

    <oauth:web-expression-handler id="oauthWebExpressionHandler" />

    <http pattern="/api/**"
                  create-session="never"
                  entry-point-ref="oauthAuthenticationEntryPoint"
                  access-decision-manager-ref="accessDecisionManager"
                  xmlns="http://www.springframework.org/schema/security">
     <anonymous enabled="false" />
     <intercept-url pattern="/**"
                             access="IS_AUTHENTICATED_FULLY"/>

     <custom-filter ref="resourceServerFilter"
                             before="PRE_AUTH_FILTER" />
     <access-denied-handler ref="oauthAccessDeniedHandler" />
   </http>

</beans>
</code>```

Here's the shell script I'm using to connect to my local server to retrieve the token ...

```<code>#!/bin/bash

ret=$(curl http://localhost:8080/myproject/oauth/token \
  -u "myclientid:mysecret" \
  -d "grant_type=client_credentials")
echo $ret > /tmp/out
cat /tmp/out
access_token=$( sed -e 's/^.*"access_token":"\([^"]*\)".*$/\1/' /tmp/out )
echo $access_token
</code>```

Edit:

Per Hans' request, here is an example access token

```<code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2ODQ4NDAzLCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiI4OGMxZjkzZC0wNmRhLTRmYTAtOTM1OS0yZWMxYzU5MWJlMGIiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.Pf-rjPDj0ZhrNOYuhA0tK8lPLLCzlkqUuFFjb48xskA
</code>```

and here is a second access token

```<code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2OTUzNTg0LCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiIxM2I5M2M4Ni05MmIwLTQyY2UtYjFkNS1lZjRiNmZhNzJkMzgiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.GfSHA_JcQg2WHYCI81lunMFIhxdX6REc4goshB2Lck0
</code>```

答:
This is sample regular access token which when issued will have 30 seconds expiration for your configuration.

You should see the info message (Failed to find access token for token) at the time a new token is issued.

```<code>{
  "access_token": "e057a4f3-9872-4b97-803e-938ad6ef32db",
  "token_type": "bearer",
  "refresh_token": "f9a7ea9a-0fd1-45a9-b8ae-de87eaf61787",
  "expires_in": 30,
  "scope": "read write"
}
</code>```

This is expected behavior as spring looks into database to verify if the access token for the authentication is already issued.

Subsequent requests until the expiry of token (30s) will not show the message. This message will show up again after old access token is expired and when new token is issued and it continues.

The below line is where that info message is displayed from

https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/store/JdbcTokenStore.java#L168

Refresh token is set to expire in 30 days by default. The similar log message will appear again when the refresh token expires.

It should work similar for JWT access token too.

This is the sequences of log messages when a new token is issued when you run the application in DEBUG logging level.

```<code>2017-06-06 14:06:51.339 DEBUG 28732 --- [nio-9191-exec-1] o.s.s.o.p.token.store.JdbcTokenStore     : Failed to find access token for authentication org.springframework.security.oauth2.provider.OAuth2Authentication@8e69d9c0: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_ADMIN, ROLE_USER
2017-06-06 14:06:51.346 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL query
2017-06-06 14:06:51.346 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL statement [select token_id, token from oauth_access_token where token_id = ?]
2017-06-06 14:06:51.347  INFO 28732 --- [nio-9191-exec-1] o.s.s.o.p.token.store.JdbcTokenStore     : Failed to find access token for token e057a4f3-9872-4b97-803e-938ad6ef32db
2017-06-06 14:06:51.442 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL update
2017-06-06 14:06:51.443 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL statement [insert into oauth_access_token (token_id, token, authentication_id, user_name, client_id, authentication, refresh_token) values (?, ?, ?, ?, ?, ?, ?)]
2017-06-06 14:06:51.450 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : SQL update affected 1 rows
2017-06-06 14:06:51.452 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL update
2017-06-06 14:06:51.452 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL statement [insert into oauth_refresh_token (token_id, token, authentication) values (?, ?, ?)]
2017-06-06 14:06:51.455 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : SQL update affected 1 rows
</code>```

Body:
I'm using Spring 4.3.8.RELEASE and spring-boot 1.5.3.RELEASE.  I want to serve oauth access tokens to applications with the proper credentials.  I'm using the org.springframework.security.oauth2.provider.token.store.JdbcTokenStore class to do this.  However, I'm noticing that each time I connect with a client to my server that I have set up with OAuth, the server repeatedly returns the same access token, even after server restarts.  My OAuth server configuration is below

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
    xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
        <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
        <anonymous enabled="false" />
        <http-basic entry-point-ref="clientAuthenticationEntryPoint" />

        <custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <http pattern="/oauth/(users|clients)/.*" request-matcher="regex"
        create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
        use-expressions="true" xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/oauth/users/([^/].*?)/tokens/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')"
            method="DELETE" />
        <intercept-url pattern="/oauth/users/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')"
            method="GET" />
        <intercept-url pattern="/oauth/clients/.*"
            access="#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')"
            method="GET" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
        <expression-handler ref="oauthWebExpressionHandler" />
    </http>

    <http pattern="/me/**" create-session="never"
        entry-point-ref="oauthAuthenticationEntryPoint"
        access-decision-manager-ref="accessDecisionManager"
        xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/me" access="ROLE_USER,SCOPE_READ" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <bean id="oauthAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="sparklr2" />
    </bean>

    <bean id="clientAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="sparklr2/client" />
        <property name="typeName" value="Basic" />
    </bean>

    <bean id="oauthAccessDeniedHandler"
        class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

    <bean id="clientCredentialsTokenEndpointFilter"
        class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <property name="authenticationManager" ref="clientAuthenticationManager" />
    </bean>

    <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
        xmlns="http://www.springframework.org/schema/beans">
        <constructor-arg>
            <list>
                <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
                <bean class="org.springframework.security.access.vote.RoleVoter" />
                <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
            </list>
        </constructor-arg>
    </bean>

    <authentication-manager id="clientAuthenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider user-service-ref="clientDetailsUserService" />
    </authentication-manager>

    <authentication-manager alias="authenticationManager"
        xmlns="http://www.springframework.org/schema/security">
        <authentication-provider>
            <user-service id="userDetailsService">
                <user name="marissa" password="koala" authorities="ROLE_USER" />
                <user name="paul" password="emu" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <bean id="clientDetailsUserService"
        class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <constructor-arg ref="clientDetails" />
    </bean>

    <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
        <constructor-arg ref="dataSource" />
        <property name="authenticationKeyGenerator">
            <bean class="org.springframework.security.oauth2.UniqueAuthenticationKeyGenerator" />
        </property>
    </bean>

    <bean id="tokenServices"
        class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <property name="tokenStore" ref="tokenStore" />
        <property name="tokenEnhancer" ref="tokenEnhancer" />
        <property name="supportRefreshToken" value="true" />
        <property name="clientDetailsService" ref="clientDetails" />
    </bean>

    <bean id="tokenEnhancer"
        class="org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter" />

    <bean id="requestFactory"
        class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
        <constructor-arg name="clientDetailsService" ref="clientDetails" />
    </bean>

    <bean id="approvalStore"
        class="org.springframework.security.oauth2.provider.approval.TokenApprovalStore">
        <property name="tokenStore" ref="tokenStore" />
    </bean>

    <oauth:authorization-server
        client-details-service-ref="clientDetails" token-services-ref="tokenServices">
        <oauth:client-credentials />
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter" entry-point-ref="entry"
        resource-id="myclientAssignment" token-services-ref="tokenServices" />

    <bean id="entry" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <constructor-arg value="/assignment" />
    </bean>

    <context:property-placeholder location="classpath:application.properties"/>
    <oauth:client-details-service id="clientDetails">
        <oauth:client client-id="${myclient.client.id}"
            authorized-grant-types="client_credentials" authorities="ROLE_CLIENT"
        access-token-validity="30"
            scope="read,write" secret="${myclient.client.secret}" />
    </oauth:client-details-service>

    <mvc:default-servlet-handler />

    <oauth:expression-handler id="oauthExpressionHandler" />

    <oauth:web-expression-handler id="oauthWebExpressionHandler" />

    <http pattern="/api/**"
                  create-session="never"
                  entry-point-ref="oauthAuthenticationEntryPoint"
                  access-decision-manager-ref="accessDecisionManager"
                  xmlns="http://www.springframework.org/schema/security">
     <anonymous enabled="false" />
     <intercept-url pattern="/**"
                             access="IS_AUTHENTICATED_FULLY"/>

     <custom-filter ref="resourceServerFilter"
                             before="PRE_AUTH_FILTER" />
     <access-denied-handler ref="oauthAccessDeniedHandler" />
   </http>

</beans>

Here's the shell script I'm using to connect to my local server to retrieve the token ...

#!/bin/bash

ret=$(curl http://localhost:8080/myproject/oauth/token \
  -u "myclientid:mysecret" \
  -d "grant_type=client_credentials")
echo $ret > /tmp/out
cat /tmp/out
access_token=$( sed -e 's/^.*"access_token":"\([^"]*\)".*$/\1/' /tmp/out )
echo $access_token

Edit:

Per Hans' request, here is an example access token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2ODQ4NDAzLCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiI4OGMxZjkzZC0wNmRhLTRmYTAtOTM1OS0yZWMxYzU5MWJlMGIiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.Pf-rjPDj0ZhrNOYuhA0tK8lPLLCzlkqUuFFjb48xskA

and here is a second access token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2OTUzNTg0LCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiIxM2I5M2M4Ni05MmIwLTQyY2UtYjFkNS1lZjRiNmZhNzJkMzgiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.GfSHA_JcQg2WHYCI81lunMFIhxdX6REc4goshB2Lck0

Body:
This is sample regular access token which when issued will have 30 seconds expiration for your configuration.

You should see the info message (Failed to find access token for token) at the time a new token is issued.

{
  "access_token": "e057a4f3-9872-4b97-803e-938ad6ef32db",
  "token_type": "bearer",
  "refresh_token": "f9a7ea9a-0fd1-45a9-b8ae-de87eaf61787",
  "expires_in": 30,
  "scope": "read write"
}

This is expected behavior as spring looks into database to verify if the access token for the authentication is already issued.

Subsequent requests until the expiry of token (30s) will not show the message. This message will show up again after old access token is expired and when new token is issued and it continues.

The below line is where that info message is displayed from

https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/store/JdbcTokenStore.java#L168

Refresh token is set to expire in 30 days by default. The similar log message will appear again when the refresh token expires.

It should work similar for JWT access token too.

This is the sequences of log messages when a new token is issued when you run the application in DEBUG logging level.

2017-06-06 14:06:51.339 DEBUG 28732 --- [nio-9191-exec-1] o.s.s.o.p.token.store.JdbcTokenStore     : Failed to find access token for authentication org.springframework.security.oauth2.provider.OAuth2Authentication@8e69d9c0: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_ADMIN, ROLE_USER
2017-06-06 14:06:51.346 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL query
2017-06-06 14:06:51.346 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL statement [select token_id, token from oauth_access_token where token_id = ?]
2017-06-06 14:06:51.347  INFO 28732 --- [nio-9191-exec-1] o.s.s.o.p.token.store.JdbcTokenStore     : Failed to find access token for token e057a4f3-9872-4b97-803e-938ad6ef32db
2017-06-06 14:06:51.442 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL update
2017-06-06 14:06:51.443 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL statement [insert into oauth_access_token (token_id, token, authentication_id, user_name, client_id, authentication, refresh_token) values (?, ?, ?, ?, ?, ?, ?)]
2017-06-06 14:06:51.450 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : SQL update affected 1 rows
2017-06-06 14:06:51.452 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL update
2017-06-06 14:06:51.452 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL statement [insert into oauth_refresh_token (token_id, token, authentication) values (?, ?, ?)]
2017-06-06 14:06:51.455 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate               : SQL update affected 1 rows


来源: stackexchange

问:
Display coach marks view when user launches app for the first time Swift 3
I need to launch a coach marks/tutorial view over a tableview when the user launches the app for the first time. The coach marks will never display again, unless the user deletes and reinstalls the app.

I scoured the internet, but was unable to find a simple solution. Oh, I'm fairly new to Swift, so please be gentle. :)

EDIT:
Here is the what I used. Works great!

```<code>  override func viewDidAppear(_ animated: Bool) {
        if !UserDefaults.standard.bool(forKey: "isSecondTime") {
            let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
            if launchedBefore  {
                print("Not the first launch.")
            } else {
                let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CoachMarksViewController")
                self.present(VC, animated: true, completion: nil)
                print("This the first launch.")
                UserDefaults.standard.set(true, forKey: "isSecondTime")
            }

        }
}
</code>```

答:
So you need a bool to indicate whether to show the coach marks/tutorial that persists across the app being terminated and restarted.  The first time the app is run the bool will indicate that the coach marks must be displayed then the app will set the bool to indicate that they are no longer required.

To persist the bool you could use UserDefaults to store the bool and read it when the app starts.  Here is the link to the Apple documentation on it.

p.s. it might be nice to give the user a way to display them again as they might forget something or just dismiss them without thinking.

ContentLicense: CC BY-SA 3.0

Body:
I need to launch a coach marks/tutorial view over a tableview when the user launches the app for the first time. The coach marks will never display again, unless the user deletes and reinstalls the app.

I scoured the internet, but was unable to find a simple solution. Oh, I'm fairly new to Swift, so please be gentle. :)

EDIT:
Here is the what I used. Works great!

  override func viewDidAppear(_ animated: Bool) {
        if !UserDefaults.standard.bool(forKey: "isSecondTime") {
            let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
            if launchedBefore  {
                print("Not the first launch.")
            } else {
                let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CoachMarksViewController")
                self.present(VC, animated: true, completion: nil)
                print("This the first launch.")
                UserDefaults.standard.set(true, forKey: "isSecondTime")
            }

        }
}


问:
Android intent to check/view emails
I am looking for a way to fire the email-app on device from my app to check emails. Note: I do not want to 'send' any email, just want to 'check' emails. The following code crashes for the gmail app -

```<code>          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setType("message/rfc822");
          startActivity(intent);
</code>```

The stack-trace being -

```<code>06-06 23:26:20.313 27703-27731/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                   Process: com.google.android.gm, PID: 27703
                                                   java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                       at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
                                                    Caused by: java.lang.NullPointerException: uri
                                                       at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
                                                       at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
                                                       at clk.a(SourceFile:8)
                                                       at clk.loadInBackground(SourceFile:74)
                                                       at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
                                                       at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
</code>```

Is there no way to fire email app just to check emails?

答:
Try this code, this will open a dialog with all all email apps in your device. Select the app from popup and it will open.

```<code>try {
List<String> emailClientNames = new ArrayList<String>();
final List<String> emailClientPackageNames = new ArrayList<String>();
// finding list of email clients that support send email
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
    "mailto", "abc@gmail.com", null));
PackageManager pkgManager = AppController.getContext().getPackageManager();
List<ResolveInfo> packages = pkgManager.queryIntentActivities(intent, 0);
if (!packages.isEmpty()) {
    for (ResolveInfo resolveInfo : packages) {
        // finding the package name
        String packageName = resolveInfo.activityInfo.packageName;
        emailClientNames.add(resolveInfo.loadLabel(getPackageManager()).toString());
        emailClientPackageNames.add(packageName);
    }
    // a selection dialog  for the email clients
    AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
    builder.setTitle("Select email client");
    builder.setItems(emailClientNames.toArray(new String[]{}), new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // on click we launch the right package
        Intent intent = getPackageManager().getLaunchIntentForPackage(emailClientPackageNames.get(which));
            startActivity(intent);
        }
    });
    AlertDialog dialog = builder.create();
    dialog.show();
}
} catch (ActivityNotFoundException e) {
// Show error message
}
</code>```

But if you want to open your default email app directly then use this code:

```<code> Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_APP_EMAIL);
startActivity(intent);
startActivity(Intent.createChooser(intent, getString(R.string.ChoseEmailClient)));
</code>```

Title: Android intent to check/view emails

Body:
I am looking for a way to fire the email-app on device from my app to check emails. Note: I do not want to 'send' any email, just want to 'check' emails. The following code crashes for the gmail app -

          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setType("message/rfc822");
          startActivity(intent);

The stack-trace being -

06-06 23:26:20.313 27703-27731/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                   Process: com.google.android.gm, PID: 27703
                                                   java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                       at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
                                                    Caused by: java.lang.NullPointerException: uri
                                                       at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
                                                       at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
                                                       at clk.a(SourceFile:8)
                                                       at clk.loadInBackground(SourceFile:74)
                                                       at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
                                                       at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)

Is there no way to fire email app just to check emails?

Body:
Try this code, this will open a dialog with all all email apps in your device. Select the app from popup and it will open.

try {
List<String> emailClientNames = new ArrayList<String>();
final List<String> emailClientPackageNames = new ArrayList<String>();
// finding list of email clients that support send email
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
    "mailto", "abc@gmail.com", null));
PackageManager pkgManager = AppController.getContext().getPackageManager();
List<ResolveInfo> packages = pkgManager.queryIntentActivities(intent, 0);
if (!packages.isEmpty()) {
    for (ResolveInfo resolveInfo : packages) {
        // finding the package name
        String packageName = resolveInfo.activityInfo.packageName;
        emailClientNames.add(resolveInfo.loadLabel(getPackageManager()).toString());
        emailClientPackageNames.add(packageName);
    }
    // a selection dialog  for the email clients
    AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
    builder.setTitle("Select email client");
    builder.setItems(emailClientNames.toArray(new String[]{}), new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // on click we launch the right package
        Intent intent = getPackageManager().getLaunchIntentForPackage(emailClientPackageNames.get(which));
            startActivity(intent);
        }
    });
    AlertDialog dialog = builder.create();
    dialog.show();
}
} catch (ActivityNotFoundException e) {
// Show error message
}

But if you want to open your default email app directly then use this code:

 Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_APP_EMAIL);
startActivity(intent);
startActivity(Intent.createChooser(intent, getString(R.string.ChoseEmailClient)));


问:
Test browser support for HTML5 elements and API's. Why does this work
I have chosen to avoid identifying the browser as unreliable and messy. Instead I am just testing for actual support of each of the elements or APIs my page uses. For testing audio support I have come up with this.

```<code>function testAudio()
    {
    if(window.AudioContext = window.AudioContext)
        {
        myAudio = new AudioContext();
        alert("Browser supports AudioContext");
        }
    else
        {
        if(window.Audio = window.Audio)
            {
            myAudio = new Audio();
            alert("Browser supports Audio Element");
            }
        else {alert("This browser does not support AudioContext or Audio Element");}
        }
    }
</code>```

Works like a charm. Current browsers return true for AudioContext, IE11 returns true only for Audio() and IE 8 returns false for both. But WHY?

In the case of true I am assigning an object to an object property of the window object. Is there an AudioContext and Audio element property of the window object? Or is the browser returning true for an assignment to an object that could exist but doesn't?

In the case of false I am assigning an object that the browser doesn't recognize to a property of the window object that doesn't exist. Why does it return false instead of throwing an error, null or undefined? And why would this return false while

```<code>if(myAudio = new AudioContext()) or if(myAudio = new Audio()) throw errors?
</code>```

答:
IE8 does not fully support HTML5, and that includes the Audio API. If you want IE8 support you'll need to include a polyfill.

When you try to instantiate a new object using a non-existent object prototype (i.e. new AudioContext()) you should expect an error. But if (window.AudioContext) is merely checking for the existence of the property--it is not calling a function, so there is no error.

The issue you're facing here is that this is an odd way to check if the browser supports the API in question.

For example,

```<code>if (window.Audio = window.Audio)
</code>```

in IE8 is going to be the same as this:

```<code>if (window.Audio = undefined)
</code>```

which, if you remove the assignment, can be reduced to this:

```<code>if (undefined)
</code>```

which is falsy, meaning that it's going to have the same result as this:

```<code>if (false)
</code>```

so you'll never get into that block.

Body:
I have chosen to avoid identifying the browser as unreliable and messy. Instead I am just testing for actual support of each of the elements or APIs my page uses. For testing audio support I have come up with this.

function testAudio()
    {
    if(window.AudioContext = window.AudioContext)
        {
        myAudio = new AudioContext();
        alert("Browser supports AudioContext");
        }
    else
        {
        if(window.Audio = window.Audio)
            {
            myAudio = new Audio();
            alert("Browser supports Audio Element");
            }
        else {alert("This browser does not support AudioContext or Audio Element");}
        }
    }

Works like a charm. Current browsers return true for AudioContext, IE11 returns true only for Audio() and IE 8 returns false for both. But WHY?

In the case of true I am assigning an object to an object property of the window object. Is there an AudioContext and Audio element property of the window object? Or is the browser returning true for an assignment to an object that could exist but doesn't?

In the case of false I am assigning an object that the browser doesn't recognize to a property of the window object that doesn't exist. Why does it return false instead of throwing an error, null or undefined? And why would this return false while

if(myAudio = new AudioContext()) or if(myAudio = new Audio()) throw errors?

Body:
IE8 does not fully support HTML5, and that includes the Audio API. If you want IE8 support you'll need to include a polyfill.

When you try to instantiate a new object using a non-existent object prototype (i.e. new AudioContext()) you should expect an error. But if (window.AudioContext) is merely checking for the existence of the property--it is not calling a function, so there is no error.

The issue you're facing here is that this is an odd way to check if the browser supports the API in question.

For example,

if (window.Audio = window.Audio)

in IE8 is going to be the same as this:

if (window.Audio = undefined)

which, if you remove the assignment, can be reduced to this:

if (undefined)

which is falsy, meaning that it's going to have the same result as this:

if (false)

so you'll never get into that block.


问:
Add ssh key in bash script (jenkins pipeline)
I have a Jenkins job which needs to execute a shell script. It does a connection via ssh key to a remote computer. Here is the pipeline job :

```<code>    stage ('Run') {
        try {
            sh "chmod +x \$(find . -name '*.sh')"
            wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm']) {
                sh "./run-ansible-playbook.sh -f ansible-playbook.yml"
            }
etc...
</code>```

The .sh file does the ssh-agent and the ssh-add commands.

```<code>sshAgentCount=$(pgrep ssh-agent | wc -l)

if [[ $sshAgentCount -eq 0 ]]; then
        echo "# run ssh-agent #"
        eval `ssh-agent -s`
       ssh-add /var/lib/jenkins/id_rsa_ansible
fi
</code>```

Problem is that sometimes this works and sometimes not. I think it is because of the tty of the user (here jenkins) which changes all time and the ssh-agent process is linked to a tty.
I don't want to call eval ssh-agent -s always because it causes a out of memory on the machine by time.

Here the ps aux | grep ssh-agent status :

```<code>jenkins   1243  0.0  0.0  11140   320 ?        Ss   17:20   0:00 ssh-agent -s
jenkins   1397  0.0  0.0  11140   320 ?        Ss   17:23   0:00 ssh-agent -s
jenkins   1435  0.0  0.0  11140   320 ?        Ss   17:23   0:00 ssh-agent -s
</code>```

Do you have an elegant solution for this problem ? (one ssh-agent only if needed)

Thank you a lot :)

答:
I think it is because of the tty of the user (here jenkins) which changes all time and the ssh-agent process is linked to a tty.

No. SSH agent is not linked to tty. SSH agent connection is stored in the environment variable $SSH_AUTH_SOCK so once you will close the original shell, which started the ssh-agent, you will lose the connection to the agent.

But you can preserve this connection by storing the environment variable in file and loading it in the next shells (if is is still usable) or similar things.

Body:
I have a Jenkins job which needs to execute a shell script. It does a connection via ssh key to a remote computer. Here is the pipeline job :

    stage ('Run') {
        try {
            sh "chmod +x \$(find . -name '*.sh')"
            wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm']) {
                sh "./run-ansible-playbook.sh -f ansible-playbook.yml"
            }
etc...

The .sh file does the ssh-agent and the ssh-add commands.

sshAgentCount=$(pgrep ssh-agent | wc -l)

if [[ $sshAgentCount -eq 0 ]]; then
        echo "# run ssh-agent #"
        eval `ssh-agent -s`
       ssh-add /var/lib/jenkins/id_rsa_ansible
fi

Problem is that sometimes this works and sometimes not. I think it is because of the tty of the user (here jenkins) which changes all time and the ssh-agent process is linked to a tty.
I don't want to call eval ssh-agent -s always because it causes a out of memory on the machine by time.

Here the ps aux | grep ssh-agent status :

jenkins   1243  0.0  0.0  11140   320 ?        Ss   17:20   0:00 ssh-agent -s
jenkins   1397  0.0  0.0  11140   320 ?        Ss   17:23   0:00 ssh-agent -s
jenkins   1435  0.0  0.0  11140   320 ?        Ss   17:23   0:00 ssh-agent -s

Do you have an elegant solution for this problem ? (one ssh-agent only if needed)

Thank you a lot :)


问:
Is there a way to export SAS number using commas instead of dots?
The question is pretty straightforward.

When I do calculations on SAS and export them to an Excel spreadsheet, the numbers are exported using a dot as a decimal delimiter. Can I use a comma as a decimal delimiter when exporting on SAS software?

For example, I have this number: 32.53 but I want it exported to Excel as 32,53.

答:
You could use several notations (FLOAT4, REAL+4, float, E, FLOAT BIN(21)) but not the delimiter itself. Contrary it can be changed in Excel.

Nonetheless, try to look at NUMXw.d


问:
Firebase: How to get User.uid?
I'm using Firebaseauth to manage users and data for my iOS app. The users can log in, and their userinfo is stored correct in the database.
But when I try to get the users to write to the database in a different viewController, using this string:

```<code>self.ref.child("users").child(user.uid).setValue(["username": username])
</code>```

The thrown error is

Type user has no member .uid

That makes sense I guess, since I haven't created the variable. But I can't figure out how to declare it?

答:
This is how you get the user's uid:

```<code>let userID = Auth.auth().currentUser!.uid
</code>```

UPDATE: Since this answer is getting upvotes, make sure you prevent your app from crashing by using guards:

```<code>guard let userID = Auth.auth().currentUser?.uid else { return }
</code>```

Title: Firebase: How to get User.uid?

Body:
I'm using Firebaseauth to manage users and data for my iOS app. The users can log in, and their userinfo is stored correct in the database.
But when I try to get the users to write to the database in a different viewController, using this string:

self.ref.child("users").child(user.uid).setValue(["username": username])

The thrown error is

Type user has no member .uid

That makes sense I guess, since I haven't created the variable. But I can't figure out how to declare it?

Body:
This is how you get the user's uid:

let userID = Auth.auth().currentUser!.uid

UPDATE: Since this answer is getting upvotes, make sure you prevent your app from crashing by using guards:

guard let userID = Auth.auth().currentUser?.uid else { return }

ContentLicense: CC BY-SA 4.0


问:
Problems Passing ViewModel with data from View to Controller
Ok, here is my problem.  I am trying to pass a view model of mine, which has multiple list in it, to my view.  Then in my view i need to edit the different list.  Then on my post i need to save the edits.  Although, when i pass my viewmodel back to my post, it is empty! Can somebody explain what i am doing wrong? i am not worried about saving the information right now, i am just worried about getting the data back to the controller.  The ViewModel is null when i hit that portion.

Controller

```<code>    public ActionResult ManageNewsArticles()
    {
        NewsViewModel newsViewModel = new NewsViewModel();

        newsViewModel.ListBreakingNews = db.NewsArticles.Where(n => n.PageSetupID == 1).ToList<NewsArticle>();
        newsViewModel.ListMainArticle = db.NewsArticles.Where(n => n.PageSetupID == 2).ToList<NewsArticle>();
        newsViewModel.ListSubNews1 = db.NewsArticles.Where(n => n.PageSetupID == 3).ToList<NewsArticle>();
        newsViewModel.ListSubNews2 = db.NewsArticles.Where(n => n.PageSetupID == 4).ToList<NewsArticle>();
        newsViewModel.ListSubNews3 = db.NewsArticles.Where(n => n.PageSetupID == 5).ToList<NewsArticle>();

        return View(newsViewModel);
    }

    [HttpPost]
    public ActionResult ManageNewsArticles(NewsViewModel newsViewModel)
    {
        if (ModelState.IsValid)
        {
            db.SaveChanges();
            return RedirectToAction("Admin");
        }

        return View(newsViewModel);
    }
</code>```

here is my View

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TrueNews.ViewModels.NewsViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Manage News Articles
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Manage News Articles</h2>

    <% Html.EnableClientValidation(); %>

    <% using (Html.BeginForm(Model)) {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <%: Html.EditorForModel(Model) %>
            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%: Html.ActionLink("Back to Admin Controls", "Admin") %>
    </div>
</asp:Content>
</code>```

NewsViewModel

```<code>public class NewsViewModel
    {
        public List<NewsArticle> ListBreakingNews { get; set; }
        public List<NewsArticle> ListMainArticle { get; set; }
        public List<NewsArticle> ListSubNews1 { get; set; }
        public List<NewsArticle> ListSubNews2 { get; set; }
        public List<NewsArticle> ListSubNews3 { get; set; }
    } // End of Class
</code>```

答:
I couldn't get your view to display correctly using the EditorForModel syntax, however I did replicate your problem and found this article which provides one way of solving it:

http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx

I created a quick table NewsArticle containing Id and Stuff columns and then had the following form in the view:

```<code><% using (Html.BeginForm())
   {%>
<%: Html.ValidationSummary(true) %>
<fieldset>

    <% for (int i = 0; i < Model.ListBreakingNews.Count; i++)
       { %>
    <div>
        Id</div>
    <div>
        <%= Html.TextBox(string.Format("ListBreakingNews[{0}].Id", i), Model.ListBreakingNews[i].Id) %>
    </div>
    <div>
        Name</div>
    <div>
        <%= Html.TextBox(string.Format("ListBreakingNews[{0}].Stuff", i), Model.ListBreakingNews[i].Stuff) %>
    </div>
    <% } %>
    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
<% } %>
</code>```

and the items in the list were passed when posted. I also found that previously you had Html.BeginForm(Model) which when I added it caused nothing to be passed through in the view model - I am only a newbie to MVC so I don't know why this happens but my code below worked only with Html.BeginForm() and not Html.BeginForm(Model).

I hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
Ok, here is my problem.  I am trying to pass a view model of mine, which has multiple list in it, to my view.  Then in my view i need to edit the different list.  Then on my post i need to save the edits.  Although, when i pass my viewmodel back to my post, it is empty! Can somebody explain what i am doing wrong? i am not worried about saving the information right now, i am just worried about getting the data back to the controller.  The ViewModel is null when i hit that portion.

Controller

    public ActionResult ManageNewsArticles()
    {
        NewsViewModel newsViewModel = new NewsViewModel();

        newsViewModel.ListBreakingNews = db.NewsArticles.Where(n => n.PageSetupID == 1).ToList<NewsArticle>();
        newsViewModel.ListMainArticle = db.NewsArticles.Where(n => n.PageSetupID == 2).ToList<NewsArticle>();
        newsViewModel.ListSubNews1 = db.NewsArticles.Where(n => n.PageSetupID == 3).ToList<NewsArticle>();
        newsViewModel.ListSubNews2 = db.NewsArticles.Where(n => n.PageSetupID == 4).ToList<NewsArticle>();
        newsViewModel.ListSubNews3 = db.NewsArticles.Where(n => n.PageSetupID == 5).ToList<NewsArticle>();

        return View(newsViewModel);
    }

    [HttpPost]
    public ActionResult ManageNewsArticles(NewsViewModel newsViewModel)
    {
        if (ModelState.IsValid)
        {
            db.SaveChanges();
            return RedirectToAction("Admin");
        }

        return View(newsViewModel);
    }

here is my View

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TrueNews.ViewModels.NewsViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Manage News Articles
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Manage News Articles

    <% Html.EnableClientValidation(); %>

    <% using (Html.BeginForm(Model)) {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <%: Html.EditorForModel(Model) %>

                <input type="submit" value="Save" />

        </fieldset>

    <% } %>

        <%: Html.ActionLink("Back to Admin Controls", "Admin") %>

</asp:Content>

NewsViewModel

public class NewsViewModel
    {
        public List<NewsArticle> ListBreakingNews { get; set; }
        public List<NewsArticle> ListMainArticle { get; set; }
        public List<NewsArticle> ListSubNews1 { get; set; }
        public List<NewsArticle> ListSubNews2 { get; set; }
        public List<NewsArticle> ListSubNews3 { get; set; }
    } // End of Class

Body:
I couldn't get your view to display correctly using the EditorForModel syntax, however I did replicate your problem and found this article which provides one way of solving it:

http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx

I created a quick table NewsArticle containing Id and Stuff columns and then had the following form in the view:

<% using (Html.BeginForm())
   {%>
<%: Html.ValidationSummary(true) %>
<fieldset>

    <% for (int i = 0; i < Model.ListBreakingNews.Count; i++)
       { %>
    <div>
        Id</div>
    <div>
        <%= Html.TextBox(string.Format("ListBreakingNews[{0}].Id", i), Model.ListBreakingNews[i].Id) %>
    </div>
    <div>
        Name</div>
    <div>
        <%= Html.TextBox(string.Format("ListBreakingNews[{0}].Stuff", i), Model.ListBreakingNews[i].Stuff) %>
    </div>
    <% } %>
    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
<% } %>

and the items in the list were passed when posted. I also found that previously you had Html.BeginForm(Model) which when I added it caused nothing to be passed through in the view model - I am only a newbie to MVC so I don't know why this happens but my code below worked only with Html.BeginForm() and not Html.BeginForm(Model).

I hope this helps.


问:
Make content fill the whole viewport
https://gyazo.com/1440b13007c6e011ec46218ceecabb6a
As you can see by the screenshot, there is a white border around the main content of the page. Ive tried making everything 100% width etc. but nothing seems to work. The nav bar is just a ul and the bottom part is a container div with other child divs heald inside.</p>

答:
The  element has a default margin. You need to set it to zero:

```<code>body {
    margin: 0;
}
</code>```

Title: Make content fill the whole viewport

Body:
The <body> element has a default margin. You need to set it to zero:

body {
    margin: 0;
}


问:
In Typescript how do I set a new class as the prototype?
This is the output I want to achieve:

MyTypeScriptClass.prototype = new ko.templateEngine();

And this is my TypeScript:

```<code>module Knockout {
    export class MyTypeScriptClass implements KnockoutNativeTemplateEngine {
        allowTemplateRewriting: boolean = false;

        renderTemplateSource(templateSource, bindingContext, options) {
            // does some custom work
        }
    }
}
</code>```

答:
You should be able to use something like the following:

```<code>import * as ko from "knockout";

export class MyTypeScriptClass extends ko.templateEngine {
    allowTemplateRewriting: boolean = false;

    public renderTemplateSource(
        templateSource: Object,
        bindingContext: KnockoutBindingContext,
        options: Object) {

            return /* does some custom work */;
    }
}
</code>```

The output ES5 code is quite different because it uses the __extends helper:

```<code>var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

var ko = require("knockout");

var MyTypeScriptClass = (function (_super) {
    __extends(MyTypeScriptClass, _super);
    function MyTypeScriptClass() {
        var _this = _super.apply(this, arguments) || this;
        _this.allowTemplateRewriting = false;
        return _this;
    }
    MyTypeScriptClass.prototype.renderTemplateSource = function (templateSource, bindingContext, options) {
        return [];
    };
    return MyTypeScriptClass;
}(ko.templateEngine));

exports.MyTypeScriptClass = MyTypeScriptClass;
</code>```

But the behaviour should be the same.

Body:
This is the output I want to achieve:

MyTypeScriptClass.prototype = new ko.templateEngine();

And this is my TypeScript:

module Knockout {
    export class MyTypeScriptClass implements KnockoutNativeTemplateEngine {
        allowTemplateRewriting: boolean = false;

        renderTemplateSource(templateSource, bindingContext, options) {
            // does some custom work
        }
    }
}

Body:
You should be able to use something like the following:

import * as ko from "knockout";

export class MyTypeScriptClass extends ko.templateEngine {
    allowTemplateRewriting: boolean = false;

    public renderTemplateSource(
        templateSource: Object,
        bindingContext: KnockoutBindingContext,
        options: Object) {

            return /* does some custom work */;
    }
}

The output ES5 code is quite different because it uses the __extends helper:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

var ko = require("knockout");

var MyTypeScriptClass = (function (_super) {
    __extends(MyTypeScriptClass, _super);
    function MyTypeScriptClass() {
        var _this = _super.apply(this, arguments) || this;
        _this.allowTemplateRewriting = false;
        return _this;
    }
    MyTypeScriptClass.prototype.renderTemplateSource = function (templateSource, bindingContext, options) {
        return [];
    };
    return MyTypeScriptClass;
}(ko.templateEngine));

exports.MyTypeScriptClass = MyTypeScriptClass;

But the behaviour should be the same.


问:
Why does the variable value get deleted when placed after DIRECTORY_SEPARATOR?
I'm trying to get this path:

C:\xampp\htdocs\site\folder\filename.jpg

By doing:

```<code>$i = new Imagick('C:\xampp\htdocs\site\folder' . DIRECTORY_SEPARATOR . $filename);
</code>```

This returns:

```<code>C:\xampp\htdocs\site\folder\
</code>```

But it doesn't have the $filename.

I have also tried:

```<code>$i = new Imagick(__DIR__ . DIRECTORY_SEPARATOR . 'folder' . DIRECTORY_SEPARATOR . $filename);
</code>```

This returns:

```<code>C:\xampp\htdocs\site\files\folder\filename.jpg
</code>```

So I tried adding ..\ to get away from the files folder:

```<code>$i = new Imagick(__DIR__ . DIRECTORY_SEPARATOR . '..\folder' .  DIRECTORY_SEPARATOR . $filename);
</code>```

But that returns:

```<code>C:\xampp\htdocs\site\files\..\folder\filename.jpg
</code>```

How can I get to the correct folder?

答:
```<code>$filename = 'filename.jpg';
$i = new Imagick('C:\xampp\htdocs\site\folder' . DIRECTORY_SEPARATOR . $filename);
</code>```

This should give the correct value

Body:
I'm trying to get this path:

C:\xampp\htdocs\site\folder\filename.jpg

By doing:

$i = new Imagick('C:\xampp\htdocs\site\folder' . DIRECTORY_SEPARATOR . $filename);

This returns:

C:\xampp\htdocs\site\folder\

But it doesn't have the $filename.

I have also tried:

$i = new Imagick(__DIR__ . DIRECTORY_SEPARATOR . 'folder' . DIRECTORY_SEPARATOR . $filename);

This returns:

C:\xampp\htdocs\site\files\folder\filename.jpg

So I tried adding ..\ to get away from the files folder:

$i = new Imagick(__DIR__ . DIRECTORY_SEPARATOR . '..\folder' .  DIRECTORY_SEPARATOR . $filename);

But that returns:

C:\xampp\htdocs\site\files\..\folder\filename.jpg

How can I get to the correct folder?

Body:
$filename = 'filename.jpg';
$i = new Imagick('C:\xampp\htdocs\site\folder' . DIRECTORY_SEPARATOR . $filename);

This should give the correct value


问:
constructor initialization function member instantation
MCVE

```<code>#include <map>
class A{
public:
    A(int){

    }
};

class B : public A{
public:
    B()
     : A(filter()){}
    int filter(){
        std::map<int,int> aStuff;
        //new(&m_aStuff)std::map<int,int>;
        m_aStuff = aStuff;
        return 0;
    }
private:
    std::map<int,int> m_aStuff;
};

int main(){
    B b;
    return 0;
}
</code>```

This fails at compile time because m_aStuff is not initialized.
Using answer I added

```<code>new(&m_aStuff)std::map<int,int>;
</code>```

If you uncomment that line it runs at compile time but m_aStuff gets re-initialized anyway when you leave the filter class.

答:
As your unasked question "How do I fix it?" was answered by Yuki without any details I will provide an answer "What happend there?".

In C++ object is constructed from base class. So the order is following:

```<code>A::A(int); // base class constructor
B::B(); // inherited class constructor
</code>```

All member objects are initialized in initializer list:

```<code>B::B()
: // Initializer list begin.
A(), // Base class initialized first.
m_aStuff() // Members of current class are initialized next.
{ // End of initializer list.
    // All members are safe to use.
}
</code>```

This is the order of object initialization. As you can see here the member m_aStuff initialized after base constructor A::A(int).
Constructor is a member function and as every function requires arguments to be evaluated. So the function int B::filter() is called before object is initialized. Which means that member variables are not initialized either. In other words the order of execution is:

Call B::filter()

Modify member variable B::m_aStuff

Call base class constructor A::A(int)

Initialize member variable B::m_aStuff

Obviously step 2 is modifying variable before it was initialized. Depending on implementation of std::map this can cause different behavior (probably undefined).

In fact following two constructions are equal:

```<code>B::B() :
A(0)
{}
</code>```

and

```<code>B::B() :
A(0),
m_aStuff()
{}
</code>```

but in the second case you are initializing it explicitly, while in first case compiler will generate this code for you.

Your solution new(&m_aStuff)std::map<int,int>; initializes object before using it which makes behavior more defined. But next the generated constructor of class B will kick in and B::m_aStuff will be initialized once again. This will set your map to initial state (though I can imagine scenarios in which memory will leak).

Body:
MCVE

#include <map>
class A{
public:
    A(int){

    }
};

class B : public A{
public:
    B()
     : A(filter()){}
    int filter(){
        std::map<int,int> aStuff;
        //new(&m_aStuff)std::map<int,int>;
        m_aStuff = aStuff;
        return 0;
    }
private:
    std::map<int,int> m_aStuff;
};

int main(){
    B b;
    return 0;
}

This fails at compile time because m_aStuff is not initialized.
Using answer I added

new(&m_aStuff)std::map<int,int>;

If you uncomment that line it runs at compile time but m_aStuff gets re-initialized anyway when you leave the filter class.

Body:
As your unasked question "How do I fix it?" was answered by Yuki without any details I will provide an answer "What happend there?".

In C++ object is constructed from base class. So the order is following:

A::A(int); // base class constructor
B::B(); // inherited class constructor

All member objects are initialized in initializer list:

B::B()
: // Initializer list begin.
A(), // Base class initialized first.
m_aStuff() // Members of current class are initialized next.
{ // End of initializer list.
    // All members are safe to use.
}

This is the order of object initialization. As you can see here the member m_aStuff initialized after base constructor A::A(int).
Constructor is a member function and as every function requires arguments to be evaluated. So the function int B::filter() is called before object is initialized. Which means that member variables are not initialized either. In other words the order of execution is:

Call B::filter()

Modify member variable B::m_aStuff

Call base class constructor A::A(int)

Initialize member variable B::m_aStuff

Obviously step 2 is modifying variable before it was initialized. Depending on implementation of std::map this can cause different behavior (probably undefined).

In fact following two constructions are equal:

B::B() :
A(0)
{}

and

B::B() :
A(0),
m_aStuff()
{}

but in the second case you are initializing it explicitly, while in first case compiler will generate this code for you.

Your solution new(&m_aStuff)std::map<int,int>; initializes object before using it which makes behavior more defined. But next the generated constructor of class B will kick in and B::m_aStuff will be initialized once again. This will set your map to initial state (though I can imagine scenarios in which memory will leak).


问:
How to Learn MS SQL Server 2005?
I would like to start learning SQL Server 2005 on my own.  Can anyone recommend good books or websites that will be a good start for me?</p>

答:
Are you learning SQL from scratch?

I would suggest starting with this SQL Tutorial.

However if you know SQL already then this is a good list of tutorials on SQL 2005 features.

OwnerDisplayName: Craig G

Title: How to Learn MS SQL Server 2005?

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Andrew Hare


问:
.net web service hosted within my application
I'm migrating an old Delphi application that I wrote into C#. The application is a datalogger that exposes logged data requests via a SOAP web service interface.

The web service is contained with the delphi graphical windows application, i.e. no need to run a web server like IIS, etc I just run the application and it's up and running under the hood.

I'm looking to do the same in my c# Windows form application, I can find loads of resources on writing web services that are ultimately hosted within IIS but am struggling to find a solution for a self contained web service within my application.

Does anyone have any suggestions or can point me towards any resources on this?

The web service does not neceserily have to be SOAP, REST is fine (in fact probably prefered).

答: If you're wanting to host a service inside your application, it's possible with the System.ServiceModel.ServiceHost class. You need to learn WCF first, but that at least answers your question to get you started. If you have any further questions, leave me a comment or two and I'll update my answer to accommodate your inquiries.


问:
Using Javascript to hide and show options
In the drop down menu below I am trying to make it show other sections or display multiple when selected..

```<code><label>Calls</label>
<select id = "callList">
    <option value = "1">one</option>
    <option value = "2">two</option>
    <option value = "3">three</option>
    <option value = "4">four</option>
</select>
<select id = "Split">
    <option value = "Quality1">Sam's</option>
    <option value = "Quality2">Walmart</option>
</select>
</code>```

so if someone picks option 2 it will display option 1 and 2 but hide the rest.
I am trying to use the js posted below to get it to display correctly but it wont.

```<code>function check() {
    var dropdown = document.getElementById("callList");
    var current_value = dropdown.options[dropdown.selectedIndex].value;

    if (current_value == "1") {
        document.getElementById("Split").style.display = "block";
    }
    else {
        document.getElementById("Split").style.display = "none";
    }
}
</code>```

答:
You are correct.

Just add onchange="check()" in select dropdown as below.

```<code>       <label>Calls</label>
         <select id = "callList" onchange="check()">
           <option value = "1">one</option>
           <option value = "2">two</option>
           <option value = "3">three</option>
           <option value = "4">four</option>
         </select>
         <select id = "Split">
         <option value = "Quality1">Sam's</option>
         <option value = "Quality2">Walmart</option>
         </select>

<script type="text/javascript">
function check() {
var dropdown = document.getElementById("callList");
var current_value = dropdown.options[dropdown.selectedIndex].value;

if (current_value == "1") {
    document.getElementById("Split").style.display = "block";
}
else {
    document.getElementById("Split").style.display = "none";
}
}
</script>
</code>```

Body:
In the drop down menu below I am trying to make it show other sections or display multiple when selected..

Calls
<select id = "callList">
    <option value = "1">one</option>
    <option value = "2">two</option>
    <option value = "3">three</option>
    <option value = "4">four</option>
</select>
<select id = "Split">
    <option value = "Quality1">Sam's</option>
    <option value = "Quality2">Walmart</option>
</select>

so if someone picks option 2 it will display option 1 and 2 but hide the rest.
I am trying to use the js posted below to get it to display correctly but it wont.

function check() {
    var dropdown = document.getElementById("callList");
    var current_value = dropdown.options[dropdown.selectedIndex].value;

    if (current_value == "1") {
        document.getElementById("Split").style.display = "block";
    }
    else {
        document.getElementById("Split").style.display = "none";
    }
}

Body:
You are correct.

Just add onchange="check()" in select dropdown as below.

       <label>Calls</label>
         <select id = "callList" onchange="check()">
           <option value = "1">one</option>
           <option value = "2">two</option>
           <option value = "3">three</option>
           <option value = "4">four</option>
         </select>
         <select id = "Split">
         <option value = "Quality1">Sam's</option>
         <option value = "Quality2">Walmart</option>
         </select>

<script type="text/javascript">
function check() {
var dropdown = document.getElementById("callList");
var current_value = dropdown.options[dropdown.selectedIndex].value;

if (current_value == "1") {
    document.getElementById("Split").style.display = "block";
}
else {
    document.getElementById("Split").style.display = "none";
}
}
</script>


问:
How to ignore return types while using SFINAE
I have this piece of code:

```<code>template <typename T, typename R>
struct is_dereferenceable_exact
{
    typedef char yes;
    typedef struct { char dummy[2]; } no;

    template <typename U, R (U::*)() const>
    struct SFINAE;

    template <typename U>
    static yes  test(SFINAE<U, &U::operator*>*);

    template <typename U>
    static no   test(...);

    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
</code>```

This struct is used for checking that given type is dereferencable, and result of dereferencing has type R. I used good old approach with ellipsis and sizeof instead of void_t or detect idiom knowingly — I want to use only C++-03-features (if possible).

But I just cannot write analogous struct which determines only existence of T::operator* ignoring its type. Can you help me?

UPD I can generalize my question: if I can write some trait using return types, how I can eliminate them like in above primer?

答:
Maybe you could also make use of sizeof operator trick:

```<code>#include <iostream>

template <typename T>
struct is_dereferenceable_exact
{
    typedef char yes;
    typedef struct { char dummy[2]; } no;

    template <int>
    struct SFINAE;

    template <typename U>
    static yes  test(SFINAE<sizeof(&U::operator*)>*);

    template <typename U>
    static no   test(...);

    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

struct A {
    int operator*() { return 0; }
};

struct B { };

int main() {
    std::cout << is_dereferenceable_exact<A>::value << std::endl;
    std::cout << is_dereferenceable_exact<B>::value << std::endl;
    return 0;
}
</code>```

[live demo]

Body:
I have this piece of code:

template <typename T, typename R>
struct is_dereferenceable_exact
{
    typedef char yes;
    typedef struct { char dummy[2]; } no;

    template <typename U, R (U::*)() const>
    struct SFINAE;

    template <typename U>
    static yes  test(SFINAE*);

    template <typename U>
    static no   test(...);

    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

This struct is used for checking that given type is dereferencable, and result of dereferencing has type R. I used good old approach with ellipsis and sizeof instead of void_t or detect idiom knowingly — I want to use only C++-03-features (if possible).

But I just cannot write analogous struct which determines only existence of T::operator* ignoring its type. Can you help me?

UPD I can generalize my question: if I can write some trait using return types, how I can eliminate them like in above primer?

Body:
Maybe you could also make use of sizeof operator trick:

#include <iostream>

template <typename T>
struct is_dereferenceable_exact
{
    typedef char yes;
    typedef struct { char dummy[2]; } no;

    template <int>
    struct SFINAE;

    template <typename U>
    static yes  test(SFINAE<sizeof(&U::operator*)>*);

    template <typename U>
    static no   test(...);

    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

struct A {
    int operator*() { return 0; }
};

struct B { };

int main() {
    std::cout << is_dereferenceable_exact<A>::value << std::endl;
    std::cout << is_dereferenceable_exact<B>::value << std::endl;
    return 0;
}

[live demo]


问:
Button to go back to MainActivity
I want to create a button that would lead the user straight back to main activity which doesn't have the android name="com.example.example".

It has android.intent.etc...

How can I reference my button to go back to this activity?

答:
```<code>public void onBackPressed(){
    finish();
}
</code>```

Title: Button to go back to MainActivity


问:
Prevent Protobuffer from renaming Fields (Classes, Members, Enum Items)
I am trying to port a project from Google Protocol Buffers 3.0.0-beta-2 to 3.1.0. After recompiling my .proto file I noticed that I had a number of compilation errors with the project due to protoc enforcing a coding standard that I did not choose and renaming fields accordingly. I do not want to rename e.g. MDData to Mddata or XYServer to Xyserver inside the project since the intended meanings of the abbreviations are now lost and possibly subject to change in further Protocol Buffer releases to come.

I have seen this behaviour on the C# part so far and am not sure if this is also the case for generated code for C++.

TL;DR:

Is there a way to disable automatic code style changes inside Google Protocol Buffer's Proto Compiler (and keep my own formatting) of fields?

答:
There is no way to enforce this short of writing your own code generator.  Only the public API of the stubs is considered stable.

Under the hood, the protoc compiler regenerates the code from scratch each time, so there is no way for it to know the original style of the file.  It would need to be passed in the original generated file along with the proto in order to do this.

That said, if you want to modify the code generator, it is certainly possible.


答:
You need to have an event to call your function.

Test something like this:

```<code><label>Calls</label>
<select id = "callList" onchange="check()">
    <option value = "1">one</option>
    <option value = "2">two</option>
    <option value = "3">three</option>
    <option value = "4">four</option>
</select>
<select id = "Split">
    <option value = "Quality1">Sam's</option>
    <option value = "Quality2">Walmart</option>
</select>
</code>```

Title: Using Javascript to hide and show options

Body:
You need to have an event to call your function.

Test something like this:

<label>Calls</label>
<select id = "callList" onchange="check()">
    <option value = "1">one</option>
    <option value = "2">two</option>
    <option value = "3">three</option>
    <option value = "4">four</option>
</select>
<select id = "Split">
    <option value = "Quality1">Sam's</option>
    <option value = "Quality2">Walmart</option>
</select>


问:
type arguments do not conform to trait Subtractable's type parameter bounds
After upgrading to Scala 2.12, I am having a weird compilation issue of this code:

```<code>val c = Map("a" -> Set[Map[String, String]](), "b" -> Map[String, String]())
</code>```

It is throwing this exception:

```<code>Error:(19, 7) type arguments [?,Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Equals]]{def seq: Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Equals]}]{def seq: Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Equals]]{def seq: Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Equals]}}] do not conform to trait Subtractable's type parameter bounds [A,+Repr <: scala.collection.generic.Subtractable[A,Repr]]
</code>```

答:
It looks like a bug. You could post it in bug tracker if analog is absent.

As workaround try to append values to map.

```<code>scala> val c = Map.empty[String,Iterable[Any]] + ("a" -> Set[Map[String, String]]()) + ("b" -> Map[S
tring, String]())
c: scala.collection.immutable.Map[String,Iterable[Any]] = Map(a -> Set(), b -> Map())
</code>```

Body:
After upgrading to Scala 2.12, I am having a weird compilation issue of this code:

val c = Map("a" -> Set[Map[String, String]](), "b" -> Map[String, String]())

It is throwing this exception:

Error:(19, 7) type arguments [?,Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Equals]]{def seq: Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Equals]}]{def seq: Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Equals]]{def seq: Iterable[Equals] with String with scala.collection.immutable.Map[String,String] => Any with scala.collection.generic.Subtractable[_ >: String with scala.collection.immutable.Map[String,String] <: Object, Equals]}}] do not conform to trait Subtractable's type parameter bounds [A,+Repr <: scala.collection.generic.Subtractable[A,Repr]]

Body:
It looks like a bug. You could post it in bug tracker if analog is absent.

As workaround try to append values to map.

scala> val c = Map.empty[String,Iterable[Any]] + ("a" -> Set[Map[String, String]]()) + ("b" -> Map[S
tring, String]())
c: scala.collection.immutable.Map[String,Iterable[Any]] = Map(a -> Set(), b -> Map())


问:
Imacros IF = #EANF# MACroERROR
I'm using the below code to scrape names from twitter.

```<code>VERSION BUILD=11.5.499.3066
TAB T=1
TAB CLOSEALLOTHERS
SET !ERRORIGNORE NO
SET !LOOP 20
TAG POS=45 TYPE=DIV ATTR=CLASS:ProfileNameTruncated<SP>account-group EXTRACT=TXT
SET Name  EVAL("var extract  = \"{{!EXTRACT}}\"; if (extract == \"#EANF#\") MacroError(\"Value is not in the set range\";")

SAVEAS TYPE=EXTRACT FOLDER=* FILE=Names.csv
WAIT SECONDS=2
</code>```

i'm getting this message Error -1250: JScript statement in EVAL contains the following error: Expected ',' or ')'. Line 7: SET Name  EVAL("var extract  = \"{{!EXTRACT}}\"; if (extract == \"#EANF#\") MacroError(\"Value is not in the set range\";")

i'm all new and the beginner.  Please help
Thanks

答:
I am not able to understand what are you actually want to achieve. Since ther us no TAG POS value loop so it will extract the same value always. Here is the edited code in javascript

```<code>     var macro;
        macro =  "CODE:";
        macro +=  "VERSION BUILD=11.5.499.3066" + "\n";
        macro +=  "TAB T=1" + "\n";
        macro +=  "TAB CLOSEALLOTHERS" + "\n";
        macro +=  "SET !ERRORIGNORE NO" + "\n";
        macro +=  "SET !LOOP {{i}}" + "\n";
        macro +=  "TAG POS={{!LOOP}} TYPE=DIV ATTR=CLASS:ProfileNameTruncated<SP>account-group EXTRACT=TXT" + "\n";

    var savemacro;
        savemacro =  "CODE:";
        savemacro +=  "SET !EXTRACT {{tname}}" + "\n";
        savemacro +=  "SAVEAS TYPE=EXTRACT FOLDER=* FILE=Names.csv" + "\n";
        savemacro +=  "WAIT SECONDS=2" + "\n";

    for (i=1;i<=10000000; i++) {
     ret = iimSet("i", i);
    retcode = iimPlay(macro)
     var tname = iimGetLastExtract(1);
    if (tname == "#EANF#"){
     tname = "";
    }
ret = iimSet("tname", tname);
 iimPlay(savemacro)
}
</code>```

Copy the code in notepad and save as *.js extension

This code will replace the #EANF# with nothing i.e. you will get the empty row. If the extracted value is #EANF#
Change the value of i to the number where the TAG POS start. Right now it's 1.

Title: Imacros IF = #EANF# MACroERROR

Body:
I'm using the below code to scrape names from twitter.

VERSION BUILD=11.5.499.3066
TAB T=1
TAB CLOSEALLOTHERS
SET !ERRORIGNORE NO
SET !LOOP 20
TAG POS=45 TYPE=DIV ATTR=CLASS:ProfileNameTruncated<SP>account-group EXTRACT=TXT
SET Name  EVAL("var extract  = \"{{!EXTRACT}}\"; if (extract == \"#EANF#\") MacroError(\"Value is not in the set range\";")

SAVEAS TYPE=EXTRACT FOLDER=* FILE=Names.csv
WAIT SECONDS=2

i'm getting this message Error -1250: JScript statement in EVAL contains the following error: Expected ',' or ')'. Line 7: SET Name  EVAL("var extract  = \"{{!EXTRACT}}\"; if (extract == \"#EANF#\") MacroError(\"Value is not in the set range\";")

i'm all new and the beginner.  Please help
Thanks

Body:
I am not able to understand what are you actually want to achieve. Since ther us no TAG POS value loop so it will extract the same value always. Here is the edited code in javascript

     var macro;
        macro =  "CODE:";
        macro +=  "VERSION BUILD=11.5.499.3066" + "\n";
        macro +=  "TAB T=1" + "\n";
        macro +=  "TAB CLOSEALLOTHERS" + "\n";
        macro +=  "SET !ERRORIGNORE NO" + "\n";
        macro +=  "SET !LOOP {{i}}" + "\n";
        macro +=  "TAG POS={{!LOOP}} TYPE=DIV ATTR=CLASS:ProfileNameTruncated<SP>account-group EXTRACT=TXT" + "\n";

    var savemacro;
        savemacro =  "CODE:";
        savemacro +=  "SET !EXTRACT {{tname}}" + "\n";
        savemacro +=  "SAVEAS TYPE=EXTRACT FOLDER=* FILE=Names.csv" + "\n";
        savemacro +=  "WAIT SECONDS=2" + "\n";

    for (i=1;i<=10000000; i++) {
     ret = iimSet("i", i);
    retcode = iimPlay(macro)
     var tname = iimGetLastExtract(1);
    if (tname == "#EANF#"){
     tname = "";
    }
ret = iimSet("tname", tname);
 iimPlay(savemacro)
}

Copy the code in notepad and save as *.js extension

This code will replace the #EANF# with nothing i.e. you will get the empty row. If the extracted value is #EANF#
Change the value of i to the number where the TAG POS start. Right now it's 1.


问:
Add selection to range in jquery
I have a problem. For example I have a
Helloworld
. And now I want to select (for example) 5th to 9th word. So, I want to have Helloworld ("worl" is hightlighted). Any ideas, how to do this?

答:
Not sure If this is what you want but you can use  or use  with appropriate style property.

As in your case:

```<code><div id="id">Hello<mark style="background-color: #f0f0f5">wor</mark>ld</div>
</code>```

Or do it this way

```<code><div id="id">Hello<span style="background-color: #f0f0f5;font-weight:bold">wor</span>ld</div>
</code>```

Title: Add selection to range in jquery

Body:
Not sure If this is what you want but you can use <mark> or use <span> with appropriate style property.

As in your case:

<div id="id">Hello<mark style="background-color: #f0f0f5">wor</mark>ld</div>

Or do it this way

<div id="id">Hello<span style="background-color: #f0f0f5;font-weight:bold">wor</span>ld</div>


问:
How can I map a shared folder from my container on Mac?
I have a folder insider a Docker container that is shared through Samba. I can map this folder on Windows without problem running something like:

```<code>net use z: \\vm_ip\folder
</code>```

In the case above, z: is the drive that I created with the content from the shared folder.

How could I map that same folder on Mac?

答:
If you are using Docker For Mac, the /Users folder from your mac is already mounted inside the virtual machine inside the Docker For Mac application runs. It is accessible via /Users inside the vm. That means you can do: docker run -v /Users/some/path:/folder ... in the container's /folder will meant to /Users/some/path in the vm, which maps back to your mac's /Users/some/path.

If you want some other location other than /Users, click on the whale icon at the top of your screen, choose Preferences, and then click on the File Sharing tab. If you have mounted a samba/cifs share somewhere on your mac, you can add that path here.

Body:
I have a folder insider a Docker container that is shared through Samba. I can map this folder on Windows without problem running something like:

net use z: \\vm_ip\folder

In the case above, z: is the drive that I created with the content from the shared folder.

How could I map that same folder on Mac?


问:
How to cancel Java 8 completable future?
I am playing with Java 8 completable futures. I have the following code:

```<code>CountDownLatch waitLatch = new CountDownLatch(1);

CompletableFuture<?> future = CompletableFuture.runAsync(() -> {
    try {
        System.out.println("Wait");
        waitLatch.await(); //cancel should interrupt
        System.out.println("Done");
    } catch (InterruptedException e) {
        System.out.println("Interrupted");
        throw new RuntimeException(e);
    }
});

sleep(10); //give it some time to start (ugly, but works)
future.cancel(true);
System.out.println("Cancel called");

assertTrue(future.isCancelled());

assertTrue(future.isDone());
sleep(100); //give it some time to finish
</code>```

Using runAsync I schedule execution of a code that waits on a latch. Next I cancel the future, expecting an interrupted exception to be thrown inside. But it seems that the thread remains blocked on the await call and the InterruptedException is never thrown even though the future is canceled (assertions pass). An equivalent code using ExecutorService works as expected. Is it a bug in the CompletableFuture or in my example?

答:
When you call CompletableFuture#cancel, you only stop the downstream part of the chain. Upstream part, i. e. something that will eventually call complete(...) or completeExceptionally(...), doesn't get any signal that the result is no more needed.

What are those 'upstream' and 'downstream' things?

Let's consider the following code:

```<code>CompletableFuture
        .supplyAsync(() -> "hello")               //1
        .thenApply(s -> s + " world!")            //2
        .thenAccept(s -> System.out.println(s));  //3
</code>```

Here, the data flows from top to bottom - from being created by supplier, through being modified by function, to being consumed by println. The part above particular step is called upstream, and the part below is downstream. E. g. steps 1 and 2 are upstream for step 3.

Here's what happens behind the scenes. This is not precise, rather it's a convenient mind model of what's going on.

Supplier (step 1) is being executed (inside the JVM's common ForkJoinPool).

The result of the supplier is then being passed by complete(...) to the next CompletableFuture downstream.

Upon receiving the result, that CompletableFuture invokes next step - a function (step 2) which takes in previous step result and returns something that will be passed further, to the downstream CompletableFuture's complete(...).

Upon receiving the step 2 result, step 3 CompletableFuture invokes the consumer, System.out.println(s). After consumer is finished, the downstream CompletableFuture will receive it's value, (Void) null

As we can see, each CompletableFuture in this chain has to know who are there downstream waiting for the value to be passed to their's complete(...) (or completeExceptionally(...)). But the CompletableFuture don't have to know anything about it's upstream (or upstreams - there might be several).

Thus, calling cancel() upon step 3 doesn't abort steps 1 and 2, because there's no link from step 3 to step 2.

It is supposed that if you're using CompletableFuture then your steps are small enough so that there's no harm if a couple of extra steps will get executed.

If you want cancellation to be propagated upstream, you have two options:

Implement this yourself - create a dedicated CompletableFuture (name it like cancelled) which is checked after every step (something like step.applyToEither(cancelled, Function.identity()))

Use reactive stack like RxJava 2, ProjectReactor/Flux or Akka Streams

Body:
I am playing with Java 8 completable futures. I have the following code:

CountDownLatch waitLatch = new CountDownLatch(1);

CompletableFuture<?> future = CompletableFuture.runAsync(() -> {
    try {
        System.out.println("Wait");
        waitLatch.await(); //cancel should interrupt
        System.out.println("Done");
    } catch (InterruptedException e) {
        System.out.println("Interrupted");
        throw new RuntimeException(e);
    }
});

sleep(10); //give it some time to start (ugly, but works)
future.cancel(true);
System.out.println("Cancel called");

assertTrue(future.isCancelled());

assertTrue(future.isDone());
sleep(100); //give it some time to finish

Using runAsync I schedule execution of a code that waits on a latch. Next I cancel the future, expecting an interrupted exception to be thrown inside. But it seems that the thread remains blocked on the await call and the InterruptedException is never thrown even though the future is canceled (assertions pass). An equivalent code using ExecutorService works as expected. Is it a bug in the CompletableFuture or in my example?

Body:
When you call CompletableFuture#cancel, you only stop the downstream part of the chain. Upstream part, i. e. something that will eventually call complete(...) or completeExceptionally(...), doesn't get any signal that the result is no more needed.

What are those 'upstream' and 'downstream' things?

Let's consider the following code:

CompletableFuture
        .supplyAsync(() -> "hello")               //1
        .thenApply(s -> s + " world!")            //2
        .thenAccept(s -> System.out.println(s));  //3

Here, the data flows from top to bottom - from being created by supplier, through being modified by function, to being consumed by println. The part above particular step is called upstream, and the part below is downstream. E. g. steps 1 and 2 are upstream for step 3.

Here's what happens behind the scenes. This is not precise, rather it's a convenient mind model of what's going on.

Supplier (step 1) is being executed (inside the JVM's common ForkJoinPool).

The result of the supplier is then being passed by complete(...) to the next CompletableFuture downstream.

Upon receiving the result, that CompletableFuture invokes next step - a function (step 2) which takes in previous step result and returns something that will be passed further, to the downstream CompletableFuture's complete(...).

Upon receiving the step 2 result, step 3 CompletableFuture invokes the consumer, System.out.println(s). After consumer is finished, the downstream CompletableFuture will receive it's value, (Void) null

As we can see, each CompletableFuture in this chain has to know who are there downstream waiting for the value to be passed to their's complete(...) (or completeExceptionally(...)). But the CompletableFuture don't have to know anything about it's upstream (or upstreams - there might be several).

Thus, calling cancel() upon step 3 doesn't abort steps 1 and 2, because there's no link from step 3 to step 2.

It is supposed that if you're using CompletableFuture then your steps are small enough so that there's no harm if a couple of extra steps will get executed.

If you want cancellation to be propagated upstream, you have two options:

Implement this yourself - create a dedicated CompletableFuture (name it like cancelled) which is checked after every step (something like step.applyToEither(cancelled, Function.identity()))

Use reactive stack like RxJava 2, ProjectReactor/Flux or Akka Streams