问:
Enable role authentication with spring boot (security) and keycloak?
I am trying to do a simple thing.

Want to make a request to a single endpoint and send a bearer token (from a client), I want this token to be validated and depending on the role assigned on keycloak accept/deny request on my endpoint.

I followed many tutorials and even books but most of all them I simply dont understand.

Followed this to setup my keycloak info (realm, role, user)
https://medium.com/@bcarunmail/securing-rest-api-using-keycloak-and-spring-oauth2-6ddf3a1efcc2

So,

I basically set up my keycloak with a client, a user with a specific role "user" and configured it like this:

```<code>@Configuration
@KeycloakConfiguration
//@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConf extends KeycloakWebSecurityConfigurerAdapter
{
    /**
     * Registers the KeycloakAuthenticationProvider with the authentication manager.
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }

    /**
     * Defines the session authentication strategy.
     */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    @Bean
    public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(
            KeycloakAuthenticationProcessingFilter filter) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
        registrationBean.setEnabled(false);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(
            KeycloakPreAuthActionsFilter filter) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
        registrationBean.setEnabled(false);
        return registrationBean;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        super.configure(http);
        http
                .authorizeRequests()
                .antMatchers("/user/*").hasRole("admin")
                .antMatchers("/admin*").hasRole("user")

    }
}
</code>```

I dont understand why at many tutorials I see this(as the last rule):

```<code>.anyRequest().permitAll();
</code>```

Basically when I set that I have no security, I can call the endpoints without a bearer token.

But when I add this as last rule

```<code> .anyRequest().denyAll();
</code>```

I always get a 403.

Debbugging I found this:

Request is to process authentication

```<code>f.KeycloakAuthenticationProcessingFilter : Attempting Keycloak authentication
o.k.a.BearerTokenRequestAuthenticator    : Found [1] values in authorization header, selecting the first value for Bearer.
o.k.a.BearerTokenRequestAuthenticator    : Verifying access_token
o.k.a.BearerTokenRequestAuthenticator    : successful authorized
a.s.a.SpringSecurityRequestAuthenticator : Completing bearer authentication. Bearer roles: []
o.k.adapters.RequestAuthenticator        : User 'testuser' invoking 'http://localhost:9090/api/user/123' on client 'users'
o.k.adapters.RequestAuthenticator        : Bearer AUTHENTICATED
f.KeycloakAuthenticationProcessingFilter : Auth outcome: AUTHENTICATED
o.s.s.authentication.ProviderManager     : Authentication attempt using org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider
o.s.s.core.session.SessionRegistryImpl   : Registering session 5B871A0E2AF55B70DC8E3B7436D79333, for principal testuser
f.KeycloakAuthenticationProcessingFilter : Authentication success using bearer token/basic authentication. Updating SecurityContextHolder to contain: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@355f68d6: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@5d7a32a9; Not granted any authorities
[nio-9090-exec-3] o.s.security.web.FilterChainProxy        : /api/user/123 at position 8 of 15 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
nio-9090-exec-3] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
[nio-9090-exec-3] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
</code>```

Seems like I get no bearer roles ...

My dependencies:

```<code>        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
            <version>6.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-security-adapter</artifactId>
            <version>6.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
</code>```

My problem?

I request an access token sending:

```<code>client_id -> my client from keycloak
username -> my user from keycloak
password -> my password from keycloak
grant_type -> password
client_secret -> from keycloak
</code>```

I get a token and then I use to request to my app endoint. My requests are always valid no matter what endpoint I use (the one with role user or with role admin).

At my properties I have something like this:

```<code>keycloak:
  auth-server-url: http://localhost:8080/auth/
  resource: users-api
  credentials:
    secret : my-secret
  use-resource-role-mappings : true
  realm: my-realm
  realmKey:  my-key
  public-client: true
  principal-attribute: preferred_username
  bearer-only: true
</code>```

Any idea how to actually enabling the roles in this case?

Do I have to configure a client to use JWT? any ideas?

I also added the annotations on my endpoint

```<code>@Secured("admin")
@PreAuthorize("hasAnyAuthority('admin')")
</code>```

but seems they dont do anything...

-- EDIT --

After fixed the url to match the resource I still get 403.

```<code>"realm_access": {
    "roles": [
      "offline_access",
      "admin",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },
</code>```

Is it somehow related the resource_access with my problem?

答:
permitAll:

Whenever you want to allow any request to access the particular resource/URL you can use permitAll. For example, the Login URL should be accessible to everyone.

denyAll:

Whenever you want to block the access of particular URL no matter from where the request comes or who is making request(ADMIN)

You also have miss-match with URL and Role (you are granting URL with admin to USER and vise-versa). (It's a good practice to use the role as ROLE_ADMIN or ADMIN or USER) Form your stack I can see Not granted any authorities so please recheck the code with authorities

```<code> http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers("/api/user/**").hasRole("ADMIN")
         .antMatchers("/api/admin/**").hasRole("USER")
         .anyRequest().authenticated();
</code>```

Body:
I am trying to do a simple thing.

Want to make a request to a single endpoint and send a bearer token (from a client), I want this token to be validated and depending on the role assigned on keycloak accept/deny request on my endpoint.

I followed many tutorials and even books but most of all them I simply dont understand.

Followed this to setup my keycloak info (realm, role, user)
https://medium.com/@bcarunmail/securing-rest-api-using-keycloak-and-spring-oauth2-6ddf3a1efcc2

So,

I basically set up my keycloak with a client, a user with a specific role "user" and configured it like this:

@Configuration
@KeycloakConfiguration
//@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConf extends KeycloakWebSecurityConfigurerAdapter
{
    /**
     * Registers the KeycloakAuthenticationProvider with the authentication manager.
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }

    /**
     * Defines the session authentication strategy.
     */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    @Bean
    public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(
            KeycloakAuthenticationProcessingFilter filter) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
        registrationBean.setEnabled(false);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(
            KeycloakPreAuthActionsFilter filter) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
        registrationBean.setEnabled(false);
        return registrationBean;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        super.configure(http);
        http
                .authorizeRequests()
                .antMatchers("/user/*").hasRole("admin")
                .antMatchers("/admin*").hasRole("user")

    }
}

I dont understand why at many tutorials I see this(as the last rule):

.anyRequest().permitAll();

Basically when I set that I have no security, I can call the endpoints without a bearer token.

But when I add this as last rule

 .anyRequest().denyAll();

I always get a 403.

Debbugging I found this:

Request is to process authentication

f.KeycloakAuthenticationProcessingFilter : Attempting Keycloak authentication
o.k.a.BearerTokenRequestAuthenticator    : Found [1] values in authorization header, selecting the first value for Bearer.
o.k.a.BearerTokenRequestAuthenticator    : Verifying access_token
o.k.a.BearerTokenRequestAuthenticator    : successful authorized
a.s.a.SpringSecurityRequestAuthenticator : Completing bearer authentication. Bearer roles: []
o.k.adapters.RequestAuthenticator        : User 'testuser' invoking 'http://localhost:9090/api/user/123' on client 'users'
o.k.adapters.RequestAuthenticator        : Bearer AUTHENTICATED
f.KeycloakAuthenticationProcessingFilter : Auth outcome: AUTHENTICATED
o.s.s.authentication.ProviderManager     : Authentication attempt using org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider
o.s.s.core.session.SessionRegistryImpl   : Registering session 5B871A0E2AF55B70DC8E3B7436D79333, for principal testuser
f.KeycloakAuthenticationProcessingFilter : Authentication success using bearer token/basic authentication. Updating SecurityContextHolder to contain: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@355f68d6: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@5d7a32a9; Not granted any authorities
[nio-9090-exec-3] o.s.security.web.FilterChainProxy        : /api/user/123 at position 8 of 15 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
nio-9090-exec-3] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
[nio-9090-exec-3] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)

Seems like I get no bearer roles ...

My dependencies:

        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
            <version>6.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-security-adapter</artifactId>
            <version>6.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

My problem?

I request an access token sending:

client_id -> my client from keycloak
username -> my user from keycloak
password -> my password from keycloak
grant_type -> password
client_secret -> from keycloak

I get a token and then I use to request to my app endoint. My requests are always valid no matter what endpoint I use (the one with role user or with role admin).

At my properties I have something like this:

keycloak:
  auth-server-url: http://localhost:8080/auth/
  resource: users-api
  credentials:
    secret : my-secret
  use-resource-role-mappings : true
  realm: my-realm
  realmKey:  my-key
  public-client: true
  principal-attribute: preferred_username
  bearer-only: true

Any idea how to actually enabling the roles in this case?

Do I have to configure a client to use JWT? any ideas?

I also added the annotations on my endpoint

@Secured("admin")
@PreAuthorize("hasAnyAuthority('admin')")

but seems they dont do anything...

-- EDIT --

After fixed the url to match the resource I still get 403.

