问:
How to improve NLTK sentence segmentation?
Given the paragraph from Wikipedia:

An ambitious campus expansion plan was proposed by Fr. Vernon F.
Gallagher in 1952. Assumption Hall, the first student dormitory, was
opened in 1954, and Rockwell Hall was dedicated in November 1958,
housing the schools of business and law. It was during the tenure of
F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to
action.

I run NLTK nltk.sent_tokenize to get the sentences. This returns:

```<code>['An ambitious campus expansion plan was proposed by Fr.',
'Vernon F. Gallagher in 1952.',
'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.',
'It was during the tenure of Fr.',
'Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action.'
 ]
</code>```

While NTLK could handle F. Henry J. McAnulty as one entity,
It failed for Fr. Vernon F. Gallagher, and this broke the sentence into two.

The correct tokenization should be:

```<code>[
'An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952.',
'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.',
'It was during the tenure of Fr. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action.'
 ]
</code>```

How can I improve the tokenizer performance?

答:
The awesome-ness of Kiss and Strunk (2006) Punkt algorithm is that it's unsupervised. So given a new text, you should retrain the model and apply the model to your text, e.g.

```<code>>>> from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters
>>> text = "An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952. Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law. It was during the tenure of F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action."

# Training a new model with the text.
>>> tokenizer = PunktSentenceTokenizer()
>>> tokenizer.train(text)
<nltk.tokenize.punkt.PunktParameters object at 0x106c5d828>

# It automatically learns the abbreviations.
>>> tokenizer._params.abbrev_types
{'f', 'fr', 'j'}

# Use the customized tokenizer.
>>> tokenizer.tokenize(text)
['An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952.', 'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.', "It was during the tenure of F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action."]
</code>```

Where there's not enough data to generate good statistics when re-training the model, you can also put in a pre-determined list of abbreviations before training; see How to avoid NLTK's sentence tokenizer spliting on abbreviations?

```<code>>>> from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters

>>> punkt_param = PunktParameters()
>>> abbreviation = ['f', 'fr', 'k']
>>> punkt_param.abbrev_types = set(abbreviation)

>>> tokenizer = PunktSentenceTokenizer(punkt_param)
>>> tokenizer.train(text)
<nltk.tokenize.punkt.PunktParameters object at 0x106c5d828>

>>> tokenizer.tokenize(text)
['An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952.', 'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.', "It was during the tenure of F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action."]
</code>```

Body:
Given the paragraph from Wikipedia:

An ambitious campus expansion plan was proposed by Fr. Vernon F.
Gallagher in 1952. Assumption Hall, the first student dormitory, was
opened in 1954, and Rockwell Hall was dedicated in November 1958,
housing the schools of business and law. It was during the tenure of
F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to
action.

I run NLTK nltk.sent_tokenize to get the sentences. This returns:

['An ambitious campus expansion plan was proposed by Fr.',
'Vernon F. Gallagher in 1952.',
'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.',
'It was during the tenure of Fr.',
'Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action.'
 ]

While NTLK could handle F. Henry J. McAnulty as one entity,
It failed for Fr. Vernon F. Gallagher, and this broke the sentence into two.

The correct tokenization should be:

[
'An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952.',
'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.',
'It was during the tenure of Fr. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action.'
 ]

How can I improve the tokenizer performance?

Body:
The awesome-ness of Kiss and Strunk (2006) Punkt algorithm is that it's unsupervised. So given a new text, you should retrain the model and apply the model to your text, e.g.

>>> from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters
>>> text = "An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952. Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law. It was during the tenure of F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action."

# Training a new model with the text.
>>> tokenizer = PunktSentenceTokenizer()
>>> tokenizer.train(text)
<nltk.tokenize.punkt.PunktParameters object at 0x106c5d828>

# It automatically learns the abbreviations.
>>> tokenizer._params.abbrev_types
{'f', 'fr', 'j'}

# Use the customized tokenizer.
>>> tokenizer.tokenize(text)
['An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952.', 'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.', "It was during the tenure of F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action."]

Where there's not enough data to generate good statistics when re-training the model, you can also put in a pre-determined list of abbreviations before training; see How to avoid NLTK's sentence tokenizer spliting on abbreviations?

>>> from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters

>>> punkt_param = PunktParameters()
>>> abbreviation = ['f', 'fr', 'k']
>>> punkt_param.abbrev_types = set(abbreviation)

>>> tokenizer = PunktSentenceTokenizer(punkt_param)
>>> tokenizer.train(text)
<nltk.tokenize.punkt.PunktParameters object at 0x106c5d828>

>>> tokenizer.tokenize(text)
['An ambitious campus expansion plan was proposed by Fr. Vernon F. Gallagher in 1952.', 'Assumption Hall, the first student dormitory, was opened in 1954, and Rockwell Hall was dedicated in November 1958, housing the schools of business and law.', "It was during the tenure of F. Henry J. McAnulty that Fr. Gallagher's ambitious plans were put to action."]


来源: stackexchange