"realm_access": {
    "roles": [
      "offline_access",
      "admin",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },

Is it somehow related the resource_access with my problem?

Body:
permitAll:

Whenever you want to allow any request to access the particular resource/URL you can use permitAll. For example, the Login URL should be accessible to everyone.

denyAll:

Whenever you want to block the access of particular URL no matter from where the request comes or who is making request(ADMIN)

You also have miss-match with URL and Role (you are granting URL with admin to USER and vise-versa). (It's a good practice to use the role as ROLE_ADMIN or ADMIN or USER) Form your stack I can see Not granted any authorities so please recheck the code with authorities

 http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers("/api/user/**").hasRole("ADMIN")
         .antMatchers("/api/admin/**").hasRole("USER")
         .anyRequest().authenticated();


来源: stackexchange

问:
Gcloud ai-platform, can't create model with own prediction-class
I try following AI Platform tutorial to upload a model and a prediction routine but one part fail and I don't understand why.

My prediction class is the same as in their tutorial:

```<code>%%writefile predictor.py
import os
import pickle

import numpy as np
from sklearn.datasets import load_iris
from sklearn.externals import joblib

class MyPredictor(object):
  def __init__(self, model, preprocessor):
    self._model = model
    self._preprocessor = preprocessor
    self._class_names = load_iris().target_names

  def predict(self, instances, **kwargs):
    inputs = np.asarray(instances)
    preprocessed_inputs = self._preprocessor.preprocess(inputs)
    if kwargs.get('probabilities'):
      probabilities = self._model.predict_proba(preprocessed_inputs)
      return probabilities.tolist()
    else:
      outputs = self._model.predict(preprocessed_inputs)
      return [self._class_names[class_num] for class_num in outputs]

  @classmethod
  def from_path(cls, model_dir):
    model_path = os.path.join(model_dir, 'model.joblib')
    model = joblib.load(model_path)

    preprocessor_path = os.path.join(model_dir, 'preprocessor.pkl')
    with open(preprocessor_path, 'rb') as f:
      preprocessor = pickle.load(f)

    return cls(model, preprocessor)
</code>```

the code I use to create my model in cloud is:

```<code>! gcloud beta ai-platform versions create {VERSION_NAME} \
  --model {MODEL_NAME} \
  --runtime-version 1.13 \
  --python-version 3.5 \
  --origin gs://{BUCKET_NAME}/custom_prediction_routine_tutorial/model/ \
  --package-uris gs://{BUCKET_NAME}/custom_prediction_routine_tutorial/my_custom_code-0.1.tar.gz \
  --prediction-class predictor.MyPredictor
</code>```

But I end up with such an odd error:

```<code>ERROR: (gcloud.beta.ai-platform.versions.create) Bad model detected with error:  "Failed to load model: Unexpected error when loading the model: 'ascii' codec can't decode byte 0xf9 in position 2: ordinal not in range(128) (Error code: 0)"
</code>```

The thing is that when I run the same command without the:

```<code>--prediction-class predictor.MyPredictor
</code>```

it work fine.

Does someone know the reason of this ? I think model.joblib might have an encoding problem but when I load it myself there is nothing wrong

答:
I've find the solution,

In the tutorial they use pickle to save the preprocessor object created, and Joblib to save the model.

You need to use Joblib to save both and then send it to google storage.

ContentLicense: CC BY-SA 4.0

Body:
I try following AI Platform tutorial to upload a model and a prediction routine but one part fail and I don't understand why.

My prediction class is the same as in their tutorial:

%%writefile predictor.py
import os
import pickle

import numpy as np
from sklearn.datasets import load_iris
from sklearn.externals import joblib

class MyPredictor(object):
  def __init__(self, model, preprocessor):
    self._model = model
    self._preprocessor = preprocessor
    self._class_names = load_iris().target_names

  def predict(self, instances, **kwargs):
    inputs = np.asarray(instances)
    preprocessed_inputs = self._preprocessor.preprocess(inputs)
    if kwargs.get('probabilities'):
      probabilities = self._model.predict_proba(preprocessed_inputs)
      return probabilities.tolist()
    else:
      outputs = self._model.predict(preprocessed_inputs)
      return [self._class_names[class_num] for class_num in outputs]

  @classmethod
  def from_path(cls, model_dir):
    model_path = os.path.join(model_dir, 'model.joblib')
    model = joblib.load(model_path)

    preprocessor_path = os.path.join(model_dir, 'preprocessor.pkl')
    with open(preprocessor_path, 'rb') as f:
      preprocessor = pickle.load(f)

    return cls(model, preprocessor)

the code I use to create my model in cloud is:

! gcloud beta ai-platform versions create {VERSION_NAME} \
  --model {MODEL_NAME} \
  --runtime-version 1.13 \
  --python-version 3.5 \
  --origin gs://{BUCKET_NAME}/custom_prediction_routine_tutorial/model/ \
  --package-uris gs://{BUCKET_NAME}/custom_prediction_routine_tutorial/my_custom_code-0.1.tar.gz \
  --prediction-class predictor.MyPredictor

But I end up with such an odd error:

ERROR: (gcloud.beta.ai-platform.versions.create) Bad model detected with error:  "Failed to load model: Unexpected error when loading the model: 'ascii' codec can't decode byte 0xf9 in position 2: ordinal not in range(128) (Error code: 0)"

The thing is that when I run the same command without the:

--prediction-class predictor.MyPredictor

it work fine.

Does someone know the reason of this ? I think model.joblib might have an encoding problem but when I load it myself there is nothing wrong


问:
Is there a way to specify a different session store with Tomcat?
Tomcat (version 5 here) stores session information in memory. When clustering this information is periodically broadcast to other servers in the cluster to keep things in sync. You can use a database store to make sessions persistant but this information is only written periodically as well and is only really used for failure-recovery rather than actually replacing the in-memory sessions.

If you don't want to use sticky sessions (our configuration doesn't allow it unfortunately) this raises the problem of the sessions getting out of sync.

In other languages, web frameworks tend to allow you to use a database as the primary session store. Whilst this introduces a potential scaling issue it does make session management very straightforward. I'm wondering if there's a way to get tomcat to use a database for sessions in this way (technically this would also remove the need for any clustering configuration in the tomcat server.xml).

答:
Another alternative would be the memcached-session-manager, a memcached based session failover and session replication solution for tomcat 6.x / 7.x. It supports both sticky sessions and non-sticky sessions.

I created this project to get the best of performance and reliability and to be able to scale out by just adding more tomcat and memcached nodes.

OwnerDisplayName: Andrew Ingram

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to see arguments when creating a new class?
When creating a new class or method I used to be able to see the parameters needed. But, now they don't come up anymore. How do I view parameters when creating a class?

Running the latest windows version.

```<code>public class Main {

    public static void main(String args[]) {
        Case theCase = new Case("Default", "Corsair", "500W");
    }
}

public class Case {

    private String model;
    private String manufacturer;
    private String powerSupply;

    public Case(String model, String manufacturer, String powerSupply,) {
       this.model = model;
       this.manufacturer = manufacturer;
       this.powerSupply = powerSupply;

    }

    public void pressPowerButton() {
        System.out.println("Power button pressed");
    }

    public String getModel() {
        return model;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public String getPowerSupply() {
        return powerSupply;
    }
}
</code>```

When making theCase I can't see what my parameters are and have to move to the "Case" class back and forth

答: You can explicitly call Parameter Info action which is usually mapped to Ctrl/(Cmd) - p.

Body:
When creating a new class or method I used to be able to see the parameters needed. But, now they don't come up anymore. How do I view parameters when creating a class?

Running the latest windows version.

public class Main {

    public static void main(String args[]) {
        Case theCase = new Case("Default", "Corsair", "500W");
    }
}

public class Case {

    private String model;
    private String manufacturer;
    private String powerSupply;

    public Case(String model, String manufacturer, String powerSupply,) {
       this.model = model;
       this.manufacturer = manufacturer;
       this.powerSupply = powerSupply;

    }

    public void pressPowerButton() {
        System.out.println("Power button pressed");
    }

    public String getModel() {
        return model;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public String getPowerSupply() {
        return powerSupply;
    }
}

When making theCase I can't see what my parameters are and have to move to the "Case" class back and forth


问:
EController login isn't working anymore in IBM Content Manager 8.4
I've got EController working like a charm in IBM CM 8.3. When I upgraded to 8.4 I saw that the idm.jar has been modified and that IDMConnection doesn't do a request forward any more but a redirect.

I've fixed that by putting params as a session attribute. But now when I login through EController and display my search results, I don't have the right permission, even when I pass the credentials of icmadmin.

The following url did work ik 8.3 :
"/IDMConnection?server=" + "name=" + strServerName + ",type=" + strServerType + "&userid=" + strUserID + "&password=" + strPassword + "&action=Login"

Do I need to send more params to it? I'm quite stuck here.

答:
I fixed it, the problem is that since 8.4 there is a browser issues with IE. So you need to provide the browser as a connection param. Like:

```<code>"/IDMConnection?server=" + "name=" + strServerName + ",type=" + strServerType + "&userid=" + strUserID + "&password=" + strPassword + "&browser=ie4&action=Login"
</code>```

Now it works.....

How did I figured it out?
Well, I re-routed the IDMLogon2.jsp to a custom filter, there I debugged/printed-out all the params and there it was :). It even has an extra param, platform=win, but that one is not necessary.

Body:
I fixed it, the problem is that since 8.4 there is a browser issues with IE. So you need to provide the browser as a connection param. Like:

"/IDMConnection?server=" + "name=" + strServerName + ",type=" + strServerType + "&userid=" + strUserID + "&password=" + strPassword + "&browser=ie4&action=Login"

Now it works.....

How did I figured it out?
Well, I re-routed the IDMLogon2.jsp to a custom filter, there I debugged/printed-out all the params and there it was :). It even has an extra param, platform=win, but that one is not necessary.


问:
Access rights for Azure DevOps Services pipeline
What are the best practices for accesses permission for programmers working in Azure DevOps? I would like the programmers to be able to use it, by for example having the possibility to create branches.

As far as I can understand by reading documents such as
https://learn.microsoft.com/en-us/azure/devops/organizations/security/set-git-tfvc-repository-permissions?view=azure-devops#git-repository

The only permission needed is a contributor? Is this correct or have I misunderstood the whole thing? The organization I’m working for have for example set the contributor to be a member of :
Build Administrators, Endpoint creators, Release Administrators

答:
You need to navigate to project settings and then to repositories. there you will find list of repositories and each repo can have certain rights assigned to it. some are inherited, some assigned. You can modify those to fit your likings.

this is the url: https://dev.azure.com/org_name/project_name/_settings/repositories

For more details, follow this link: https://learn.microsoft.com/en-us/azure/devops/organizations/security/set-git-tfvc-repository-permissions?view=azure-devops


问:
How to select both text from same class?
I'm using JQuery and I wanna show html from same divs. Example:

```

<pre class="lang-js prettyprint-override"><code>$('.content').keyup(function() {
  $('#result').html($('.content').html());
});
</code>```

In this code I take only first div's text, if I use $(this) instead of $('.content'), I take last div's text. So I can't solve this problem. Thanks

答:
<strong>$('.content')</strong> always return an array so you need to loop it </p>

```<code> $('.content').keyup(function() {
  var htmlcontent='';
  $(".content").each(function(){
    htmlcontent+=$(this).html();
  })
  $('#result').html(htmlcontent);
});
</code>```

Body:
I'm using JQuery and I wanna show html from same divs. Example:

$('.content').keyup(function() {
  $('#result').html($('.content').html());
});

In this code I take only first div's text, if I use $(this) instead of $('.content'), I take last div's text. So I can't solve this problem. Thanks

Body:
$('.content') always return an array so you need to loop it

 $('.content').keyup(function() {
  var htmlcontent='';
  $(".content").each(function(){
    htmlcontent+=$(this).html();
  })
  $('#result').html(htmlcontent);
});


问:
Vue Router return 404 when revisit to the url
I just enable Vue router history mode. And it work fine when I visit to vue routing via v-href or href. But, when I try to refresh that page or go directly from browser address bar, it just return 404. Is there any option to accept refresh/revisit to that url?

The following is my Vue router configuration

var router = new VueRouter({
  hashbang: false,
  history: true,
  mode: 'html5',
  linkActiveClass: "active",
  root:  '/user'
});
```

答:
If you don't really care about the hash in the url, you can just set the mode to hash in you router configuration file: mode: 'hash'
That works fine without the need to set up the server side.

```<code>const router = new VueRouter({
    routes: Routes,
    mode: 'hash'
});
</code>```

Hash mode comes by default in vue, so it should work even if you leave blank instead of mode: 'hash'.

Body:
If you don't really care about the hash in the url, you can just set the mode to hash in you router configuration file: mode: 'hash'
That works fine without the need to set up the server side.

const router = new VueRouter({
    routes: Routes,
    mode: 'hash'
});

Hash mode comes by default in vue, so it should work even if you leave blank instead of mode: 'hash'.


问:
shuffle card deck issues in language agnostic
Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.

Problem 1 :

Product of everything except current

Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]

For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.

IMPORTANT: Your algorithm must run in linear time.

Problem 2 : ( the topic was in one of Jeff posts )

Shuffle card deck evenly

Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).

Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()

What is the complexity of your algorithm (as a function of the number n of cards in the deck)?

Explain how you would test that the cards are evenly shuffled by your method (black box testing).

P.S. I had two hours to code the solutions

答: Tnilsson, I've also uset the Fisher-Yates shuffle :). I'm very interested dough, about the testing part :)</p>

OwnerDisplayName: Kociub

LastEditorDisplayName: John Nolan


问:
Looping through a request.querystring in VB.NET
I am trying to loop through a query string and pull out certain values as in:

```<code>?ProductID=1234&ProductID=4321&Quantity=1
</code>```

For each value next to ProductID I want to execute some logic.  But I am not sure how to get to the values.  Any ideas?

答:
When your query string has more than one value with the same key you can use the NameValueCollection.GetValues method which returns a string array:</p>

```<code>dim productID as string
for each productID  in Page.Request.QueryString.GetValues("ProductID")
  ' do something with productID
next productID
</code>```

OwnerDisplayName: Jim

Body:
I am trying to loop through a query string and pull out certain values as in:

?ProductID=1234&ProductID=4321&Quantity=1

For each value next to ProductID I want to execute some logic.  But I am not sure how to get to the values.  Any ideas?

Body:
When your query string has more than one value with the same key you can use the NameValueCollection.GetValues method which returns a string array:

dim productID as string
for each productID  in Page.Request.QueryString.GetValues("ProductID")
  ' do something with productID
next productID

OwnerDisplayName: Jason DeFontes


问:
Adding the last two elements of a list
In Mathematica, what is the cleanest way of taking a list

```<code>{r1, r2, r3, ..., rn, a, b}
</code>```

and returning

```<code>{r1, r2, r3, ..., rn, a + b}
</code>```

or more generally

```<code>{r1, r2, r3, ..., rn, f[a, b]}
</code>```

for some function f?

答:
Suppose 'list' is defined:

```<code>Remove[list];
list = {r1, r2, r2, r4, r5, a, b};
</code>```

Re-set 'list' to be {r1, r2, r3, r4, r5, a} with the [[-1]] replaced by the sum of the last two elements in 'list'.

```<code>list = ReplacePart[Drop[list, -1], -1 -> Plus @@ list[[-2 ;; -1]]]
</code>```

Thanks for asking this, btw. :)

Title: Adding the last two elements of a list

Body:
In Mathematica, what is the cleanest way of taking a list

{r1, r2, r3, ..., rn, a, b}

and returning

{r1, r2, r3, ..., rn, a + b}

or more generally

{r1, r2, r3, ..., rn, f[a, b]}

for some function f?

Body:
Suppose 'list' is defined:

Remove[list];
list = {r1, r2, r2, r4, r5, a, b};

Re-set 'list' to be {r1, r2, r3, r4, r5, a} with the [[-1]] replaced by the sum of the last two elements in 'list'.

list = ReplacePart[Drop[list, -1], -1 -> Plus @@ list[[-2 ;; -1]]]

Thanks for asking this, btw. :)


问:
How to use Array.protoype.map() on array of objects to filter out some specific keys based on it's values?
I have the following array of objects, in which some specific keys have a value which is either a string or an array. I want to get the keys with string values as it is and remove "NA" from keys with array values.

I am trying to achieve the same by doing .map method on the array, check the type of the value of each key in the data object, if an array then use .filter to remove the "NA" values.

```<code>var dataArr = [
    {
     a: 'foo',
     b: [1, 2, "NA", "NA", 3],
     c: ["NA", 6]
    },
    {
     a: 'bar',
     b: ["NA", "NA", "NA"],
     c: []
    }
];
dataArr.map(dataObj => {
    for (let key in dataObj) {
        if (key !== 'a')
            dataObj[key] = dataObj[key].filter(val => { if(val != "NA") return val})
    }
    return dataObj;
});
</code>```

The above block of code works as expected but I want a better and future-proof solution. Moreover, this looks bad too.

答:
I guess this will be a better code refactor,pls provide with the desired output also:</p>

```<code>dataArr.forEach(object=>{
  for (let value in object){
   let isArr = Object.prototype.toString.call(data) == '[object Array]';
   isArr? object[value] = object[value].filter(val => {return val != "NA"}):null}
 })
</code>```

Body:
I have the following array of objects, in which some specific keys have a value which is either a string or an array. I want to get the keys with string values as it is and remove "NA" from keys with array values.

I am trying to achieve the same by doing .map method on the array, check the type of the value of each key in the data object, if an array then use .filter to remove the "NA" values.

var dataArr = [
    {
     a: 'foo',
     b: [1, 2, "NA", "NA", 3],
     c: ["NA", 6]
    },
    {
     a: 'bar',
     b: ["NA", "NA", "NA"],
     c: []
    }
];
dataArr.map(dataObj => {
    for (let key in dataObj) {
        if (key !== 'a')
            dataObj[key] = dataObj[key].filter(val => { if(val != "NA") return val})
    }
    return dataObj;
});

The above block of code works as expected but I want a better and future-proof solution. Moreover, this looks bad too.

Body:
I guess this will be a better code refactor,pls provide with the desired output also:

dataArr.forEach(object=>{
  for (let value in object){
   let isArr = Object.prototype.toString.call(data) == '[object Array]';
   isArr? object[value] = object[value].filter(val => {return val != "NA"}):null}
 })


问:
Vertical alignment on editable UITextView
I want to set the vertical alignment on my UITextView. The text view is editable and scroll is disabled:

let textView = UITextView(frame: frame)
textView.backgroundColor = .clear
textView.attributedText = myAttributedString
textView.isUserInteractionEnabled = true
textView.isEditable = true
textView.allowsEditingTextAttributes = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero
self.addSubview(textView)
```

<p>So, I would like to do something like :</p>