问:
@RolesAllowed in conjuction with configureGlobalSecurity jdbcAuthentication in Spring boot
@RolesAllowed does not seem to work when im using jdbcAuthentication(), but it works fine if I am using inMemoryAuthentication(). jdbcAuthentication() works fine if I remove @RolesAllowed.

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.
            jdbcAuthentication()
            .usersByUsernameQuery("select u.email, u.password, u.enabled from bagtag.user u where email=?")
            .authoritiesByUsernameQuery("select u.email, r.name from bagtag.user u join bagtag.role r on (r.id = u.role_id) where u.email=?")
            .dataSource(dataSource)
            .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/api/**").fullyAuthenticated().and().httpBasic()
                .realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint()).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }
}
</code>```

The following RequestMapping does with @RolesAllowed but it works if I remove @RolesAllowed. I am getting the following error.

```<code>{
    "timestamp": 1510628906600,
    "status": 403,
    "error": "Forbidden",
    "exception": "org.springframework.security.access.AccessDeniedException",
    "message": "Access is denied",
    "path": "/api/user/admin"
}

@RestController
@RequestMapping(value = "/api/user", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {

    @Autowired
    UserService us;

    @RolesAllowed(Role.SUPERADMIN)
    @RequestMapping(value = "/admin", method = RequestMethod.POST)
    public ResponseEntity<User> createAdmin(@RequestBody UserWrapper uw) {
       return new ResponseEntity<User>(uw.getUser(), HttpStatus.OK);
    }
}
</code>```

I have tried to inspect the authenticated user with
System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());

which returns

org.springframework.security.core.userdetails.User@ca3b1db5: Username: test@test.dk; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: SUPERADMIN

I have tried to remove @RolesAllowed and replaced the following line in the
http.csrf().disable().authorizeRequests().antMatchers("/api/**").fullyAuthenticated().and().httpBasic()

with

http.csrf().disable().authorizeRequests().antMatchers("/api/**").hasAnyRole(String.format("%s,%s,%s", Role.SUPERADMIN, Role.ADMIN, Role.STAFF)).and().httpBasic()

This gives me http status 403

```<code>{
    "timestamp": 1510629419006,
    "status": 403,
    "error": "Forbidden",
    "message": "Access is denied",
    "path": "/api/user/admin"
}
</code>```

This is my two tables in my database. A user can only have a single role.

```<code>CREATE TABLE `role` (
   `role_id` int(11) NOT NULL AUTO_INCREMENT,
   `role` varchar(255) DEFAULT NULL,
   `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
   PRIMARY KEY (`role_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

CREATE TABLE `user` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `email` varchar(255) NOT NULL,
   `password` varchar(255) NOT NULL,
   `first_name` varchar(255) NOT NULL,
   `last_name` varchar(255) DEFAULT NULL,
   `role_id` int(11) NOT NULL,
   `enabled` bit(1) NOT NULL DEFAULT b'0',
   `last_login` timestamp NULL DEFAULT NULL,
   `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
   PRIMARY KEY (`id`),
   UNIQUE KEY `email_UNIQUE` (`email`),
 ) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8
</code>```

答:
So I found the solution to my problem, I had to add .rolePrefix("ROLE_"); to my configureGlobalSecurity method.

I am not sure why this is the solution. The default role prefix for AuthenticationManagerBuilder is an empty String according to according the documentation. So my best guess is that Spring default role prefix is "ROLE_".

If anyone knows the real explanation behind this madness please either post a comment or an answer. I would be very thanksful!

EDIT:
@RolesAllowed default prefix is ROLE_ which is why you have to add ROLE_ prefix to spring security!

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
     public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
         auth.
            jdbcAuthentication()
            .usersByUsernameQuery(usersQuery)
            .authoritiesByUsernameQuery(rolesQuery)
            .dataSource(dataSource)
            .passwordEncoder(bCryptPasswordEncoder)
            //.rolePrefix fixed the problem
            .rolePrefix("ROLE_");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/api/**")
            .hasAnyRole(String.format("%s,%s,%s", Role.SUPERADMIN, Role.ADMIN, Role.STAFF)).and().httpBasic()
            .realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint()).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
@RolesAllowed does not seem to work when im using jdbcAuthentication(), but it works fine if I am using inMemoryAuthentication(). jdbcAuthentication() works fine if I remove @RolesAllowed.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.
            jdbcAuthentication()
            .usersByUsernameQuery("select u.email, u.password, u.enabled from bagtag.user u where email=?")
            .authoritiesByUsernameQuery("select u.email, r.name from bagtag.user u join bagtag.role r on (r.id = u.role_id) where u.email=?")
            .dataSource(dataSource)
            .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/api/**").fullyAuthenticated().and().httpBasic()
                .realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint()).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }
}

The following RequestMapping does with @RolesAllowed but it works if I remove @RolesAllowed. I am getting the following error.

{
    "timestamp": 1510628906600,
    "status": 403,
    "error": "Forbidden",
    "exception": "org.springframework.security.access.AccessDeniedException",
    "message": "Access is denied",
    "path": "/api/user/admin"
}

@RestController
@RequestMapping(value = "/api/user", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {

    @Autowired
    UserService us;

    @RolesAllowed(Role.SUPERADMIN)
    @RequestMapping(value = "/admin", method = RequestMethod.POST)
    public ResponseEntity<User> createAdmin(@RequestBody UserWrapper uw) {
       return new ResponseEntity<User>(uw.getUser(), HttpStatus.OK);
    }
}

I have tried to inspect the authenticated user with
System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());

which returns

org.springframework.security.core.userdetails.User@ca3b1db5: Username: test@test.dk; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: SUPERADMIN

I have tried to remove @RolesAllowed and replaced the following line in the
http.csrf().disable().authorizeRequests().antMatchers("/api/**").fullyAuthenticated().and().httpBasic()

with

http.csrf().disable().authorizeRequests().antMatchers("/api/**").hasAnyRole(String.format("%s,%s,%s", Role.SUPERADMIN, Role.ADMIN, Role.STAFF)).and().httpBasic()

This gives me http status 403

{
    "timestamp": 1510629419006,
    "status": 403,
    "error": "Forbidden",
    "message": "Access is denied",
    "path": "/api/user/admin"
}

This is my two tables in my database. A user can only have a single role.

CREATE TABLE `role` (
   `role_id` int(11) NOT NULL AUTO_INCREMENT,
   `role` varchar(255) DEFAULT NULL,
   `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
   PRIMARY KEY (`role_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

CREATE TABLE `user` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `email` varchar(255) NOT NULL,
   `password` varchar(255) NOT NULL,
   `first_name` varchar(255) NOT NULL,
   `last_name` varchar(255) DEFAULT NULL,
   `role_id` int(11) NOT NULL,
   `enabled` bit(1) NOT NULL DEFAULT b'0',
   `last_login` timestamp NULL DEFAULT NULL,
   `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
   PRIMARY KEY (`id`),
   UNIQUE KEY `email_UNIQUE` (`email`),
 ) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8

Body:
So I found the solution to my problem, I had to add .rolePrefix("ROLE_"); to my configureGlobalSecurity method.

I am not sure why this is the solution. The default role prefix for AuthenticationManagerBuilder is an empty String according to according the documentation. So my best guess is that Spring default role prefix is "ROLE_".

If anyone knows the real explanation behind this madness please either post a comment or an answer. I would be very thanksful!

EDIT:
@RolesAllowed default prefix is ROLE_ which is why you have to add ROLE_ prefix to spring security!

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
     public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
         auth.
            jdbcAuthentication()
            .usersByUsernameQuery(usersQuery)
            .authoritiesByUsernameQuery(rolesQuery)
            .dataSource(dataSource)
            .passwordEncoder(bCryptPasswordEncoder)
            //.rolePrefix fixed the problem
            .rolePrefix("ROLE_");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/api/**")
            .hasAnyRole(String.format("%s,%s,%s", Role.SUPERADMIN, Role.ADMIN, Role.STAFF)).and().httpBasic()
            .realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint()).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }
}


问:
Return RESTful/json response instead of login form in Spring boot OAUTH2
I'm struggling to return a json response when the user is nog logged in, instead of returning a html login form.

The application is only using @RestController's and I do not want any web support.

```<code>    http
        .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic().disable();
</code>```

When I do a get request using the browser or postman, I receive back the default spring HTML login form.

```<code>security.basic.enabled=true
</code>```

I'm using OATH2, and when I request a token it works great and I get a response like this:

```<code>{
  "access_token": "227803d1-fe94-4e31-b496-3a03bafb9479",
  "token_type": "bearer",
  "refresh_token": "322f4ee9-4c48-4e06-a129-f4b6af93d664",
  "expires_in": 43199,
  "scope": "read write"
}
</code>```

Somehow, it works correct in this example:

https://github.com/royclarkson/spring-rest-service-oauth

And when I'm not authorized, I want back something like this:

```<code>{
  "error": "unauthorized",
  "error_description": "An Authentication object was not found in the SecurityContext"
}
</code>```

But I'm getting a login form, and I want the response above. What am I doing wrong? I litterally can't uderstand why it works in the GitHub example, and not in my case. Is there a way to completely disable the login form, and force the json response?

答:
Will need a custom AuthenticationEntryPoint and override the commence() method.

Indeed, the entry point has to be registered in the Spring Security config

```<code>http.exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
</code>```

Sample code:

```<code>public class UserAuthenticationEntryPoint implements
        AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException ex)
            throws IOException, ServletException {
        response.setContentType("application/json");
        response.getOutputStream().print("{\"error\":\"Unauthorized.. Please authenticate..\"}");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
</code>```

Body:
I'm struggling to return a json response when the user is nog logged in, instead of returning a html login form.

The application is only using @RestController's and I do not want any web support.

    http
        .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic().disable();

When I do a get request using the browser or postman, I receive back the default spring HTML login form.

security.basic.enabled=true

I'm using OATH2, and when I request a token it works great and I get a response like this:

{
  "access_token": "227803d1-fe94-4e31-b496-3a03bafb9479",
  "token_type": "bearer",
  "refresh_token": "322f4ee9-4c48-4e06-a129-f4b6af93d664",
  "expires_in": 43199,
  "scope": "read write"
}

Somehow, it works correct in this example:

https://github.com/royclarkson/spring-rest-service-oauth

And when I'm not authorized, I want back something like this:

{
  "error": "unauthorized",
  "error_description": "An Authentication object was not found in the SecurityContext"
}

But I'm getting a login form, and I want the response above. What am I doing wrong? I litterally can't uderstand why it works in the GitHub example, and not in my case. Is there a way to completely disable the login form, and force the json response?

Body:
Will need a custom AuthenticationEntryPoint and override the commence() method.

Indeed, the entry point has to be registered in the Spring Security config

http.exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)

Sample code:

public class UserAuthenticationEntryPoint implements
        AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException ex)
            throws IOException, ServletException {
        response.setContentType("application/json");
        response.getOutputStream().print("{\"error\":\"Unauthorized.. Please authenticate..\"}");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}


问:
Applescript keystroke not behaving as expected
I'm experimenting with Applescript for the first time, and am trying to build a script to setup my default layout of applications for developing at work. This involves placing applications across multiple Mission Control spaces. My problem at hand is simply moving about the spaces. I found in many posts similar to this that such action could be achieved with

```<code>tell application "System Events"
    tell process "Finder"
        keystroke "1" using control down
    end tell
end tell
</code>```

if the appropriate key binding was in place. I made the Preferences change so I could use control+1 to move to the first MC space. However, running the script doesn't do anything. This is the event log output:

```<code>tell application "System Events"
    keystroke "1" using control down
end tell
</code>```

No errors that I can see, but again: new to Applescript. I've tried many variations of this command including wrapping control down in curly braces and wrapping the call to "System Events" inside a call to "Finder" like this

```<code>tell application "Finder"
    tell application "System Events"
        keystroke "1" using control down
    end tell
end tell
</code>```

but the output is exactly the same with no shift in view. I think I'm missing something here...

According to this question's responses, I tried adding in a delay to make sure I wasn't stepping on my own feet with running the script with CMD-r but nothing happens. I hear the sound effect when you try to click out of an important focus window (if that makes any sense), it's a short beep. Am I talking to the applications improperly?

EDIT

Ok I got something working, but I'm a little confused why this is the case.

```<code>tell application "Finder"
    activate
    delay 0.2
    tell application "System Events" to keystroke "a" using control down
end tell
</code>```

This accomplishes what I need, but I have to change the key binding to a letter. I can replicate the error tone by pressing control+1 when Applescript Editor is active. I guess there's a shortcut for AE that uses the key combo. But why is that running when Finder is supposed to be active?

答:
This should work:

tell application "Finder"

    activate

end tell

    delay 0.2

    tell application "System Events"

key code 18 using {control down}

end tell

Body:
I'm experimenting with Applescript for the first time, and am trying to build a script to setup my default layout of applications for developing at work. This involves placing applications across multiple Mission Control spaces. My problem at hand is simply moving about the spaces. I found in many posts similar to this that such action could be achieved with

tell application "System Events"
    tell process "Finder"
        keystroke "1" using control down
    end tell
end tell

if the appropriate key binding was in place. I made the Preferences change so I could use control+1 to move to the first MC space. However, running the script doesn't do anything. This is the event log output:

tell application "System Events"
    keystroke "1" using control down
end tell

No errors that I can see, but again: new to Applescript. I've tried many variations of this command including wrapping control down in curly braces and wrapping the call to "System Events" inside a call to "Finder" like this

tell application "Finder"
    tell application "System Events"
        keystroke "1" using control down
    end tell
end tell

but the output is exactly the same with no shift in view. I think I'm missing something here...

According to this question's responses, I tried adding in a delay to make sure I wasn't stepping on my own feet with running the script with CMD-r but nothing happens. I hear the sound effect when you try to click out of an important focus window (if that makes any sense), it's a short beep. Am I talking to the applications improperly?

EDIT

Ok I got something working, but I'm a little confused why this is the case.

tell application "Finder"
    activate
    delay 0.2
    tell application "System Events" to keystroke "a" using control down
end tell

This accomplishes what I need, but I have to change the key binding to a letter. I can replicate the error tone by pressing control+1 when Applescript Editor is active. I guess there's a shortcut for AE that uses the key combo. But why is that running when Finder is supposed to be active?


问:
How to use python structure array similar to matlab
Good morning
   I have thoroughly looked around to try figuring out a way to create a
   matlab like struct array in python. My input .csv file is header less

My matlab code

```<code>  dumpdata = csvread('dumpdata.csv');
  N_dumpdata_samples = length(dumpdata);

  rec_sample_1second = struct('UTC_time',{},'sv_id_set',{},'pseudorange',
  {},'state',{});

  for s=1:1:N_dumpdata_samples

    rec_sample_1second(s).UTC_time = dumpdata(s,1);
   rec_sample_1second(s).UTC_time = round(rec_sample_1second(s).
   UTC_time * 10);
   rec_sample_1second(s).UTC_time = rec_sample_1second(s).
   UTC_time / 10;

   for t=1:1:15

       rec_sample_1second(s).sv_id_set(t) = dumpdata(s,t+1);
       rec_sample_1second(s).pseudorange(t) = dumpdata(s,t+16);
       rec_sample_1second(s).state(t) = dumpdata(s,t+31);
       end;
    end;
</code>```

Trying to implement in python

```<code>   import numpy as np
   import pandas as pd

   df = pd.read_csv('path'/Dumpdata.csv',header=None)
   N_dumpdata_samples=len(df)
   structure={}
   structure["parent1"] = {}
  UTC_time=[]
  for s in range(N_dumpdata_samples):
      # structure['parent1']['UTC_time']=df[s,0] -> this line give error
      UTC_time=df['s',0]
  .......
</code>```

My question is : How can I implement same logic and structure in python.

Thanks

答:
When accessing a dataframe using integer locations you need to use df.iloc[int].

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html

For example, if you want to access the instance in the first row and first column you would want to look at df.iloc[0,0].

Body:
Good morning
   I have thoroughly looked around to try figuring out a way to create a
   matlab like struct array in python. My input .csv file is header less

My matlab code

  dumpdata = csvread('dumpdata.csv');
  N_dumpdata_samples = length(dumpdata);

  rec_sample_1second = struct('UTC_time',{},'sv_id_set',{},'pseudorange',
  {},'state',{});

  for s=1:1:N_dumpdata_samples

    rec_sample_1second(s).UTC_time = dumpdata(s,1);
   rec_sample_1second(s).UTC_time = round(rec_sample_1second(s).
   UTC_time * 10);
   rec_sample_1second(s).UTC_time = rec_sample_1second(s).
   UTC_time / 10;

   for t=1:1:15

       rec_sample_1second(s).sv_id_set(t) = dumpdata(s,t+1);
       rec_sample_1second(s).pseudorange(t) = dumpdata(s,t+16);
       rec_sample_1second(s).state(t) = dumpdata(s,t+31);
       end;
    end;

Trying to implement in python

   import numpy as np
   import pandas as pd

   df = pd.read_csv('path'/Dumpdata.csv',header=None)
   N_dumpdata_samples=len(df)
   structure={}
   structure["parent1"] = {}
  UTC_time=[]
  for s in range(N_dumpdata_samples):
      # structure['parent1']['UTC_time']=df[s,0] -> this line give error
      UTC_time=df['s',0]
  .......

My question is : How can I implement same logic and structure in python.

Thanks


问:
Xcode error : Abort trap 6 (only show in device)
it's very strange , my project is all right until I open my Xcode this morning , I did not change any thing but I got an Command failed due to signal: Abort trap: 6 ( I user Xcode9 and Swift4). but with simulations, everything works fine.

I have tried turn swift optimization to [No] but don't work.

答:
You can try out doing one thing if you are using pods

```<code>Step 1 - Make a copy of your project
</code>```

here try 2 different things

```<code>Step 2 - Pod update
</code>```

if this did not work then

```<code>Step 2 - Run pod deintegrate

Step 3 - pod install
</code>```

Just try if it helps

Body:
You can try out doing one thing if you are using pods

Step 1 - Make a copy of your project

here try 2 different things

Step 2 - Pod update

if this did not work then

Step 2 - Run pod deintegrate

Step 3 - pod install

Just try if it helps


问:
One page wordpress template with subscription option
I'm new to wordpress. I have to create a one page template for my site and show a subscribe textbox on it with my own custom style. Later, I will use it to send monthly newsletters. What can be the simplest way to do that? I saw into some plugins like newsletter, subscribe2, but they are complicated and I don't know how to integrate them with my text box. They just provide some sort of widget to show on sidebar. Any tutorial or simple plugin? Please help!</p>

答:
You basically have three options:

a. Use a web-hosted syndication service as per the below. (Easiest to configure)

b. Install some sort of newsletter sending plugin for WordPress. (More control, but more configuration)

c. Use a web-hosted newsletter service like Constant Contact (Expensive and Ugh.).

Try using Feedburner with email subscriptions -- see: http://howtotechtips.blogspot.com/2008/05/create-feedburner-email-subscription.html. You sign up, supply your RSS feed's address, then copy-paste the resulting code where-ever in your template you like. Then, whenever you write a new post, your subscribers are sent an email.

ContentLicense: CC BY-SA 2.5


问:
Visual Studio 2017 Cordova Android build does not generate all icon sizes
I am building a cross-platform Cordova app with Visual Studio 2017. When building my .apk file, Visual Studio only generates icon assets for the device I have plugged in, not all the sizes that need to be supported in a Play Store release.

Relevant line in my config.xml that defines my icon:

<icon src="res/icons/icon_psi_color_edges.png" />

In my .apk file, under assets/, VS only creates a drawable-mdpi-v4 folder, corresponding to the Nexus 4 device I am using as the deployment target.

I would like to have Visual Studio generate all the icon sizes. Is there a solution to this problem?

答:
You can use a "Cordova icon generator" (there are quite a few if you search in Google).

We use http://phonegap.appiq.software/ as it not only generates the icons & screens, it also generates the correct xml that you just copy & paste into your config.xml file (replacing the default icon & screen code).


问:
Sass Preprocessors - Can They Ignore Specific Patterns?
I'm using CodeKit to compile .scss using libsass.  In these files I want to include some Liquid templating

```<code>.some-class {
    color: {{ settings.color_primary }};
}
</code>```

Throws and error though.  Is there a way to tell the preprocessor to let this pass through?

Thanks

答:
Use sass interpolations to insert anything literally

```<code>.some-class {
    color: #{ "{{ settings.color_primary }}" };
}
</code>```

You may also use a helper function for nicer syntax

```<code>@function liquid-var($name) {
    @return #{ "{{ " + $name + " }}" };
}

.some-class {
    color: liquid-var("settings.color_primary");
}
</code>```

Body:
I'm using CodeKit to compile .scss using libsass.  In these files I want to include some Liquid templating

.some-class {
    color: {{ settings.color_primary }};
}

Throws and error though.  Is there a way to tell the preprocessor to let this pass through?

Thanks

Body:
Use sass interpolations to insert anything literally

.some-class {
    color: #{ "{{ settings.color_primary }}" };
}

You may also use a helper function for nicer syntax

@function liquid-var($name) {
    @return #{ "{{ " + $name + " }}" };
}

.some-class {
    color: liquid-var("settings.color_primary");
}


问:
How to connect Unity to back4app?
I'm trying to create Pokemon Go type game with Unity. here the link for the tutorial I follow. I'm new to unity and back4apps. I'm stuck in connecting Unity to back4app server. How to do it? Is there any video tutorials?</p>

答:
this is the link with the instructions from parse Platform

http://docs.parseplatform.org/unity/guide/

Title: How to connect Unity to back4app?


问:
How to get SVG dimentions to scale with screen size?
I've tried changing between <line> and <path> in case the percentage parameters made a difference. But I'm still getting the same issue where the <svg> won't line up with my 's. My end goal is to basically have the 2 ends of the <svg> lock into the border of the 's. Any advice would be amazing.

Pen

html:

```<code><div class="svg-benefitsContainer">
<svg class="benefitSVG" height="500%" width="100%" preserveAspectRatio="none">
    <line class="benefitSVG1" x1="15%" y1="15%" x2="20%" y2="32%" />
</svg>
</div>
<div>
<img src="https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/5a09f06d9140b7f3b7d84274/1510600813361/quality.png" class="benefitsImgMed" />
<img src="https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/5a09f014ec212d1131cf09fc/1510600724150/flash.png" class="benefitsImgLig" />
</code>```

css:

```<code>body {
  background-color: black;
}

.benefitsImgMed,
.benefitsImgLig,
.benefitsImgArr,
.benefitsImgNig {
  position: absolute;
  padding: 10px;
  border-color: white;
  border-width: 5px;
  border-radius: 50%;
  border-style: solid;
}

.benefitsImgMed {
  margin-left: 8%;
  margin-top: 6%;
  width: 13%;
}

.benefitsImgLig {
  margin-top: 32%;
  margin-left: 19%;
  width: 13%;
}

.benefitsImgArr {
  margin-left: 37%;
  margin-top: 3%;
  width: 13%;
}

.benefitsImgNig {
  margin-left: 66%;
  margin-top: 18%;
  width: 13%;
}

.svg-benefitsContainer {
  width: 100%;
  height: 500%;
}

.benefitSVG {
  position: absolute
}

.benefitSVG1 {
  fill: none;
  stroke: white;
  stroke-width: 5;
  /*L 125 315 q -20 200 115 190*/
}
</code>```

答:
Because SVG percentages work differently to HTML percentages.

The <svg> width and height are relative to its parent container width and height respectively.

The <line> x and width are relative to the SVG viewport width.

The <line> y and height are relative to the SVG viewport height.

The <image> left and top are relative to the browser width.

If you want it to be reliable, the safest solution is to put all of the objects in an SVG file together.  It's a lot simpler to understand also.

body{background-color:black;}

line, circle {
  fill: black;
  stroke: white;
  stroke-width: 0.5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="svg-benefitsContainer">
<svg class="benefitSVG" height="100%" width="100%" viewBox="0 0 100 100">
  <line class="benefitSVG1" x1="14.5" y1="12.5" x2="25.5" y2="38.5" />

  <circle cx="14.5" cy="12.5" r="8"/>
  <image xlink:href="https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/5a09f06d9140b7f3b7d84274/1510600813361/quality.png"
       x="8" y="6" width="13" height="13"
       class="benefitsImgMed"/>

  <circle cx="25.5" cy="38.5" r="8"/>
  <image xlink:href="https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/5a09f014ec212d1131cf09fc/1510600724150/flash.png"
       x="19" y="32" width="13" height="13"
       class="benefitsImgLig"/>
</svg></code>```

Body:
I've tried changing between <line> and <path> in case the percentage parameters made a difference. But I'm still getting the same issue where the <svg> won't line up with my 's. My end goal is to basically have the 2 ends of the <svg> lock into the border of the 's. Any advice would be amazing.

Pen

html:

<svg class="benefitSVG" height="500%" width="100%" preserveAspectRatio="none">
    <line class="benefitSVG1" x1="15%" y1="15%" x2="20%" y2="32%" />
</svg>

css:

body {
  background-color: black;
}

.benefitsImgMed,
.benefitsImgLig,
.benefitsImgArr,
.benefitsImgNig {
  position: absolute;
  padding: 10px;
  border-color: white;
  border-width: 5px;
  border-radius: 50%;
  border-style: solid;
}

.benefitsImgMed {
  margin-left: 8%;
  margin-top: 6%;
  width: 13%;
}

.benefitsImgLig {
  margin-top: 32%;
  margin-left: 19%;
  width: 13%;
}

.benefitsImgArr {
  margin-left: 37%;
  margin-top: 3%;
  width: 13%;
}

.benefitsImgNig {
  margin-left: 66%;
  margin-top: 18%;
  width: 13%;
}

.svg-benefitsContainer {
  width: 100%;
  height: 500%;
}

.benefitSVG {
  position: absolute
}