<pre class="lang-swift prettyprint-override"><code>textView.verticalAlignment = .center
</code>```

I already tried subclassing the text view and adding an attribute like this:

class MyTextView: UITextView {
    public var verticalAlignment: UIControl.ContentVerticalAlignment = .center {
        didSet {
            let topCorrection: CGFloat
            switch verticalAlignment {
            case .center:
                topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
            case .bottom:
                topCorrection = (bounds.size.height - contentSize.height * zoomScale)
            case .top, .fill:
                topCorrection = 0
            @unknown default:
                topCorrection = 0
            }
            contentInset.top = max(0, topCorrection)
        }
    }
}
```

But it seems not to work with isScrollEnabled set to false.

Every other solution I found on the internet didn't work either and I'm a bit hopeless… Can you help me?

Thanks

答:
Create a custom textView

```<code>class CustomTextView: UITextView {
    override var canBecomeFirstResponder: Bool {
        return false
    }

    override var selectedTextRange: UITextRange? {
        get {
            return nil
        } set {

        }
    }

    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if let tapGestureRecognizer = gestureRecognizer as? UITapGestureRecognizer,
            tapGestureRecognizer.numberOfTapsRequired == 1 {
            return super.gestureRecognizerShouldBegin(gestureRecognizer)
        }

        if let longPressGestureRecognizer = gestureRecognizer as? UILongPressGestureRecognizer,

            longPressGestureRecognizer.minimumPressDuration < 0.325 {
            return super.gestureRecognizerShouldBegin(gestureRecognizer)
        }
        gestureRecognizer.isEnabled = false
        return false
    }
}
</code>```

Use this textview as a baseclass for the textview

Body:
I want to set the vertical alignment on my UITextView. The text view is editable and scroll is disabled:

let textView = UITextView(frame: frame)
textView.backgroundColor = .clear
textView.attributedText = myAttributedString
textView.isUserInteractionEnabled = true
textView.isEditable = true
textView.allowsEditingTextAttributes = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero
self.addSubview(textView)

So, I would like to do something like :

textView.verticalAlignment = .center

I already tried subclassing the text view and adding an attribute like this:

class MyTextView: UITextView {
    public var verticalAlignment: UIControl.ContentVerticalAlignment = .center {
        didSet {
            let topCorrection: CGFloat
            switch verticalAlignment {
            case .center:
                topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
            case .bottom:
                topCorrection = (bounds.size.height - contentSize.height * zoomScale)
            case .top, .fill:
                topCorrection = 0
            @unknown default:
                topCorrection = 0
            }
            contentInset.top = max(0, topCorrection)
        }
    }
}

But it seems not to work with isScrollEnabled set to false.

Every other solution I found on the internet didn't work either and I'm a bit hopeless… Can you help me?

Thanks

Body:
Create a custom textView

class CustomTextView: UITextView {
    override var canBecomeFirstResponder: Bool {
        return false
    }

    override var selectedTextRange: UITextRange? {
        get {
            return nil
        } set {

        }
    }

    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if let tapGestureRecognizer = gestureRecognizer as? UITapGestureRecognizer,
            tapGestureRecognizer.numberOfTapsRequired == 1 {
            return super.gestureRecognizerShouldBegin(gestureRecognizer)
        }

        if let longPressGestureRecognizer = gestureRecognizer as? UILongPressGestureRecognizer,

            longPressGestureRecognizer.minimumPressDuration < 0.325 {
            return super.gestureRecognizerShouldBegin(gestureRecognizer)
        }
        gestureRecognizer.isEnabled = false
        return false
    }
}

Use this textview as a baseclass for the textview


问:
Text Overlay Image with Darkened Opacity React Native
I am attempting to overlay a title over an image - with the image darkened with a lower opacity. However, the opacity effect is changing the overlaying text as well - making it dim. Any fix to this? Here is what is looks like:

And here is my code for the custom component (article preview - which the above image is a row of article preview components):

```<code>//component for article preview touchable image
/* will require the following
- rss feed and api
- user's keyword interests from parse In home.js
- parse db needs to be augmented to include what they heart
- parse db needs to be augmented to include what they press on (like google news)
*/
var React = require('react-native');
var {
  View,
  StyleSheet,
  Text,
  Image,
  TouchableHighlight,
} = React;

//dimensions
var Dimensions = require('Dimensions');
var window = Dimensions.get('window');
var ImageButton = require('../../common/imageButton');
var KeywordBox = require('../../authentication/onboarding/keyword-box');

//additional libraries

module.exports = React.createClass({
  //onPress function that triggers when button pressed
  //this.props.text is property that can be dynamically filled within button
  /* following props:
    - source={this.props.source}
    - onPress={this.props.onPress}
    - {this.props.text}
    - {this.props.heartText}
    - key={this.props.key}
    - text={this.props.category}
    - this.props.selected
  */
  render: function() {
    return (
      <TouchableHighlight
        underlayColor={'transparent'}
        onPress={this.props.onPress} >
          <Image
            source={this.props.source}
            style={[styles.articlePreview, this.border('red')]}>
                  <View style={[styles.container, this.border('organge')]}>
                      <View style={[styles.header, this.border('blue')]}>
                          <Text style={[styles.previewText]}>{this.props.text}</Text>
                      </View>
                      <View style={[styles.footer, this.border('white')]}>
                        <View style={[styles.heartRow, this.border('black')]}>
                          <ImageButton
                              style={[styles.heartBtn, , this.border('red')]}
                              resizeMode={'contain'}
                              onPress={this.onHeartPress}
                              source={require('../../img/heart_btn.png')} />
                          <Text style={[styles.heartText]}>{this.props.heartText + ' favorites'}</Text>
                        </View>
                          <KeywordBox
                              style={[styles.category, this.border('blue')]}
                              key={this.props.key}
                              text={this.props.category}
                              onPress={this.props.categoryPress}
                              selected={this.props.selected} />
                      </View>
                  </View>
          </Image>
      </TouchableHighlight>
    );
  },
  onHeartPress: function() {
    //will move this function to a general module
  },
  border: function(color) {
      return {
        //borderColor: color,
        //borderWidth: 4,
      }
   },
});

var styles = StyleSheet.create({
  heartText: {
    color: 'white',
    fontSize: 12,
    fontWeight: 'bold',
    alignSelf: 'center',
    marginLeft: 5,
    fontFamily: 'SFCompactText-Medium'
  },
  heartRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignSelf: 'center',
    justifyContent: 'center',
  },
  heartBtn: {
    height: (92/97)*(window.width/13),
    width: window.width/13,
    alignSelf:'center',
  },
  category: {
    fontFamily: 'Bebas Neue',
    fontSize: 10,
    fontWeight: 'bold'
  },
  header: {
    flex: 3,
    alignItems: 'center',
    justifyContent: 'space-around',
    marginTop: window.height/30,
  },
  footer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    margin: window.height/50,
  },
  container: {
    flex: 1,
    backgroundColor: 'black',
    opacity: 0.6,
  },
  articlePreview: {
    flex: 1,
    height: window.height/3.2,
    width: window.width,
    flexDirection: 'column'
  },
  previewText: {
    fontFamily: 'Bebas Neue',
    fontSize: 23,
    color: 'white',
    alignSelf: 'center',
    textAlign: 'center',
    margin: 5,
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  },

});
</code>```

答:
Instead of applying the opacity to entire ImageBackground element, implement it on the image itself  Eg.</p>

```<code><ImageBackground style={styles.imageContainer}
                 imageStyle={{ opacity: 0.5 }}
                 source={require('../assets/images/background.png')}>
                <View style={styles.welcomeContainer}>
                    <Image source={require('../assets/images/zeptagram-logo.png')} style={styles.welcomeImage} />
                </View>
            </ImageBackground>
</code>```

Body:
I am attempting to overlay a title over an image - with the image darkened with a lower opacity. However, the opacity effect is changing the overlaying text as well - making it dim. Any fix to this? Here is what is looks like:

And here is my code for the custom component (article preview - which the above image is a row of article preview components):

//component for article preview touchable image
/* will require the following
- rss feed and api
- user's keyword interests from parse In home.js
- parse db needs to be augmented to include what they heart
- parse db needs to be augmented to include what they press on (like google news)
*/
var React = require('react-native');
var {
  View,
  StyleSheet,
  Text,
  Image,
  TouchableHighlight,
} = React;

//dimensions
var Dimensions = require('Dimensions');
var window = Dimensions.get('window');
var ImageButton = require('../../common/imageButton');
var KeywordBox = require('../../authentication/onboarding/keyword-box');

//additional libraries