.benefitSVG1 {
  fill: none;
  stroke: white;
  stroke-width: 5;
  /*L 125 315 q -20 200 115 190*/
}

Body:
Because SVG percentages work differently to HTML percentages.

The <svg> width and height are relative to its parent container width and height respectively.

The <line> x and width are relative to the SVG viewport width.

The <line> y and height are relative to the SVG viewport height.

The <image> left and top are relative to the browser width.

If you want it to be reliable, the safest solution is to put all of the objects in an SVG file together.  It's a lot simpler to understand also.

body{background-color:black;}

line, circle {
  fill: black;
  stroke: white;
  stroke-width: 0.5;
}

<div class="svg-benefitsContainer">
<svg class="benefitSVG" height="100%" width="100%" viewBox="0 0 100 100">
  <line class="benefitSVG1" x1="14.5" y1="12.5" x2="25.5" y2="38.5" />

  <circle cx="14.5" cy="12.5" r="8"/>
  <image xlink:href="https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/5a09f06d9140b7f3b7d84274/1510600813361/quality.png"
       x="8" y="6" width="13" height="13"
       class="benefitsImgMed"/>

  <circle cx="25.5" cy="38.5" r="8"/>
  <image xlink:href="https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/5a09f014ec212d1131cf09fc/1510600724150/flash.png"
       x="19" y="32" width="13" height="13"
       class="benefitsImgLig"/>
</svg>


问:
Need to design a table with loads of attributes which must all be searchable by SQL
I'm in a fix here. I'm building a home reservation site and the client requires a filter search facility to allow visitors to search and filter through properties based upon criteria. The thing is that his list of criteria is exceedingly long, largely boolean values and calculable values stuff like:

Attached bathroom, balcony, smoking, alcoholic, maximum number of occupants, cable TV, Internet, carpeted, airconditioning, central heating, room service, etc., etc., etc...

I'm thinking of having to create a field for each of these, but there's a very strong chance that the number of preferences might even go up. I dished out the idea of storing everying in a serialised object as a string as then it would be impossible to search using an SQL query. Do I have any options apart from setting up individual fields for each preference here?

Thanks. I'm using PHP MySQL.

答:
You could do a mapping like suggested before but include a value in the mapping

Hotel Table

```<code>create table hotel_table (
 id int(4) unsigned not null auto_increment primary key,
 hotel_name varchar(40) not null,
 ...other row info
);
</code>```

Hotel Criteria

```<code>create table hotel_criteria (
 id int(4) unsigned not null auto_increment primary key,
 criteria_name varchar(40) not null
);
</code>```

Hotel Criteria Map

```<code>create table hotel_criteria_map (
 id int(4) unsigned not null auto_increment primary key,
 hotel_id int(4) unsigned not null,
 criteria_id int(4) unsigned not null,
 string_data varchar(20) null, #use this to add in extra string information for criteria
 decimal_data decimal(6,2) null, #use this to add in extra decimal information for criteria
 #... either of the above or other extra info, just giving examples ...
 unique key (hotel_id,criteria_id),
 foreign key (hotel_id) references hotel_table(id),
 foreign key (criteria_id) references hotel_criteria(id)
);
</code>```

You could then select those values:

```<code>select * from hotel_table where id={your hotel id}; #hotel info

select m.*,c.criteria_name from hotel_criteria_map m, hotel_criteria c where m.criteria_id=c.id and hotel_id={your hotel id}; #criteria info
</code>```

There may be a better way to do this but just a suggestion.  You would only enter the criteria for a certain hotel into the map if it pertained to that certain hotel (essentially not having any criteria map rows that would be bool 0).

Body:
You could do a mapping like suggested before but include a value in the mapping

Hotel Table

create table hotel_table (
 id int(4) unsigned not null auto_increment primary key,
 hotel_name varchar(40) not null,
 ...other row info
);

Hotel Criteria

create table hotel_criteria (
 id int(4) unsigned not null auto_increment primary key,
 criteria_name varchar(40) not null
);

Hotel Criteria Map

create table hotel_criteria_map (
 id int(4) unsigned not null auto_increment primary key,
 hotel_id int(4) unsigned not null,
 criteria_id int(4) unsigned not null,
 string_data varchar(20) null, #use this to add in extra string information for criteria
 decimal_data decimal(6,2) null, #use this to add in extra decimal information for criteria
 #... either of the above or other extra info, just giving examples ...
 unique key (hotel_id,criteria_id),
 foreign key (hotel_id) references hotel_table(id),
 foreign key (criteria_id) references hotel_criteria(id)
);

You could then select those values:

select * from hotel_table where id={your hotel id}; #hotel info

select m.*,c.criteria_name from hotel_criteria_map m, hotel_criteria c where m.criteria_id=c.id and hotel_id={your hotel id}; #criteria info

There may be a better way to do this but just a suggestion.  You would only enter the criteria for a certain hotel into the map if it pertained to that certain hotel (essentially not having any criteria map rows that would be bool 0).


问:
Array/Results Code not working
Good afternoon! I have 5 job titles in an array (mechanic, cleaner, driver, cashier, electrician). I'm also looking to have an input box and a submit button. I want to be able to put a number (let's say 3) and have the JS print out jobs 1,2 and 3, in this case it would print out mechanic, cleaner and driver. I'm a little confused on what to do. I'd appreciate some help.</p>

答:
HOPE THIS HELPS...

$(document).ready(function(){
  $('#btnval').click(function(){
    $val=$('#txtval').val();
     //$val=3;
      var job = ['mechanic', 'cleaner', 'driver', 'cashier', 'electrician'];
var text = "";
var i;
for (i = 0; i < $val; i++) {
    text += job[i] + "
";
}
document.getElementById("demo").innerHTML = text;

  });
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Display" id="btnval" />
<div id="demo">

</div></code>```

Title: Array/Results Code not working

Body:
HOPE THIS HELPS...

$(document).ready(function(){
  $('#btnval').click(function(){
    $val=$('#txtval').val();
     //$val=3;
      var job = ['mechanic', 'cleaner', 'driver', 'cashier', 'electrician'];
var text = "";
var i;
for (i = 0; i < $val; i++) {
    text += job[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;

  });
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Display" id="btnval" />
<div id="demo">

</div>


问:
React.js typescript sweetalert error
i'm using React.js with Typescript and i'm having this error:

```<code>node_modules\@types\sweetalert\index.d.ts
error TS2451: Cannot redeclare block-scoped variable 'sweetAlert'.
</code>```

dependencies:

```<code>"dependencies": {
    "react": "^16.1.0",
    "react-dom": "^16.1.0",
    "react-router-dom": "^4.2.2",
    "react-scripts-ts": "2.8.0",
    "sweetalert": "^2.0.8"
  },
  "devDependencies": {
    "@types/jest": "^21.1.6",
    "@types/node": "^8.0.51",
    "@types/react": "^16.0.22",
    "@types/react-dom": "^16.0.3",
    "@types/react-router-dom": "^4.2.1",
    "@types/sweetalert": "^1.1.28"
  }
</code>```

答:
Cannot redeclare block-scoped variable 'sweetAlert'.

sweetAlert is written in TypeScript and you do not need @types/sweetAlert anymore.

Fix

```<code>npm uninstall @types/sweetAlert
</code>```

Profit

Title: React.js typescript sweetalert error

Body:
i'm using React.js with Typescript and i'm having this error:

node_modules\@types\sweetalert\index.d.ts
error TS2451: Cannot redeclare block-scoped variable 'sweetAlert'.

dependencies:

"dependencies": {
    "react": "^16.1.0",
    "react-dom": "^16.1.0",
    "react-router-dom": "^4.2.2",
    "react-scripts-ts": "2.8.0",
    "sweetalert": "^2.0.8"
  },
  "devDependencies": {
    "@types/jest": "^21.1.6",
    "@types/node": "^8.0.51",
    "@types/react": "^16.0.22",
    "@types/react-dom": "^16.0.3",
    "@types/react-router-dom": "^4.2.1",
    "@types/sweetalert": "^1.1.28"
  }

Body:
Cannot redeclare block-scoped variable 'sweetAlert'.

sweetAlert is written in TypeScript and you do not need @types/sweetAlert anymore.

Fix

npm uninstall @types/sweetAlert

Profit


问:
How to add multiple styles based on property with styled-components?
In CSS/LESS I would do this:

```<code>.button {
    &:active, .active {
        background-color: #393939;
        border-color: #2F2F2F;
        box-shadow: inset 0 0 0 1px #3D3D3D,
            inset 0 2px 0 #323232;

    }
}
</code>```

Where :active is the style for my button when it's being clicked, and .active is the class I would add to the button when it's active (for toggle-able button).

With styled-components I presently have this:

```<code>import styled from 'styled-components';

export default styled.button`
    width: 32px;
    height: 32px;
    border-radius: 5px;
    background-color: #535353;
    border: 1px solid transparent;
    cursor: pointer;
    outline: none;
    padding: 4px;

    &:active, /* what to do here?? */ {
        background-color: #393939;
        border-color: #2F2F2F;
        box-shadow: inset 0 0 0 1px #3D3D3D,
            inset 0 2px 0 #323232;

    }
`
</code>```

But I don't know how to re-use all those :active styles based on some property. I know I can access the prop with ${props => prop.active}, but I don't know how to re-use that block of styles without repeating all those styles again.

How would I do this?

答:
If you want to share some styles you could simply move it into a variable that you use in both places:</p>

```<code>import styled, { css } from 'styled-components'

const activeStyles = `
   background-color: #393939;
    border-color: #2F2F2F;
    box-shadow: inset 0 0 0 1px #3D3D3D,
        inset 0 2px 0 #323232;
`

export default styled.button`
  width: 32px;
  height: 32px;
  border-radius: 5px;
  background-color: #535353;
  border: 1px solid transparent;
  cursor: pointer;
  outline: none;
  padding: 4px;

  &:active {
    ${activeStyles}
  }

  ${props => props.active ? css`${activeStyles}` : ''}
`
</code>```

Body:
In CSS/LESS I would do this:

.button {
    &:active, .active {
        background-color: #393939;
        border-color: #2F2F2F;
        box-shadow: inset 0 0 0 1px #3D3D3D,
            inset 0 2px 0 #323232;

    }
}

Where :active is the style for my button when it's being clicked, and .active is the class I would add to the button when it's active (for toggle-able button).

With styled-components I presently have this:

import styled from 'styled-components';

export default styled.button`
    width: 32px;
    height: 32px;
    border-radius: 5px;
    background-color: #535353;
    border: 1px solid transparent;
    cursor: pointer;
    outline: none;
    padding: 4px;

    &:active, /* what to do here?? */ {
        background-color: #393939;
        border-color: #2F2F2F;
        box-shadow: inset 0 0 0 1px #3D3D3D,
            inset 0 2px 0 #323232;

    }
`

But I don't know how to re-use all those :active styles based on some property. I know I can access the prop with ${props => prop.active}, but I don't know how to re-use that block of styles without repeating all those styles again.

How would I do this?

Body:
If you want to share some styles you could simply move it into a variable that you use in both places:

import styled, { css } from 'styled-components'

const activeStyles = `
   background-color: #393939;
    border-color: #2F2F2F;
    box-shadow: inset 0 0 0 1px #3D3D3D,
        inset 0 2px 0 #323232;
`

export default styled.button`
  width: 32px;
  height: 32px;
  border-radius: 5px;
  background-color: #535353;
  border: 1px solid transparent;
  cursor: pointer;
  outline: none;
  padding: 4px;

  &:active {
    ${activeStyles}
  }

  ${props => props.active ? css`${activeStyles}` : ''}
`

ContentLicense: CC BY-SA 4.0


问:
reset userdefualts every time button is pressed (swift4)
I am trying to use userdefualts to save a tuple displayed on a label. Right now my code uses userdefulats as followed. If a, 2 then a, 3 is entered. The label displays a,2 a,2, a,3. The label is just appending each new entry. I need the userdefualt to overwrite whatever was just saved. So it should only display a,2 a,3. </p>

```<code>        @IBAction func submitText(_ sender: Any) {
        if let domain = Bundle.main.bundleIdentifier {
            UserDefaults.standard.removePersistentDomain(forName: domain)
        }

        llble.text = String(describing: result) + "\n"
                    UserDefaults.standard.set(llble.text, forKey: "name")

        }

    override func viewDidAppear(_ animated: Bool) {
        let save : String? = UserDefaults.standard.object(forKey: "name") as? String
        if let nameToDisplay = save {
            llble.text = nameToDisplay
        }
    }
</code>```

答:
You can use the following approach in Swift. This would remove and delete all possible user defaults value.</p>

```<code>UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
UserDefaults.standard.synchronize()
</code>```

Body:
I am trying to use userdefualts to save a tuple displayed on a label. Right now my code uses userdefulats as followed. If a, 2 then a, 3 is entered. The label displays a,2 a,2, a,3. The label is just appending each new entry. I need the userdefualt to overwrite whatever was just saved. So it should only display a,2 a,3.

        @IBAction func submitText(_ sender: Any) {
        if let domain = Bundle.main.bundleIdentifier {
            UserDefaults.standard.removePersistentDomain(forName: domain)
        }

        llble.text = String(describing: result) + "\n"
                    UserDefaults.standard.set(llble.text, forKey: "name")

        }

    override func viewDidAppear(_ animated: Bool) {
        let save : String? = UserDefaults.standard.object(forKey: "name") as? String
        if let nameToDisplay = save {
            llble.text = nameToDisplay
        }
    }

Body:
You can use the following approach in Swift. This would remove and delete all possible user defaults value.

UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
UserDefaults.standard.synchronize()


问:
malloc : error double free with printf and a NULL wchar_t*
I'm trying to port an application from Linux to Mac Os X (leopard), but when I execute it, I have this error message : malloc: *** error for object 0x100160 : double free.

I've reproduced this issue with the code below :

```<code>//main.cpp
#include <stdio.h>
#include <wchar.h>

int main(int argc, char*argv[])
{
    wchar_t *b=NULL;
    printf("a=%ls, b=%ls \n", L"a", b);
}
</code>```

Compiled with gcc:

```<code>gcc main.cpp -o test
</code>```

The output of the execution:

```<code>a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug
</code>```

It's strange because if I use this line : printf("a=%ls, b=%ls", b, b), no error are printed.
Furthermore, I can't use wprintf(L"a=%ls, b=%ls", a, b).
On Fedora 13, this program don't print any error.

Is it a printf bug?
How can I remove this error?

答:
This is simply a bug in vprintf_l, which handles printf (and presumably all its friends).

Strictly speaking, the library is within its rights to handle this situation by doing whatever it likes, heap corruption included, but judging by the code the intent -- as should be the case for any non-rubbish printf implementation -- is to handle NULL strings sensibly. There is simply a bug in the code that does this. These things happen.

If an attempt is made to print a NULL wide char pointer after a previous non-NULL wide char pointer was printed, vprintf_l will cock up on the next string argument, or when vprintf_l exits. (There may be other ways to get this to happen, too, I suppose - I didn't check.)

The offending code is here:

```<code>    case 's':
        if (flags & LONGINT) {
            wchar_t *wcp;

            if (convbuf != NULL)
                free(convbuf);
            if ((wcp = GETARG(wchar_t *)) == NULL)
                cp = "(null)";
            else {
                convbuf = __wcsconv(wcp, prec, loc);
                if (convbuf == NULL) {
                    fp->_flags |= __SERR;
                    goto error;
                }
                cp = convbuf;
            }
        } else if ((cp = GETARG(char *)) == NULL)
</code>```

If GETARG(wchar_t *) returns NULL, convbuf will point to the old (and now freed) buffer. Then, when the function exits, there is a double free:

```<code>if (convbuf != NULL)
    free(convbuf);
</code>```

The same would apply were there another string argument, though in this case the double free happens in the case 's' code above:

```<code>printf("a=%ls, b=%ls c=%ls\n", L"a", b, L"c");
</code>```

The solution of course would be to set convbuf to NULL after it is freed.

The printf code is here:

http://www.opensource.apple.com/source/Libc/Libc-594.1.4/stdio/vfprintf-fbsd.c

Judging by the disassembly, it is the code that is used for the default runtime in Snow Leopard.

Body:
I'm trying to port an application from Linux to Mac Os X (leopard), but when I execute it, I have this error message : malloc: *** error for object 0x100160 : double free.

I've reproduced this issue with the code below :

//main.cpp
#include <stdio.h>
#include <wchar.h>

int main(int argc, char*argv[])
{
    wchar_t *b=NULL;
    printf("a=%ls, b=%ls \n", L"a", b);
}

Compiled with gcc:

gcc main.cpp -o test

The output of the execution:

a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug

It's strange because if I use this line : printf("a=%ls, b=%ls", b, b), no error are printed.
Furthermore, I can't use wprintf(L"a=%ls, b=%ls", a, b).
On Fedora 13, this program don't print any error.

Is it a printf bug?
How can I remove this error?

Body:
This is simply a bug in vprintf_l, which handles printf (and presumably all its friends).

Strictly speaking, the library is within its rights to handle this situation by doing whatever it likes, heap corruption included, but judging by the code the intent -- as should be the case for any non-rubbish printf implementation -- is to handle NULL strings sensibly. There is simply a bug in the code that does this. These things happen.

If an attempt is made to print a NULL wide char pointer after a previous non-NULL wide char pointer was printed, vprintf_l will cock up on the next string argument, or when vprintf_l exits. (There may be other ways to get this to happen, too, I suppose - I didn't check.)

The offending code is here:

    case 's':
        if (flags & LONGINT) {
            wchar_t *wcp;

            if (convbuf != NULL)
                free(convbuf);
            if ((wcp = GETARG(wchar_t *)) == NULL)
                cp = "(null)";
            else {
                convbuf = __wcsconv(wcp, prec, loc);
                if (convbuf == NULL) {
                    fp->_flags |= __SERR;
                    goto error;
                }
                cp = convbuf;
            }
        } else if ((cp = GETARG(char *)) == NULL)

If GETARG(wchar_t *) returns NULL, convbuf will point to the old (and now freed) buffer. Then, when the function exits, there is a double free:

if (convbuf != NULL)
    free(convbuf);

The same would apply were there another string argument, though in this case the double free happens in the case 's' code above:

printf("a=%ls, b=%ls c=%ls\n", L"a", b, L"c");

The solution of course would be to set convbuf to NULL after it is freed.

The printf code is here:

http://www.opensource.apple.com/source/Libc/Libc-594.1.4/stdio/vfprintf-fbsd.c

Judging by the disassembly, it is the code that is used for the default runtime in Snow Leopard.

OwnerDisplayName: please delete me


问:
show different colors when user posts something
I made a form where user posts just links and text. No images and videos. I also did some kind of validations from server side in PHP. I also did very basic SQL INSERT for storing data in database. What I want is, that whenever user posts, it is always displayed on a website with different colors from database. I Googled it but got nothing. Any idea, or help on where to start?

Simple html form:

```<code><form action="checkbox1.php" method="post">
    <input name="name" id="name" type="text"/><br/>
    <input type="text" id="name2" name="name2"><br/>
    <input type="checkbox" id="checkbox" name="checkbox"><br/>
    <input type="submit" id="submit" name="submit">
</form>
</code>```

答:
```<code>.postHolder:nth-child(5n+0) .post-text {
   background: #8dc63f;
}
.postHolder:nth-child(5n+1) .post-text  {
   background: #009688;
}
.postHolder:nth-child(5n+2) .post-text  {
   background: #3f51b5;
}
.postHolder:nth-child(5n+3) .post-text  {
   background: #f44336;
}
.postHolder:nth-child(5n+4) .post-text  {
   background: #607d8b;
}
</code>```

This example will work in your case, .postHolder is the class of the dive which will repeat for every post, and .post-text is class where you actually want to apply CSS, I have applied background color you can add whatever you want.

Body:
I made a form where user posts just links and text. No images and videos. I also did some kind of validations from server side in PHP. I also did very basic SQL INSERT for storing data in database. What I want is, that whenever user posts, it is always displayed on a website with different colors from database. I Googled it but got nothing. Any idea, or help on where to start?

Simple html form:

<form action="checkbox1.php" method="post">
    <input name="name" id="name" type="text"/>

    <input type="text" id="name2" name="name2">

    <input type="checkbox" id="checkbox" name="checkbox">

    <input type="submit" id="submit" name="submit">
</form>

Body:
.postHolder:nth-child(5n+0) .post-text {
   background: #8dc63f;
}
.postHolder:nth-child(5n+1) .post-text  {
   background: #009688;
}
.postHolder:nth-child(5n+2) .post-text  {
   background: #3f51b5;
}
.postHolder:nth-child(5n+3) .post-text  {
   background: #f44336;
}
.postHolder:nth-child(5n+4) .post-text  {
   background: #607d8b;
}

This example will work in your case, .postHolder is the class of the dive which will repeat for every post, and .post-text is class where you actually want to apply CSS, I have applied background color you can add whatever you want.


问:
Resize Bootstrap 4 Dropdown Caret Size
Im using Bootstrap v4 framework in my html page. now i would like to resize or increase caret size in my dropdown list. Does anyone know how to do this?

Here it is my code

```<code><div class="container">
<form name="books">
    <div class="form-group">
    <select class="form-control" style="height:3rem">
        <option>Select Category</option>
        <option value="1">Tamil</option>
        <option value="2">English</option>
        <option value="3">Mathematics</option>
        <option value="4">Science</option>
    </select>
    </div>
</form>
</div>
</code>```

答:
In order to do that just increase the size of the border</p>

```<code>.dropdown-toggle::after {
    display: inline-block;
    width: 0;
    height: 0;
    margin-left: .3em;
    vertical-align: middle;
    content: "";
    border-top: .5em solid;
    border-right: .5em solid transparent;
    border-left: .5em solid transparent;
}
</code>```

Title: Resize Bootstrap 4 Dropdown Caret Size

Body:
Im using Bootstrap v4 framework in my html page. now i would like to resize or increase caret size in my dropdown list. Does anyone know how to do this?

Here it is my code

<form name="books">

    <select class="form-control" style="height:3rem">
        <option>Select Category</option>
        <option value="1">Tamil</option>
        <option value="2">English</option>
        <option value="3">Mathematics</option>
        <option value="4">Science</option>
    </select>

</form>

Body:
In order to do that just increase the size of the border

.dropdown-toggle::after {
    display: inline-block;
    width: 0;
    height: 0;
    margin-left: .3em;
    vertical-align: middle;
    content: "";
    border-top: .5em solid;
    border-right: .5em solid transparent;
    border-left: .5em solid transparent;
}


问:
How programmatically push segue in Storyboard?

How to push view controller programmatically? In some case not button press but programmatic trigger needs. How?

Need write something like:

```<code>[self performSegueWithIdentifier:@"menu41" sender:self];
</code>```

or

```<code>[self.self.navigationController performSegueWithIdentifier:@"menu41" sender:self];
</code>```

Added an identifier "menu41" to segue.

答:
You can try this:
use this code to perform segue:

self.performSegueWithIdentifier("menu41", sender: self)

This will call method where you can pass values or perform any specific activity as per requirement.

override func prepareForSegue(segue: UIStoryboardSegue!, sender:
  AnyObject!) { if segue.identifier == "menu41" {

}

Body:
How to push view controller programmatically? In some case not button press but programmatic trigger needs. How?

Need write something like:

[self performSegueWithIdentifier:@"menu41" sender:self];

or

[self.self.navigationController performSegueWithIdentifier:@"menu41" sender:self];

Added an identifier "menu41" to segue.


问:
Can't run app with Instant Run on Android Studio 3.0
I've updated to Android Studio 3.0 and now I cannot run the app with Instant Run enabled.

I get 'Execution failed for task' due to a java.io.FileNotFoundException because it can't find the apk under

../build/intermediates/instant-run-resources/resources-production/

Any idea how to overcome this so that I can run the project with Instant Run?

I'm not sure where to find the missing apk file or how to change the path to look for it in.

答:
Configure your project for Instant Run

Android Studio enables Instant Run by default for projects built using Android plugin for Gradle 2.3.0 and higher.
Please checkout this LINK to configure your project for instant run.


问:
Xamarin Progress dialog to show and hide
I am having some difficulty in showing the progress view in my Xamarin app. I believe its do with the different threads. Here is my code.

```<code>private void NavigateCommand()
    {
       using (UserDialogs.Instance.Loading("Verifying Credentials",null, null, true, MaskType.Black))
                {
                try
                    {
                    var authResult = Task.Run(async () => await _loginService
                                            .Login(Priority.Background, EmailAddress.Value, Password.Value)
                                                  .ConfigureAwait(false)).Result;

                        CacheToken(authResult);
                    }
                    catch { }
                }

            Device.BeginInvokeOnMainThread(() => UserDialogs.Instance.HideLoading());
            _navigationService.NavigateAsync("PageOnePage");
    }
</code>```

So what is happening now is that, the progress/loading view does not show until the second last line (which is the code for hiding) is executed. Its a quick flash and it disappears. I appreciate any help.

答:
Something like this should work as it places your UserDialogs/ NavigateAsync calls on the UI thread and Login/CacheToken on a background thread:

```<code>private void NavigateCommand()
{
    Device.BeginInvokeOnMainThread(async () =>
    {
        using (UserDialogs.Instance.Loading("Verifying Credentials", null, null, true, MaskType.Black))
        {
            await Task.Run(async () =>
            {
                var authResult = await _loginService.Login(Priority.Background, EmailAddress.Value, Password.Value);
                CacheToken(authResult);
            });
            Device.BeginInvokeOnMainThread(() =>
            {
                UserDialogs.Instance.HideLoading();
                _navigationService.NavigateAsync("PageOnePage");
            });
        }
    });
}
</code>```

Body:
I am having some difficulty in showing the progress view in my Xamarin app. I believe its do with the different threads. Here is my code.

private void NavigateCommand()
    {
       using (UserDialogs.Instance.Loading("Verifying Credentials",null, null, true, MaskType.Black))
                {
                try
                    {
                    var authResult = Task.Run(async () => await _loginService
                                            .Login(Priority.Background, EmailAddress.Value, Password.Value)
                                                  .ConfigureAwait(false)).Result;

                        CacheToken(authResult);
                    }
                    catch { }
                }

            Device.BeginInvokeOnMainThread(() => UserDialogs.Instance.HideLoading());
            _navigationService.NavigateAsync("PageOnePage");
    }

So what is happening now is that, the progress/loading view does not show until the second last line (which is the code for hiding) is executed. Its a quick flash and it disappears. I appreciate any help.

Body:
Something like this should work as it places your UserDialogs/ NavigateAsync calls on the UI thread and Login/CacheToken on a background thread:

private void NavigateCommand()
{
    Device.BeginInvokeOnMainThread(async () =>
    {
        using (UserDialogs.Instance.Loading("Verifying Credentials", null, null, true, MaskType.Black))
        {
            await Task.Run(async () =>
            {
                var authResult = await _loginService.Login(Priority.Background, EmailAddress.Value, Password.Value);
                CacheToken(authResult);
            });
            Device.BeginInvokeOnMainThread(() =>
            {
                UserDialogs.Instance.HideLoading();
                _navigationService.NavigateAsync("PageOnePage");
            });
        }
    });
}


问:
onNavigationItemSelected not being called for Bottom Navigation Bar
I'm trying to implement a bottom nav bar that changes fragments when the nav items are clicked. However, when I click on the nav bar items, the fragments don't change. Using log.d, I noticed onNavigationItemSelected is not being called. How do I fix this?

To note, the  startFeedFragment, startScheduleFragment, & startSettingsFragmentare implemented the same way and they work for the buttons in the toolbar. I also referenced this tutorial and this question for help.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setUpRecycler();
        startFeedFragment();

        BottomNavigationView bottomNavBar = (BottomNavigationView) findViewById(R.id.navigation);
        bottomNavBar.bringToFront();
        bottomNavBar.setOnNavigationItemSelectedListener(this);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Log.d("NAV BAR", "onNavigationItemSelected hit");
        switch (item.getItemId()) {
            case R.id.feedMenu:
                startFeedFragment();
                Log.d("NAV BAR", "feed");
                break;
            case R.id.myScheduleMenu:
                startScheduleFragment();
                Log.d("NAV BAR", "schedule");
                break;
            case R.id.settingsMenu:
                startSettingsFragment();
                Log.d("NAV BAR", "settings lol");
                break;
            default:
                Log.d("NAV BAR", "false");
                return false;
        }
        return true;
    }

   /**
     * Switches out the fragment for {@link FeedFragment} and sets an appropriate title. startScheduleFragmens & startSettingsFragment are implemented the same way
     */
    private void startFeedFragment()
    {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragmentContainer, new FeedFragment());
        transaction.commit();
        getSupportActionBar().setTitle(R.string.title_fragment_feed);
    }
}
</code>```

Snippet from xml file

```<code>    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <FrameLayout
            android:id="@+id/fragmentContainer"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/navigation"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:itemBackground="@android:color/white"
            app:itemIconTint="@color/colorPrimaryDark"
            app:itemTextColor="@color/colorPrimaryDark"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/bottom_nav"
            android:elevation="8dp"/>
    </android.support.constraint.ConstraintLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
Solved! It was because I had set the buttons in the menu to android:enabled="false". That meant they couldn't be pressed, which is why onNavigationItemSelected wasn't being called. I set all buttons to android:enabled="true" to fix this.

Correct code for bottom_nav.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/bottom_nav_my_schedule"
        android:title="@string/menu_my_schedule"
        android:icon="@drawable/ic_event_available_white_24dp"
        android:enabled="true"/> <!--make sure enabled is set to true!-->
    <item android:id="@+id/bottom_nav_feed"
        android:title="@string/menu_feed"
        android:icon="@drawable/ic_view_list_white_24dp"
        android:enabled="true" /> <!--make sure enabled is set to true!-->
    <item android:id="@+id/bottom_nav_settings"
        android:title="@string/menu_settings"
        android:icon="@drawable/ic_settings_white_24dp"
        android:enabled="true"/> <!--make sure enabled is set to true!-->
</menu>
</code>```

Body:
I'm trying to implement a bottom nav bar that changes fragments when the nav items are clicked. However, when I click on the nav bar items, the fragments don't change. Using log.d, I noticed onNavigationItemSelected is not being called. How do I fix this?

To note, the  startFeedFragment, startScheduleFragment, & startSettingsFragmentare implemented the same way and they work for the buttons in the toolbar. I also referenced this tutorial and this question for help.

MainActivity.java

public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setUpRecycler();
        startFeedFragment();

        BottomNavigationView bottomNavBar = (BottomNavigationView) findViewById(R.id.navigation);
        bottomNavBar.bringToFront();
        bottomNavBar.setOnNavigationItemSelectedListener(this);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Log.d("NAV BAR", "onNavigationItemSelected hit");
        switch (item.getItemId()) {
            case R.id.feedMenu:
                startFeedFragment();
                Log.d("NAV BAR", "feed");
                break;
            case R.id.myScheduleMenu:
                startScheduleFragment();
                Log.d("NAV BAR", "schedule");
                break;
            case R.id.settingsMenu:
                startSettingsFragment();
                Log.d("NAV BAR", "settings lol");
                break;
            default:
                Log.d("NAV BAR", "false");
                return false;
        }
        return true;
    }

   /**
     * Switches out the fragment for {@link FeedFragment} and sets an appropriate title. startScheduleFragmens & startSettingsFragment are implemented the same way
     */
    private void startFeedFragment()
    {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragmentContainer, new FeedFragment());
        transaction.commit();
        getSupportActionBar().setTitle(R.string.title_fragment_feed);
    }
}