module.exports = React.createClass({
  //onPress function that triggers when button pressed
  //this.props.text is property that can be dynamically filled within button
  /* following props:
    - source={this.props.source}
    - onPress={this.props.onPress}
    - {this.props.text}
    - {this.props.heartText}
    - key={this.props.key}
    - text={this.props.category}
    - this.props.selected
  */
  render: function() {
    return (
      <TouchableHighlight
        underlayColor={'transparent'}
        onPress={this.props.onPress} >
          <Image
            source={this.props.source}
            style={[styles.articlePreview, this.border('red')]}>
                  <View style={[styles.container, this.border('organge')]}>
                      <View style={[styles.header, this.border('blue')]}>
                          <Text style={[styles.previewText]}>{this.props.text}</Text>
                      </View>
                      <View style={[styles.footer, this.border('white')]}>
                        <View style={[styles.heartRow, this.border('black')]}>
                          <ImageButton
                              style={[styles.heartBtn, , this.border('red')]}
                              resizeMode={'contain'}
                              onPress={this.onHeartPress}
                              source={require('../../img/heart_btn.png')} />
                          <Text style={[styles.heartText]}>{this.props.heartText + ' favorites'}</Text>
                        </View>
                          <KeywordBox
                              style={[styles.category, this.border('blue')]}
                              key={this.props.key}
                              text={this.props.category}
                              onPress={this.props.categoryPress}
                              selected={this.props.selected} />
                      </View>
                  </View>
          </Image>
      </TouchableHighlight>
    );
  },
  onHeartPress: function() {
    //will move this function to a general module
  },
  border: function(color) {
      return {
        //borderColor: color,
        //borderWidth: 4,
      }
   },
});

var styles = StyleSheet.create({
  heartText: {
    color: 'white',
    fontSize: 12,
    fontWeight: 'bold',
    alignSelf: 'center',
    marginLeft: 5,
    fontFamily: 'SFCompactText-Medium'
  },
  heartRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignSelf: 'center',
    justifyContent: 'center',
  },
  heartBtn: {
    height: (92/97)*(window.width/13),
    width: window.width/13,
    alignSelf:'center',
  },
  category: {
    fontFamily: 'Bebas Neue',
    fontSize: 10,
    fontWeight: 'bold'
  },
  header: {
    flex: 3,
    alignItems: 'center',
    justifyContent: 'space-around',
    marginTop: window.height/30,
  },
  footer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    margin: window.height/50,
  },
  container: {
    flex: 1,
    backgroundColor: 'black',
    opacity: 0.6,
  },
  articlePreview: {
    flex: 1,
    height: window.height/3.2,
    width: window.width,
    flexDirection: 'column'
  },
  previewText: {
    fontFamily: 'Bebas Neue',
    fontSize: 23,
    color: 'white',
    alignSelf: 'center',
    textAlign: 'center',
    margin: 5,
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  },

});

Body:
Instead of applying the opacity to entire ImageBackground element, implement it on the image itself  Eg.

<ImageBackground style={styles.imageContainer}
                 imageStyle={{ opacity: 0.5 }}
                 source={require('../assets/images/background.png')}>
                <View style={styles.welcomeContainer}>
                    <Image source={require('../assets/images/zeptagram-logo.png')} style={styles.welcomeImage} />
                </View>
            </ImageBackground>


问:
In Spring + Mybatis, how can I get dao method's parameter names in runtime?
In code, when I only know the beanId that point to dao object, how can I get method (in dao object) parameter names in runtime?

I'm using Java 7, Spring 4.1.6.RELEASE, Mybatis 3.2.8. And I am completely clueless

String daoBeanId = "IUserDao";
String methodName = "insertUser";

ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();

Object daoInstance = applicationContext.getBean(daoBeanId);
Class daoClass = daoInstance.getClass();

Method method = ReflectUtil.getMethod(daoClass,methodName);

//some code to get this method's parameter names
```

this is different from “Can I obtain method parameter name using Java reflection? ”，because in mybatis，dao object is proxy object，proxy object seems don't have the parameter names information，so it makes this question more complicated and difficult

答:
You can try this for Java 8

```<code>Parameter[] parameters = method.getParameters();
for (Parameter parameter : parameters) {
    System.out.println(parameter.getName());
}
</code>```

This is for earlier Java versions

```<code>for (int i = 0; i < method.getArgumentTypes().length; i++) {
    LocalVariable variable =
    method.getLocalVariableTable().getLocalVariable(i);
    System.out.println(variable.getName());
}
</code>```

Body:
In code, when I only know the beanId that point to dao object, how can I get method (in dao object) parameter names in runtime?

I'm using Java 7, Spring 4.1.6.RELEASE, Mybatis 3.2.8. And I am completely clueless

String daoBeanId = "IUserDao";
String methodName = "insertUser";

ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();

Object daoInstance = applicationContext.getBean(daoBeanId);
Class daoClass = daoInstance.getClass();

Method method = ReflectUtil.getMethod(daoClass,methodName);

//some code to get this method's parameter names

this is different from “Can I obtain method parameter name using Java reflection? ”，because in mybatis，dao object is proxy object，proxy object seems don't have the parameter names information，so it makes this question more complicated and difficult

Body:
You can try this for Java 8

Parameter[] parameters = method.getParameters();
for (Parameter parameter : parameters) {
    System.out.println(parameter.getName());
}

This is for earlier Java versions

for (int i = 0; i < method.getArgumentTypes().length; i++) {
    LocalVariable variable =
    method.getLocalVariableTable().getLocalVariable(i);
    System.out.println(variable.getName());
}


问:
how to filter out boolean fields in spark dataframe?
I have three columns in my data frame. In this second and third are boolean fields. I want to filter out the values which are true. i have tried this one nn.filter(col("col3")===true).show but it says invalid column name "true". what worng with my code? Does any help please?

my codes:

```<code>scala> nn.printSchema
root
 |-- ID: integer (nullable = true)
 |-- col2: boolean (nullable = true)
 |-- col3: boolean (nullable = true)

scala> nn.show
+---+-----+-----+
| ID| col2| col3|
+---+-----+-----+
|  4| true|false|
|  5|false|false|
|  6|false|false|
|  7|false|false|
| 12|false|false|
| 13|false|false|
| 14|false|false|
| 15|false| true|
| 16|false|false|
| 17|false|false|
| 18|false|false|
| 22|false|false|
| 36|false|false|
| 37|false|false|
| 38|false|false|
| 39|false|false|
| 40|false|false|
| 41| true|false|
| 42|false|false|
+---+-----+-----+

scala> nn.filter(col("col3")===true).show
[Stage 14:>                                                         (0 + 1) / 1]19/05/26 22:44:16 ERROR executor.Executor: Exception in task 0.0 in stage 14.0 (TID 14)
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'true'.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
        at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:297)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:301)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:109)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
</code>```

答:
```<code>import spark.implicits._

val someDf = Seq((1, true, false), (2, true, true)).toDF("col1", "col2", "col3")

someDf.show()

import org.apache.spark.sql.functions._

someDf.filter(col("col3")===true).show()

Original DataFrame :
+----+----+-----+
|col1|col2| col3|
+----+----+-----+
|   1|true|false|
|   2|true| true|
+----+----+-----+

Filtered Dataframe :
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   2|true|true|
+----+----+----+
</code>```

Body:
I have three columns in my data frame. In this second and third are boolean fields. I want to filter out the values which are true. i have tried this one nn.filter(col("col3")===true).show but it says invalid column name "true". what worng with my code? Does any help please?

my codes:

scala> nn.printSchema
root
 |-- ID: integer (nullable = true)
 |-- col2: boolean (nullable = true)
 |-- col3: boolean (nullable = true)

scala> nn.show
+---+-----+-----+
| ID| col2| col3|
+---+-----+-----+
|  4| true|false|
|  5|false|false|
|  6|false|false|
|  7|false|false|
| 12|false|false|
| 13|false|false|
| 14|false|false|
| 15|false| true|
| 16|false|false|
| 17|false|false|
| 18|false|false|
| 22|false|false|
| 36|false|false|
| 37|false|false|
| 38|false|false|
| 39|false|false|
| 40|false|false|
| 41| true|false|
| 42|false|false|
+---+-----+-----+

scala> nn.filter(col("col3")===true).show
[Stage 14:>                                                         (0 + 1) / 1]19/05/26 22:44:16 ERROR executor.Executor: Exception in task 0.0 in stage 14.0 (TID 14)
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'true'.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
        at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:297)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:301)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:109)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)


问:
Mailchimp authentication showing Access-Control-Allow-Origin
When integrating with mailchimp, I do authentication after I get access_token then I also send a get request to get metadata and faces a problem.

After synching user name and password I get access_token and I got error on this code:

```<code>var AccessToken = '<?php //echo $_GET['access_token']; ?>'
jQuery.ajax( {
    url: "https://login.mailchimp.com/oauth2/metadata",
    type: 'GET',
    beforeSend : function( xhr ) {
        xhr.setRequestHeader( 'Authorization', 'OAuth ' +
        AccessToken );
    },
    success: function( response ) {
        console.log(response);
    },
    error : function(error) {
        console.log(error);
    }
} );
</code>```

I also tried from curl as:

```<code>public function list()
{
  $url = 'https://login.mailchimp.com/oauth2/token';
  $data = [
    'grant_type' => 'authorization_code',
    'client_id' => 345555555555555555555555,
    'client_secret' => '4b0xxxxxxxxxxxxxxxxxxxxx5406a7d',
    'redirect_uri' => 'http://127.0.0.1:8000/success',
    'code' => $_GET['code']
    ];
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $response = curl_exec ($ch);
 $err = curl_error($ch);  //if you need
 curl_close ($ch);
 return $response;
     }