Snippet from xml file

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <FrameLayout
            android:id="@+id/fragmentContainer"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/navigation"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:itemBackground="@android:color/white"
            app:itemIconTint="@color/colorPrimaryDark"
            app:itemTextColor="@color/colorPrimaryDark"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/bottom_nav"
            android:elevation="8dp"/>
    </android.support.constraint.ConstraintLayout>

</android.support.design.widget.CoordinatorLayout>

Body:
Solved! It was because I had set the buttons in the menu to android:enabled="false". That meant they couldn't be pressed, which is why onNavigationItemSelected wasn't being called. I set all buttons to android:enabled="true" to fix this.

Correct code for bottom_nav.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/bottom_nav_my_schedule"
        android:title="@string/menu_my_schedule"
        android:icon="@drawable/ic_event_available_white_24dp"
        android:enabled="true"/> <!--make sure enabled is set to true!-->
    <item android:id="@+id/bottom_nav_feed"
        android:title="@string/menu_feed"
        android:icon="@drawable/ic_view_list_white_24dp"
        android:enabled="true" /> <!--make sure enabled is set to true!-->
    <item android:id="@+id/bottom_nav_settings"
        android:title="@string/menu_settings"
        android:icon="@drawable/ic_settings_white_24dp"
        android:enabled="true"/> <!--make sure enabled is set to true!-->