</code>```

```<code>Access to XMLHttpRequest at 'https://login.mailchimp.com/oauth2/metadata' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Cross-Origin Read Blocking (CORB) blocked cross-origin response https://login.mailchimp.com/oauth2/metadata with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ list:74
</code>```

答:
The error in your request states that CORB,

Cross-origin read blocking, better known as CORB, is an algorithm by
  which dubious cross-origin resource fetches are identified and blocked
  before they reach a web page. CORB reduces the risk of leaking
  sensitive data by keeping it further from cross-origin web pages. In
  most browsers, it keeps such data out of untrusted script execution
  contexts. In browsers with Site Isolation, it can keep such data out
  of untrusted renderer processes entirely, helping even against side
  channel attacks.

Since, you're making request from a localhost, it is being considered as dubious origin, as a result its being blocked.

Body:
When integrating with mailchimp, I do authentication after I get access_token then I also send a get request to get metadata and faces a problem.

After synching user name and password I get access_token and I got error on this code:

var AccessToken = '<?php //echo $_GET['access_token']; ?>'
jQuery.ajax( {
    url: "https://login.mailchimp.com/oauth2/metadata",
    type: 'GET',
    beforeSend : function( xhr ) {
        xhr.setRequestHeader( 'Authorization', 'OAuth ' +
        AccessToken );
    },
    success: function( response ) {
        console.log(response);
    },
    error : function(error) {
        console.log(error);
    }
} );

I also tried from curl as:

public function list()
{
  $url = 'https://login.mailchimp.com/oauth2/token';
  $data = [
    'grant_type' => 'authorization_code',
    'client_id' => 345555555555555555555555,
    'client_secret' => '4b0xxxxxxxxxxxxxxxxxxxxx5406a7d',
    'redirect_uri' => 'http://127.0.0.1:8000/success',
    'code' => $_GET['code']
    ];
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $response = curl_exec ($ch);
 $err = curl_error($ch);  //if you need
 curl_close ($ch);
 return $response;
     }

Access to XMLHttpRequest at 'https://login.mailchimp.com/oauth2/metadata' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Cross-Origin Read Blocking (CORB) blocked cross-origin response https://login.mailchimp.com/oauth2/metadata with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ list:74


问:
How can you stop a program from listening as soon as you stop talking?
I am making a simple program to listen to my michrophone and using google's api convert it to text.
It's going fine but my problem is that when i am stop talking, the program keeps listening and just after few seconds after i stopped talking it stops.

I know its probably a problem with my noise in the background although I have Blue yeti microphone so it should'nt rally happens but still I tried to adjust the noise and yet it showed the same result.

```<code>import speech_recognition as sr

# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone(device_index = 1) as source:
    print("Say something!")
    #audio = r.adjust_for_ambient_noise(source) - Tried also that
    audio = r.listen(source)
    print('Stopped listening!')
try:
    print("Google Speech Recognition thinks you said " + r.recognize_google(audio, language="he-HE"))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))
</code>```

As expected the program keeps listening even when i'm not talking for few seconds which makes it really slow and bad..
Thanks for the help!

答:
You can try adjusting the pause_threshold attribute of the Recognizerclass.
By default, it is set to 0.8
Found the info by looking at the Recognizer source code here: https://github.com/Uberi/speech_recognition/blob/350397d2fb5db318c877f29ee3dc6e6cbf4a393d/speech_recognition/init.py#L508

Body:
I am making a simple program to listen to my michrophone and using google's api convert it to text.
It's going fine but my problem is that when i am stop talking, the program keeps listening and just after few seconds after i stopped talking it stops.

I know its probably a problem with my noise in the background although I have Blue yeti microphone so it should'nt rally happens but still I tried to adjust the noise and yet it showed the same result.

import speech_recognition as sr

# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone(device_index = 1) as source:
    print("Say something!")
    #audio = r.adjust_for_ambient_noise(source) - Tried also that
    audio = r.listen(source)
    print('Stopped listening!')
try:
    print("Google Speech Recognition thinks you said " + r.recognize_google(audio, language="he-HE"))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))

As expected the program keeps listening even when i'm not talking for few seconds which makes it really slow and bad..
Thanks for the help!


问:
How to install npm -g on offline server
I need to install a "global" npm applications on an offline server.

It is easy to install a normal application:

```<code>npm install
</code>```

and then pack up the resulting files. Either manually or using npm pack.

However, how can I install global application (that has a install script of some sort) such as forever without Internet?

```<code>npm install -g forever
</code>```

答:
On your local machine or any machine that has internet connection, do

```<code>npm install npm-bundle -g
npm install forever -g
</code>```

Now, go to cd /usr/local/lib/node_modules/forever and do

```<code>npm-bundle
</code>```

It will create a .tgz file. Now scp/ftp that .tgz file to the offline server and do

```<code>npm install forever -g
</code>```

Reference: This blog

Title: How to install npm -g on offline server

Body:
I need to install a "global" npm applications on an offline server.

It is easy to install a normal application:

npm install

and then pack up the resulting files. Either manually or using npm pack.

However, how can I install global application (that has a install script of some sort) such as forever without Internet?

npm install -g forever

Body:
On your local machine or any machine that has internet connection, do

npm install npm-bundle -g
npm install forever -g

Now, go to cd /usr/local/lib/node_modules/forever and do

npm-bundle

It will create a .tgz file. Now scp/ftp that .tgz file to the offline server and do

npm install forever -g

Reference: This blog


问:
How to fix the "multi-character literals are not allowed" error in antlr4 lexer rule?
The rule I am trying to write is:

```<code>Character : '\u0000'..'\u10FFF';
</code>```

But when trying to run antlr tool against the lexer file where it is defined I get the following error:

```<code>multi-character literals are not allowed in lexer sets: '\u10FFF'
</code>```

How to resolve this problem?

答:
Try wrapping the multi-char literal with { and }, and use the v4 style character set [...]:

```<code>Character : [\u0000-\u{10FFF}];
</code>```

From https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md#lexer-rule-elements:

[...] Match one of the characters specified in the character set. Interpret x-y as the set of characters between range x and y, inclusively. The following escaped characters are interpreted as single special characters: \n, \r, \b, \t, \f, \uXXXX, and \u{XXXXXX}. To get ], \, or - you must escape them with \.

Body:
The rule I am trying to write is:

Character : '\u0000'..'\u10FFF';

But when trying to run antlr tool against the lexer file where it is defined I get the following error:

multi-character literals are not allowed in lexer sets: '\u10FFF'

How to resolve this problem?

Body:
Try wrapping the multi-char literal with { and }, and use the v4 style character set [...]:

Character : [\u0000-\u{10FFF}];

From https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md#lexer-rule-elements:

[...] Match one of the characters specified in the character set. Interpret x-y as the set of characters between range x and y, inclusively. The following escaped characters are interpreted as single special characters: \n, \r, \b, \t, \f, \uXXXX, and \u{XXXXXX}. To get ], \, or - you must escape them with \.


问:
CN field is missing in SSL certificate from subject
I have SSL certificate, and I want to know the domain name associated with the certificate, for that I am using openssl to get the text of the .crt file.

The sample output is as follows:

```<code>Certificate:
Data:
    Version: 1 (0x0)
    Serial Number: 87778 (22)
Signature Algorithm: sha1WithRSAEncryption
    Issuer: C=IN, ST=Maharastra, L=Mumbai, O=Tests Pvt Ltd, OU=test/emailAddress=all@test.com
    Validity
        Not Before: Jan  2 02:09:10 2014 GMT
        Not After : Dec 31 02:09:10 2023 GMT
    Subject: C=IN, ST=Maharastra, L=Mumbai, O=Tests Pvt Ltd, OU=test/emailAddress=all@test.com
    Subject Public Key Info:
        Public Key Algorithm: rsaEncryption
</code>```

As we can see there is not CN field in the above certificate, let me know if the certificate is wrong, or we can expect certificate files without CN.

答:
With HTTPS a server certificate is expected to contain the name of the server and this name should match the expected name, otherwise the TLS handshake will fail. The name is specified today using the Subject Alternative Names (SAN) extension and before that was given using the CN of the subject. But the CN is considered obsolete for years and browsers like Chrome will not consider it anymore, i.e. make the SAN mandatory.

The certificate in your case contains neither CN nor SAN and thus will not be usable for HTTPS. There are other use cases of SSL/TLS apart from HTTPS though where this certificate might be acceptable. But it is unclear what specific use case you have.

Body:
I have SSL certificate, and I want to know the domain name associated with the certificate, for that I am using openssl to get the text of the .crt file.

The sample output is as follows:

Certificate:
Data:
    Version: 1 (0x0)
    Serial Number: 87778 (22)
Signature Algorithm: sha1WithRSAEncryption
    Issuer: C=IN, ST=Maharastra, L=Mumbai, O=Tests Pvt Ltd, OU=test/emailAddress=all@test.com
    Validity
        Not Before: Jan  2 02:09:10 2014 GMT
        Not After : Dec 31 02:09:10 2023 GMT
    Subject: C=IN, ST=Maharastra, L=Mumbai, O=Tests Pvt Ltd, OU=test/emailAddress=all@test.com
    Subject Public Key Info:
        Public Key Algorithm: rsaEncryption

As we can see there is not CN field in the above certificate, let me know if the certificate is wrong, or we can expect certificate files without CN.


问:
How can I "push" a UIViewController from FlutterViewController
I want to "push" a new native view (Activity as in Android & UIViewController as in iOS) upon our Flutter view, and after that new native view is completed/finished, make screen come back to our Flutter view.

I can do this in Android.
But I'm very new to iOS, when I try to do this in ios/Runner/AppDelegate.m:

```<code>  SwiftViewController *swiftViewController = [controller.storyboard instantiateViewControllerWithIdentifier:@"SwiftViewController"];
  [(FlutterViewController *)self.window.rootViewController pushViewController:swiftViewController animated:YES];