</menu>


问:
Javascript setter function with prototyping
I am learning Javascript. When I try to use setters with prototyping I am getting an error

TypeError: cir1.radiusToCircle is not a function

```<code>var Circle = function(radius){
    this._radius = radius;
}

//prototype

Circle.prototype ={
    set radiusToCircle(rad) { this._radius = rad; },
    get radiusFromCircle() { return this._radius;},

    get area() { return (Math.PI * (this._radius * this._radius));}
};

var cir1 = new Circle(5);

cir1.radiusToCircle(14);
</code>```

What am I missing here?

Thanks in advance.

答:
What you are doing may work, but I don't know the set/get commands you are using and whether or not overloading the function is a good idea.

From the docs, it looks like the set/get will bind a callback that will run some unrelated code when you assign the member variable directly.  If that's what you are trying to do, you don't need a prototype function.

```<code>var Circle = function(radius){
    this._radius = radius;
}

Circle.prototype.getRadiusToCircle = function() {
    return this._radius;
}

Circle.prototype.setRadiusToCircle = function(rad) {
    this._radius = rad;
}

Circle.prototype.overloadRadiusToCircle = function(rad) {
    if(rad != null) {
        this._radius = rad;
    } else {
        return rad;
    }
}

Circle.prototype.area = function() {
    return (Math.PI * (this._radius * this._radius));
}
</code>```

For example

```<code>var Circle = function(radius){
    this._radius = radius;
    this._area = Math.PI * (radius * radius);
}

Circle.prototype = {
    set _radius(radius) {
        this._area = Math.PI * (radius * radius);
    }
}

Circle.prototype.getArea = function() {
    return _area;
}
</code>```

Body:
I am learning Javascript. When I try to use setters with prototyping I am getting an error

TypeError: cir1.radiusToCircle is not a function

var Circle = function(radius){
    this._radius = radius;
}

//prototype

Circle.prototype ={
    set radiusToCircle(rad) { this._radius = rad; },
    get radiusFromCircle() { return this._radius;},

    get area() { return (Math.PI * (this._radius * this._radius));}
};

var cir1 = new Circle(5);

cir1.radiusToCircle(14);

What am I missing here?

Thanks in advance.

Body:
What you are doing may work, but I don't know the set/get commands you are using and whether or not overloading the function is a good idea.

From the docs, it looks like the set/get will bind a callback that will run some unrelated code when you assign the member variable directly.  If that's what you are trying to do, you don't need a prototype function.

var Circle = function(radius){
    this._radius = radius;
}

Circle.prototype.getRadiusToCircle = function() {
    return this._radius;
}

Circle.prototype.setRadiusToCircle = function(rad) {
    this._radius = rad;
}

Circle.prototype.overloadRadiusToCircle = function(rad) {
    if(rad != null) {
        this._radius = rad;
    } else {
        return rad;
    }
}

Circle.prototype.area = function() {
    return (Math.PI * (this._radius * this._radius));
}

For example

var Circle = function(radius){
    this._radius = radius;
    this._area = Math.PI * (radius * radius);
}

Circle.prototype = {
    set _radius(radius) {
        this._area = Math.PI * (radius * radius);
    }
}

Circle.prototype.getArea = function() {
    return _area;
}


问:
Restore Minimized CMD Window
I have a batch script running in a minimized window. How can I conditionally restore the size of the window and bring it to the foreground?</p>

```<code>IF EXIST "temp.txt"  (
    REM How to restore window and bring to foreground?
)
</code>```

答:
You should really give us more information.

I'll try to answer it with the general knowledge:

It does not work like that in cmd.

There is, however, a workaround:
You can use: START "window title" /max script.cmd.

In your example it would be:

```<code>IF EXIST "temp.txt"  (
    START "my max window" /max CMD /C script.cmd
)
</code>```

Cmd /C  .... closes window after execution

OR

Cmd /K. .. leave the window opened after execution

Note: you can always check for more information at start /? when entered on command prompt.

First Edit - I have decided to toss in a simple example for better illustration:

Lets have first file called min_max.cmd:

```<code>@ECHO off

ECHO Hello this is original window.
START "min testing" /min CMD /C message.cmd min
START "max testing" /max CMD /K message.cmd max
</code>```

Then second file would be called message.cmd (both in same directory):

```<code>@ECHO OFF

SET "windows_function=%1"
ECHO " -> %windows_function% <- was executed!"
PAUSE
</code>```

You will see that the minimize window has been minimized, with proper title for easier identification, shows a message and then waits for key press.  After pressing any key the window will disappear.

On the other hand the maximized window, with proper title for easier identification, will too wait for the key press but will not disappear afterwards.

Title: Restore Minimized CMD Window

Body:
I have a batch script running in a minimized window. How can I conditionally restore the size of the window and bring it to the foreground?

IF EXIST "temp.txt"  (
    REM How to restore window and bring to foreground?
)

Body:
You should really give us more information.

I'll try to answer it with the general knowledge:

It does not work like that in cmd.

There is, however, a workaround:
You can use: START "window title" /max script.cmd.

In your example it would be:

IF EXIST "temp.txt"  (
    START "my max window" /max CMD /C script.cmd
)

Cmd /C  .... closes window after execution

OR

Cmd /K. .. leave the window opened after execution

Note: you can always check for more information at start /? when entered on command prompt.

First Edit - I have decided to toss in a simple example for better illustration:

Lets have first file called min_max.cmd:

@ECHO off

ECHO Hello this is original window.
START "min testing" /min CMD /C message.cmd min
START "max testing" /max CMD /K message.cmd max

Then second file would be called message.cmd (both in same directory):

@ECHO OFF

SET "windows_function=%1"
ECHO " -> %windows_function% <- was executed!"
PAUSE

You will see that the minimize window has been minimized, with proper title for easier identification, shows a message and then waits for key press.  After pressing any key the window will disappear.

On the other hand the maximized window, with proper title for easier identification, will too wait for the key press but will not disappear afterwards.


问:
modify a column in pandas data-frame selecting a sub-string
This is my pandas data-frame. I want to modify values of first column (System) by extracting just a,b,c,d. How can this be done in python</p>

```<code> System       mem
/vol/a/        10
/vol/b/        20
/vol/c/        30
/vol/d/        40
</code>```

答:
You can use .str.extract:

```<code>In [11]: df.System.str.extract("/vol/(.*?)/", expand=False)
Out[11]:
0    a
1    b
2    c
3    d
Name: System, dtype: object
</code>```

Body:
This is my pandas data-frame. I want to modify values of first column (System) by extracting just a,b,c,d. How can this be done in python

 System       mem
/vol/a/        10
/vol/b/        20
/vol/c/        30
/vol/d/        40

Body:
You can use .str.extract:

In [11]: df.System.str.extract("/vol/(.*?)/", expand=False)
Out[11]:
0    a
1    b
2    c
3    d
Name: System, dtype: object


问:
Entity Framework 6 doesn't detect inheritance
I have the following class setup

```<code> public abstract class SearchElement
{
    public int Id { get; set; }

    public SearchElement parent { get; set; }

    public int Order { get; set; }

    public UserQuery UserQuery { get; set; }
}

public class SearchGroup : SearchElement
{
    public virtual ICollection<SearchElement> SearchObjects { get; set; }

    public bool IsAndOperator { get; set; }

    public SearchGroup()
    {
        this.SearchObjects = new List<SearchElement>();
    }
}
public abstract class SearchCondition<IContext, OutputType> : SearchElement
{
    public ComparisonTypes Comparison { get; set; }

    public string Value { get; set; }

    public abstract Expression<Func<OutputType, bool>> BuildConditionQuery(IContext context);
}
public class SearchPackage : SearchCondition<ISearchContext, ProjectParticipantQuestionnaireResponseGroup>
{
    public override System.Linq.Expressions.Expression<Func<ProjectParticipantQuestionnaireResponseGroup, bool>> BuildConditionQuery(ISearchContext context)
    {
        return this.BuildCondition<ProjectParticipantQuestionnaireResponseGroup, int>(r => r.Package.Id, int.Parse(this.Value), this.Comparison);
    }
}
</code>```

Now for some reason, when in the EntityFramework context I specify:

```<code>public DbSet<SearchElement> SearchElements { get; set; }
</code>```

The SearchGroup class gets detected and the appropriate fields get created in the SearchElement table. However, the SearchPackage class does not get detected and it's fields are not created in the SearchElement table.

I can of course create a DbSet for the SearchPackage, but there are multiple similar classes (same inheritance, although some with difference  values) and I don't want to create a DbSet for each of them. Does anyone has suggestions about what I can do?

For clarity: I am using Entity Framework 6.1.3 and C# 4.5.1

答:
EF 6 cannot map a CLR generic type. (Sorry, I can't find an authoritative reference on this right now.) This is the problem, not one of inheritance generally. When EF traverses your inheritance "tree," it gets to SearchCondition<,> and gives up.

Finding a way around this will probably require a rethinking of your object model to something more serialization-friendly. Is there a way that you can split your object-model into a set of services (that might contain generics) that interacts with a set of more easily mapped DTOs?

<s>Another (possible, untested) option: Make an ISearchElement mapped interface. SearchPackage should implement it directly. This way, SearchPackage--and other SearchCondition<,> implementors should get "picked up" by EF inheritance traversal.</s>

Body:
I have the following class setup

 public abstract class SearchElement
{
    public int Id { get; set; }

    public SearchElement parent { get; set; }

    public int Order { get; set; }

    public UserQuery UserQuery { get; set; }
}

public class SearchGroup : SearchElement
{
    public virtual ICollection<SearchElement> SearchObjects { get; set; }

    public bool IsAndOperator { get; set; }

    public SearchGroup()
    {
        this.SearchObjects = new List<SearchElement>();
    }
}
public abstract class SearchCondition<IContext, OutputType> : SearchElement
{
    public ComparisonTypes Comparison { get; set; }

    public string Value { get; set; }

    public abstract Expression<Func<OutputType, bool>> BuildConditionQuery(IContext context);
}
public class SearchPackage : SearchCondition<ISearchContext, ProjectParticipantQuestionnaireResponseGroup>
{
    public override System.Linq.Expressions.Expression<Func<ProjectParticipantQuestionnaireResponseGroup, bool>> BuildConditionQuery(ISearchContext context)
    {
        return this.BuildCondition<ProjectParticipantQuestionnaireResponseGroup, int>(r => r.Package.Id, int.Parse(this.Value), this.Comparison);
    }
}

Now for some reason, when in the EntityFramework context I specify:

public DbSet<SearchElement> SearchElements { get; set; }

The SearchGroup class gets detected and the appropriate fields get created in the SearchElement table. However, the SearchPackage class does not get detected and it's fields are not created in the SearchElement table.

I can of course create a DbSet for the SearchPackage, but there are multiple similar classes (same inheritance, although some with difference  values) and I don't want to create a DbSet for each of them. Does anyone has suggestions about what I can do?

For clarity: I am using Entity Framework 6.1.3 and C# 4.5.1


问:
In python How can I parse a JSON string, which has value regex, with slashes(\) without breaking JSON structure?
My application gets a request with regex in its JSON value.

```<code>{ "regex" : "^1\.0(\.\\d+)?$" }
</code>```

I use below code to parse it:

```<code>parsedData = json.loads(requestData)
</code>```

But it fails because of non-JSON characters.

I tried many ways, One of them is this

Bease64 encoding and decoding :

```<code>>>> s = '^1\.0(\.\\d+)?$'
>>> e = base64.b64encode('^1\.0(\.\d+)?$')
>>> e
'XjFcLjAoXC5cZCspPyQ='
>>> d = base64.b64decode(e)
>>> d
'^1\\.0(\\.\\d+)?$'
</code>```

Observe the output - '^1\\.0(\\.\\d+)?$'  : 1 extra slash added.

Clearly now not able to distinguish between the one with 2 slashes and one slashes.

Since the data is regex, I want it in the original format in a variable.

How can I get that?

答:
The issue here is that your json isn't properly encoded, so you're having trouble decoding it.  This is a chicken & egg problem.

```<code>>>> import json
>>> r = r'^1\.0(\.\d+)?$'
>>> print r
^1\.0(\.\d+)?$
>>> print json.dumps(r)
"^1\\.0(\\.\\d+)?$"
</code>```

You need to investigate how the json is being created before it's passed to you (if you're in control there) or reach out to the person generating it.

Body:
My application gets a request with regex in its JSON value.

{ "regex" : "^1\.0(\.\\d+)?$" }

I use below code to parse it:

parsedData = json.loads(requestData)

But it fails because of non-JSON characters.

I tried many ways, One of them is this

Bease64 encoding and decoding :

>>> s = '^1\.0(\.\\d+)?$'
>>> e = base64.b64encode('^1\.0(\.\d+)?$')
>>> e
'XjFcLjAoXC5cZCspPyQ='
>>> d = base64.b64decode(e)
>>> d
'^1\\.0(\\.\\d+)?$'

Observe the output - '^1\\.0(\\.\\d+)?$'  : 1 extra slash added.

Clearly now not able to distinguish between the one with 2 slashes and one slashes.

Since the data is regex, I want it in the original format in a variable.

How can I get that?

Body:
The issue here is that your json isn't properly encoded, so you're having trouble decoding it.  This is a chicken & egg problem.

>>> import json
>>> r = r'^1\.0(\.\d+)?$'
>>> print r
^1\.0(\.\d+)?$
>>> print json.dumps(r)
"^1\\.0(\\.\\d+)?$"

You need to investigate how the json is being created before it's passed to you (if you're in control there) or reach out to the person generating it.