</code>```

It gives error:

No visible @interface for "FlutterViewController" declared the selector 'pushViewController:animated'

So how to do it in iOS? Thanks

答:
Writing custom platform-specific code

Widget with a button. Tap on button should push rely message to push a view controller to the iOS app.

```<code>class BodyWidget extends StatelessWidget {

  static const platform = const MethodChannel('samples.flutter.dev/navigation_channel');

  Future<void> _pushOnNative() async {
    try {
      Map parameters = Map();
      parameters["title"] = "Contact Details";
      parameters["name"] = "Bang Operator";
      parameters["so_profile_exists"] = true;
      await platform.invokeMethod('push',[parameters]);
    } on PlatformException catch (e) {
      print("Failed to communicate level: '${e.message}'.");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: FlatButton(
          textColor: Colors.white,
          color: Colors.red,
          onPressed: _pushOnNative,
          child: Text('Push Me'),
        )
    );
  }
}
</code>```

On iOS app side,
We need to observe the channel samples.flutter.dev/navigation_channel for method 'push'.
We can also pass arguments from flutter side, in this example we pass a Map(Dart) that is received as NSDictionary(Obj-C)

```<code>- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];

  FlutterViewController *controller = (FlutterViewController*)self.window.rootViewController;
  UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];

  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  self.window.rootViewController = navigationController;
  [navigationController setNavigationBarHidden:YES animated:YES];
  [self.window makeKeyAndVisible];

  [self setupNavigationChannelCallbacksOnMessenger:controller
                           forNavigationController:navigationController];

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)setupNavigationChannelCallbacksOnMessenger:(id<FlutterBinaryMessenger>)messenger
                           forNavigationController:(UINavigationController *)navigationController {
  FlutterMethodChannel* pushChannel = [FlutterMethodChannel
                                       methodChannelWithName:@"samples.flutter.dev/navigation_channel"
                                       binaryMessenger:messenger];

  [pushChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
    if ([call.method isEqualToString:@"push"] && [self getDictionaryFromArguments:call.arguments]) {
      NSDictionary *parameters = [self getDictionaryFromArguments:call.arguments];
      [self pushContactScreenWithInfo:parameters onNaivgationController:navigationController];
      result(@(true));
    } else {
      result(FlutterMethodNotImplemented);
    }
  }];
}

- (NSDictionary *)getDictionaryFromArguments:(id)arguments {
  if (![arguments isKindOfClass:[NSArray class]]) {
    return nil;
  }
  NSArray *argumentsArray = (NSArray *)arguments;
  if (argumentsArray.firstObject == nil || ![argumentsArray.firstObject isKindOfClass:[NSDictionary class]]) {
    return nil;
  }
  return (NSDictionary *)argumentsArray.firstObject;
}

- (void)pushContactScreenWithInfo:(NSDictionary *)info
          onNaivgationController:(UINavigationController *)navigationContorller {
  UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  ContactViewController *controller = [storyboard instantiateViewControllerWithIdentifier:@"ContactViewController"];
  [navigationContorller pushViewController:controller animated:YES];
  [controller view];
  [controller configureWithInfo:info];
}
</code>```

Body:
I want to "push" a new native view (Activity as in Android & UIViewController as in iOS) upon our Flutter view, and after that new native view is completed/finished, make screen come back to our Flutter view.

I can do this in Android.
But I'm very new to iOS, when I try to do this in ios/Runner/AppDelegate.m:

  SwiftViewController *swiftViewController = [controller.storyboard instantiateViewControllerWithIdentifier:@"SwiftViewController"];
  [(FlutterViewController *)self.window.rootViewController pushViewController:swiftViewController animated:YES];

It gives error:

No visible @interface for "FlutterViewController" declared the selector 'pushViewController:animated'

So how to do it in iOS? Thanks

Body:
Writing custom platform-specific code

Widget with a button. Tap on button should push rely message to push a view controller to the iOS app.

class BodyWidget extends StatelessWidget {

  static const platform = const MethodChannel('samples.flutter.dev/navigation_channel');

  Future<void> _pushOnNative() async {
    try {
      Map parameters = Map();
      parameters["title"] = "Contact Details";
      parameters["name"] = "Bang Operator";
      parameters["so_profile_exists"] = true;
      await platform.invokeMethod('push',[parameters]);
    } on PlatformException catch (e) {
      print("Failed to communicate level: '${e.message}'.");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: FlatButton(
          textColor: Colors.white,
          color: Colors.red,
          onPressed: _pushOnNative,
          child: Text('Push Me'),
        )
    );
  }
}

On iOS app side,
We need to observe the channel samples.flutter.dev/navigation_channel for method 'push'.
We can also pass arguments from flutter side, in this example we pass a Map(Dart) that is received as NSDictionary(Obj-C)

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];

  FlutterViewController *controller = (FlutterViewController*)self.window.rootViewController;
  UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];

  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  self.window.rootViewController = navigationController;
  [navigationController setNavigationBarHidden:YES animated:YES];
  [self.window makeKeyAndVisible];

  [self setupNavigationChannelCallbacksOnMessenger:controller
                           forNavigationController:navigationController];

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)setupNavigationChannelCallbacksOnMessenger:(id<FlutterBinaryMessenger>)messenger
                           forNavigationController:(UINavigationController *)navigationController {
  FlutterMethodChannel* pushChannel = [FlutterMethodChannel
                                       methodChannelWithName:@"samples.flutter.dev/navigation_channel"
                                       binaryMessenger:messenger];

  [pushChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
    if ([call.method isEqualToString:@"push"] && [self getDictionaryFromArguments:call.arguments]) {
      NSDictionary *parameters = [self getDictionaryFromArguments:call.arguments];
      [self pushContactScreenWithInfo:parameters onNaivgationController:navigationController];
      result(@(true));
    } else {
      result(FlutterMethodNotImplemented);
    }
  }];
}

- (NSDictionary *)getDictionaryFromArguments:(id)arguments {
  if (![arguments isKindOfClass:[NSArray class]]) {
    return nil;
  }
  NSArray *argumentsArray = (NSArray *)arguments;
  if (argumentsArray.firstObject == nil || ![argumentsArray.firstObject isKindOfClass:[NSDictionary class]]) {
    return nil;
  }
  return (NSDictionary *)argumentsArray.firstObject;
}

- (void)pushContactScreenWithInfo:(NSDictionary *)info
          onNaivgationController:(UINavigationController *)navigationContorller {
  UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  ContactViewController *controller = [storyboard instantiateViewControllerWithIdentifier:@"ContactViewController"];
  [navigationContorller pushViewController:controller animated:YES];
  [controller view];
  [controller configureWithInfo:info];
}


问:
Command 'node' not found, but can be installed with: sudo apt install nodejs
I wanted to install bitnami nodejs stack on Ubuntu 18.04. after installing terminal isn't recognizing node command. I even can't check node version.

After installing i have tried to check for node and npm version. But every time I am getting Command 'node' not found, but can be installed with:sudo apt install nodejs. I have already installed nodejs Stack from bitnami. i don't want to install it again. i have tried to setup environment variable through "export PATH=$PATH:/opt/nodejs-10.15.3-2/nodejs/bin" this command. But I can only check nodejs version only once per session. I mean if I close terminal then I can't check nodejs version. so I can't use Visual studio code as node is not recognized.

答:
Bitnami Engineer here. Once you install a Bitnami stack, you need to load the Bitnami environment to use the different components that the stack installs. You can use the Bitnami Console to do so, please run these commands

```<code>cd installdir
./use_APPNAME
</code>```

APPNAME is the name of the stack you installed

You can find more information in our documentation: https://docs.bitnami.com/installer/how-to/understand-bnconsole/

Body:
Bitnami Engineer here. Once you install a Bitnami stack, you need to load the Bitnami environment to use the different components that the stack installs. You can use the Bitnami Console to do so, please run these commands

cd installdir
./use_APPNAME

APPNAME is the name of the stack you installed

You can find more information in our documentation: https://docs.bitnami.com/installer/how-to/understand-bnconsole/


问:
Jenkins Role Strategy - Assign Role
After latest update of 'role based strategy' plugin, I can't assign roles anymore, and I cant see assigned roles.

I'm getting ERROR instead of username, and when I if I click on save, I'm getting:

HTTP ERROR 403 Problem accessing /role-strategy/assignSubmit. Reason:
      No valid crumb was included in the request

This happened before, and I rolled back plugin to earlier version, and all worked file. But right now, i do not have roll back button near that plugin. I should not keep Jenkins up to date.

答: So ok, the problem is actually in GitHub Authentication plugin. Downgrade it to previous version, and everything will work. Hopefully in next version they will fix the problem...</p>

Title: Jenkins Role Strategy - Assign Role


问:
Mixpanel - Bulk delete old users
I am about to go into the next plan in mixpanel for having too many people and would like to delete some old users first.

Is there a simple way/script/api to bulk delete old users?

答:
Using the Mixpanel-api python Module

```<code>pip install mixpanel-api
</code>```

This script will delete any profile that hasn't been seen since January 1st, 2019:

```<code>from mixpanel_api import Mixpanel

mixpanel = Mixpanel('MIXPANEL_SECRET', token='MIXPANEL_TOKEN')

deleted_count = mixpanel.people_delete(query_params={ 'selector' : 'user["$last_seen"]<"2019-01-01T00:00:00"'})
print(deleted_count)
</code>```

Replace MIXPANEL_SECRET and MIXPANEL_TOKEN with your own project tokens.

Title: Mixpanel - Bulk delete old users

Body:
Using the Mixpanel-api python Module

pip install mixpanel-api

This script will delete any profile that hasn't been seen since January 1st, 2019:

from mixpanel_api import Mixpanel

mixpanel = Mixpanel('MIXPANEL_SECRET', token='MIXPANEL_TOKEN')

deleted_count = mixpanel.people_delete(query_params={ 'selector' : 'user["$last_seen"]<"2019-01-01T00:00:00"'})
print(deleted_count)

Replace MIXPANEL_SECRET and MIXPANEL_TOKEN with your own project tokens.


问:
Login failed invalid key error with Facebook SDK
I get "Login failed error" with the Facebook Android SDK while running on the device. I have done everything what they specified, like creating a hash and all.

The error is:

Facebook-authorize(5539): Login failed: invalid_key
  facebook error: com.facebook.android.FacebookError: invalid_key

答: I had a similar problem (invalid_key) and for me the solution was to install Cygwin (I am using Windows 7 64-bit) and regenerate the key from there. I got a totally different key (than on PowerShell) and now my application does login just fine.</p>


问:
Laravel Dusk NoSuchElementException / Unable to locate element
I'm trying to run some basic Laravel Dusk Tests but always running into problems with the Facebook WebDriver:

I already updated chrome to the latest version and manually updated the Chrome WebDriver with Hombrew:

Any suggestions?

Cheers, Stan

Error:

```<code>Tests\Browser\Tests\Auth\SignUpTest::a_user_can_sign_up
Facebook\WebDriver\Exception\NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"body textarea[name='input[name="name"]']"}
  (Session info: headless chrome=64.0.3282.119)
  (Driver info: chromedriver=2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2),platform=Mac OS X 10.12.6 x86_64)
</code>```

MySignUpTest:

```<code>public function a_user_can_sign_up()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit(new SignUpPage)
                ->signUp('Erika Musterfrau', 'erika.musterfrau@socialite.ch', 'password', 'password')
                ->assertPathIs('/dashboard')
                ->assertSeeIn('.navbar', 'Erika Musterfrau');
        });
    }
</code>```

MySignUpPage:

```<code> public function assert(Browser $browser)
    {
        $browser->assertPathIs('/register');
    }

    public function signUp(Browser $browser, $name = null, $email = null, $password = null, $passwordConfirmation = null)
    {
        $browser->type('@name', $name)
            ->type('@email', $email)
            ->type('@password', $password)
            ->type('@password_confirmation', $passwordConfirmation)
            ->press('Register');
    }

    /**
     * Get the element shortcuts for the page.
     *
     * @return array
     */
    public function elements()
    {
        return [
            '@name' => 'input[name="name"]',
            '@email' => 'input[name="email"]',
            '@password' => 'input[name="password"]',
            '@password_confirmation' => 'input[name="password_confirmation"]',
        ];
    }
</code>```

OneOfMyRegisterInputViews:

```<code><div class="form-group row">
                            <div class="col-lg-8 offset-2">
                                <input placeholder="name"
                                        type="text"
                                        class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}"
                                        name="name"
                                        value="{{ old('name') }}"
                                        required
                                >
                                @if ($errors->has('name'))
                                    <div class="invalid-feedback">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </div>
                                @endif
                            </div>
                        </div>
</code>```

答: For those who still have a problem: check APP_URL variable in your Laravel's .env file. URL on which the application is running must match with the APP_URL parameter</p>

Body:
I'm trying to run some basic Laravel Dusk Tests but always running into problems with the Facebook WebDriver:

I already updated chrome to the latest version and manually updated the Chrome WebDriver with Hombrew:

Any suggestions?

Cheers, Stan

Error:

Tests\Browser\Tests\Auth\SignUpTest::a_user_can_sign_up
Facebook\WebDriver\Exception\NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"body textarea[name='input[name="name"]']"}
  (Session info: headless chrome=64.0.3282.119)
  (Driver info: chromedriver=2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2),platform=Mac OS X 10.12.6 x86_64)

MySignUpTest:

public function a_user_can_sign_up()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit(new SignUpPage)
                ->signUp('Erika Musterfrau', 'erika.musterfrau@socialite.ch', 'password', 'password')
                ->assertPathIs('/dashboard')
                ->assertSeeIn('.navbar', 'Erika Musterfrau');
        });
    }

MySignUpPage:

 public function assert(Browser $browser)
    {
        $browser->assertPathIs('/register');
    }

    public function signUp(Browser $browser, $name = null, $email = null, $password = null, $passwordConfirmation = null)
    {
        $browser->type('@name', $name)
            ->type('@email', $email)
            ->type('@password', $password)
            ->type('@password_confirmation', $passwordConfirmation)
            ->press('Register');
    }

    /**
     * Get the element shortcuts for the page.
     *
     * @return array
     */
    public function elements()
    {
        return [
            '@name' => 'input[name="name"]',
            '@email' => 'input[name="email"]',
            '@password' => 'input[name="password"]',
            '@password_confirmation' => 'input[name="password_confirmation"]',
        ];
    }

OneOfMyRegisterInputViews:

                                <input placeholder="name"
                                        type="text"
                                        class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}"
                                        name="name"
                                        value="{{ old('name') }}"
                                        required
                                >
                                @if ($errors->has('name'))

                                        {{ $errors->first('name') }}

                                @endif


问:
How to make a middleware that can call database to check user claims to authorize a user in asp.net core 2.2
What is the best practice to make a middleware or a proper way to implement middleware in asp.net core 2.2.

My Scenario is
I have a web api build in asp.net core 2.2 and I implement authorization in my controller something like this [Authorize(Policy = "UserDelete")] UserDelete is a user claim my problem is i have many user claim can user have, more or less up to 20 claims if I save this claims in JWT it can cause large size of JWT all i want to do is to call claims or create a middleware that call the database for this claims so that all i need to save in JWT is user credentials.

答:
All you need is to create an AuthorizationHandler, please follow the instructions:
1- create a class and name it MinimumPermissionHandler or whatever. copy and paste following codes in it:

```<code>public class MinimumPermissionRequirement : IAuthorizationRequirement { }

public class MinimumPermissionHandler : AuthorizationHandler<MinimumPermissionRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumPermissionRequirement requirement)
    {
        if (!(context.Resource is AuthorizationFilterContext filterContext))
        {
            context.Fail();
            return Task.CompletedTask;
        }

        //check if token has subjectId
        var subClaim = context.User?.Claims?.FirstOrDefault(c => c.Type == "sub");
        if (subClaim == null)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        //check if token is expired
        var exp = context.User.Claims.FirstOrDefault(c => c.Type == "exp")?.Value;
        if(exp == null || new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(long.Parse(exp)).ToLocalTime() < DateTime.Now)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        //other checkpoints
        //your db functions to check if user has desired claims

        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}
</code>```

2- Define a policy and add the handler to services, so put this lines in your Startup class:

```<code>public void ConfigureServices(IServiceCollection services)
{
   //deleted extra lines for brevity
   services.AddAuthorization(options =>
   {
      options.AddPolicy("AccessControl", policy =>
      {
           policy.RequireAuthenticatedUser();
           policy.AddRequirements(new MinimumPermissionRequirement());
      });
   });
   //injection
   services.AddScoped<IAuthorizationHandler, MinimumPermissionHandler>();
}
</code>```

3- Finally for checking access permission just put this code above Controllers

```<code>[Authorize(Policy = "AccessControl")]
</code>```

Body:
All you need is to create an AuthorizationHandler, please follow the instructions:
1- create a class and name it MinimumPermissionHandler or whatever. copy and paste following codes in it:

public class MinimumPermissionRequirement : IAuthorizationRequirement { }

public class MinimumPermissionHandler : AuthorizationHandler<MinimumPermissionRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumPermissionRequirement requirement)
    {
        if (!(context.Resource is AuthorizationFilterContext filterContext))
        {
            context.Fail();
            return Task.CompletedTask;
        }

        //check if token has subjectId
        var subClaim = context.User?.Claims?.FirstOrDefault(c => c.Type == "sub");
        if (subClaim == null)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        //check if token is expired
        var exp = context.User.Claims.FirstOrDefault(c => c.Type == "exp")?.Value;
        if(exp == null || new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(long.Parse(exp)).ToLocalTime() < DateTime.Now)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        //other checkpoints
        //your db functions to check if user has desired claims

        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

2- Define a policy and add the handler to services, so put this lines in your Startup class:

public void ConfigureServices(IServiceCollection services)
{
   //deleted extra lines for brevity
   services.AddAuthorization(options =>
   {
      options.AddPolicy("AccessControl", policy =>
      {
           policy.RequireAuthenticatedUser();
           policy.AddRequirements(new MinimumPermissionRequirement());
      });
   });
   //injection
   services.AddScoped<IAuthorizationHandler, MinimumPermissionHandler>();
}

3- Finally for checking access permission just put this code above Controllers

[Authorize(Policy = "AccessControl")]