问:
Graph directed and weighted
I have a weighted directed graph, with 10 nodes, which begins with the node a. And the nodes are connected to each other (the specific connection is shown in the code) and the edge shows how likely (probability) it is to go to the next node. If for example the node a is connected to node b and c, and both have the same probability to got to (0.5) the first node in the list should be taken, so here b.

And the user enters the number of times the traversal function should go trough the graph. The return of the traversal function should be the number of times the node e has been accessed.

I already did some of it, if you could help me and tell me how I should access each node and check it if it's the one with the "e" or not, would be great.

```<code>#include <iosrteam>
#include <cstdlib>
#include <vector>
using namespace std;

struct node {
        const char* label;
        vector<float> prob;
        vector<node*> succ;
};

// TODO: implement function traversal

void node_init(node* a, const char label[]) {
    a->label = label;
}

void edge_init(node* a, node* b, float probability) {
    a->succ.push_back(b);
    a->prob.push_back(probability);
}

void init_graph(node* nodes) {
    node_init(nodes, "a");
    node_init(nodes+1, "b ");
    node_init(nodes+2, "c ");
    node_init(nodes+3, "d ");
    node_init(nodes+4, "e ");
    node_init(nodes+5, "f ");
    node_init(nodes+6, "g ");
    node_init(nodes+7, "h ");
    node_init(nodes+8, "i ");
    node_init(nodes+9, "j ");

    edge_init(nodes, nodes+1, 0.5);
    edge_init(nodes, nodes+2, 0.5);
    edge_init(nodes+1, nodes+3, 0.3);
    edge_init(nodes+1, nodes+4, 0.3);
    edge_init(nodes+1, nodes+5, 0.4);
    edge_init(nodes+2, nodes+4, 0.5);
    edge_init(nodes+2, nodes+5, 0.5);
    edge_init(nodes+3, nodes, 1.0);
    edge_init(nodes+4, nodes+6, 0.5);
    edge_init(nodes+4, nodes+7, 0.5);
    edge_init(nodes+5, nodes+6, 0.25);
    edge_init(nodes+5, nodes+7, 0.25);
    edge_init(nodes+5, nodes+8, 0.25);
    edge_init(nodes+5, nodes+9, 0.25);
    edge_init(nodes+6, nodes, 1.0);
    edge_init(nodes+7, nodes, 1.0);
    edge_init(nodes+8, nodes, 1.0);
    edge_init(nodes+9, nodes, 1.0);
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        srand(time(0));
        node *nodes= new node[12];
        init_graph(nodes);
        int fische = traversal(nodes,atoi(argv[1]));
        cout << endl << "Number of e-access: " << e << endl;
        delete [] nodes;
    } else {
        cout << "Call with number of steps for traversal.\n";
    }
    return 0;
}
</code>```

答:
Here is what I figured out, it seems to be working (our tutor told us to sum op the probabilities and to compare it to the randomly generated number, don't ask me why): </p>

```<code>#include <iostream>
#include <cstdlib>
#include <vector>
#include <time.h>

using namespace std;

struct node {
    const char* label;
    vector<float> prob;
    vector<node*> succ;
};

// TODO: implement function traversal

int traversal(node* start, int argv ){
    int e=0;
    int i=0;
    cout<<start->label<<endl;
    if(string(start->label).compare("e ") == 0){
        e++;
    }
    if(argv>0) {
        float summe =0;
        double ran = (double)rand() / RAND_MAX;
        for(int i=0; i<start->prob.size();i++){
            summe = summe + start->prob[i];
            if(summe>ran){
                e =e + traversal(start->succ[i], argv-1);
                break;
            }

        }
    }
    return e;
}

void node_init(node* a, const char label[]) {
    a->label = label;
}

void edge_init(node* a, node* b, float probability) {
    a->succ.push_back(b);
    a->prob.push_back(probability);
}

void init_graph(node* nodes) {
    node_init(nodes, "a ");
    node_init(nodes+1, "b ");
    node_init(nodes+2, "c ");
    node_init(nodes+3, "d ");
    node_init(nodes+4, "e ");
    node_init(nodes+5, "f ");
    node_init(nodes+6, "g ");
    node_init(nodes+7, "h ");
    node_init(nodes+8, "i ");
    node_init(nodes+9, "j ");

    edge_init(nodes, nodes+1, 0.5);
    edge_init(nodes, nodes+2, 0.5);
    edge_init(nodes+1, nodes+3, 0.3);
    edge_init(nodes+1, nodes+4, 0.3);
    edge_init(nodes+1, nodes+5, 0.4);
    edge_init(nodes+2, nodes+4, 0.5);
    edge_init(nodes+2, nodes+5, 0.5);
    edge_init(nodes+3, nodes, 1.0);
    edge_init(nodes+4, nodes+6, 0.5);
    edge_init(nodes+4, nodes+7, 0.5);
    edge_init(nodes+5, nodes+6, 0.25);
    edge_init(nodes+5, nodes+7, 0.25);
    edge_init(nodes+5, nodes+8, 0.25);
    edge_init(nodes+5, nodes+9, 0.25);
    edge_init(nodes+6, nodes, 1.0);
    edge_init(nodes+7, nodes, 1.0);
    edge_init(nodes+8, nodes, 1.0);
    edge_init(nodes+9, nodes, 1.0);
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        srand(time(0));
        node *nodes= new node[12];
        init_graph(nodes);
        int e = traversal(nodes,atoi(argv[1]));
        cout << endl << "Number of e-access: " << e << endl;
        delete [] nodes;
    } else {
        cout << "Call with number of steps for traversal.\n";
    }
    return 0;
}
</code>```

Title: Graph directed and weighted

Body:
I have a weighted directed graph, with 10 nodes, which begins with the node a. And the nodes are connected to each other (the specific connection is shown in the code) and the edge shows how likely (probability) it is to go to the next node. If for example the node a is connected to node b and c, and both have the same probability to got to (0.5) the first node in the list should be taken, so here b.

And the user enters the number of times the traversal function should go trough the graph. The return of the traversal function should be the number of times the node e has been accessed.

I already did some of it, if you could help me and tell me how I should access each node and check it if it's the one with the "e" or not, would be great.

#include <iosrteam>
#include <cstdlib>
#include <vector>
using namespace std;

struct node {
        const char* label;
        vector<float> prob;
        vector<node*> succ;
};

// TODO: implement function traversal

void node_init(node* a, const char label[]) {
    a->label = label;
}

void edge_init(node* a, node* b, float probability) {
    a->succ.push_back(b);
    a->prob.push_back(probability);
}

void init_graph(node* nodes) {
    node_init(nodes, "a");
    node_init(nodes+1, "b ");
    node_init(nodes+2, "c ");
    node_init(nodes+3, "d ");
    node_init(nodes+4, "e ");
    node_init(nodes+5, "f ");
    node_init(nodes+6, "g ");
    node_init(nodes+7, "h ");
    node_init(nodes+8, "i ");
    node_init(nodes+9, "j ");

    edge_init(nodes, nodes+1, 0.5);
    edge_init(nodes, nodes+2, 0.5);
    edge_init(nodes+1, nodes+3, 0.3);
    edge_init(nodes+1, nodes+4, 0.3);
    edge_init(nodes+1, nodes+5, 0.4);
    edge_init(nodes+2, nodes+4, 0.5);
    edge_init(nodes+2, nodes+5, 0.5);
    edge_init(nodes+3, nodes, 1.0);
    edge_init(nodes+4, nodes+6, 0.5);
    edge_init(nodes+4, nodes+7, 0.5);
    edge_init(nodes+5, nodes+6, 0.25);
    edge_init(nodes+5, nodes+7, 0.25);
    edge_init(nodes+5, nodes+8, 0.25);
    edge_init(nodes+5, nodes+9, 0.25);
    edge_init(nodes+6, nodes, 1.0);
    edge_init(nodes+7, nodes, 1.0);
    edge_init(nodes+8, nodes, 1.0);
    edge_init(nodes+9, nodes, 1.0);
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        srand(time(0));
        node *nodes= new node[12];
        init_graph(nodes);
        int fische = traversal(nodes,atoi(argv[1]));
        cout << endl << "Number of e-access: " << e << endl;
        delete [] nodes;
    } else {
        cout << "Call with number of steps for traversal.\n";
    }
    return 0;
}

Body:
Here is what I figured out, it seems to be working (our tutor told us to sum op the probabilities and to compare it to the randomly generated number, don't ask me why):

#include <iostream>
#include <cstdlib>
#include <vector>
#include <time.h>

using namespace std;

struct node {
    const char* label;
    vector<float> prob;
    vector<node*> succ;
};

// TODO: implement function traversal

int traversal(node* start, int argv ){
    int e=0;
    int i=0;
    cout<<start->label<<endl;
    if(string(start->label).compare("e ") == 0){
        e++;
    }
    if(argv>0) {
        float summe =0;
        double ran = (double)rand() / RAND_MAX;
        for(int i=0; i<start->prob.size();i++){
            summe = summe + start->prob[i];
            if(summe>ran){
                e =e + traversal(start->succ[i], argv-1);
                break;
            }

        }
    }
    return e;
}

void node_init(node* a, const char label[]) {
    a->label = label;
}

void edge_init(node* a, node* b, float probability) {
    a->succ.push_back(b);
    a->prob.push_back(probability);
}

void init_graph(node* nodes) {
    node_init(nodes, "a ");
    node_init(nodes+1, "b ");
    node_init(nodes+2, "c ");
    node_init(nodes+3, "d ");
    node_init(nodes+4, "e ");
    node_init(nodes+5, "f ");
    node_init(nodes+6, "g ");
    node_init(nodes+7, "h ");
    node_init(nodes+8, "i ");
    node_init(nodes+9, "j ");

    edge_init(nodes, nodes+1, 0.5);
    edge_init(nodes, nodes+2, 0.5);
    edge_init(nodes+1, nodes+3, 0.3);
    edge_init(nodes+1, nodes+4, 0.3);
    edge_init(nodes+1, nodes+5, 0.4);
    edge_init(nodes+2, nodes+4, 0.5);
    edge_init(nodes+2, nodes+5, 0.5);
    edge_init(nodes+3, nodes, 1.0);
    edge_init(nodes+4, nodes+6, 0.5);
    edge_init(nodes+4, nodes+7, 0.5);
    edge_init(nodes+5, nodes+6, 0.25);
    edge_init(nodes+5, nodes+7, 0.25);
    edge_init(nodes+5, nodes+8, 0.25);
    edge_init(nodes+5, nodes+9, 0.25);
    edge_init(nodes+6, nodes, 1.0);
    edge_init(nodes+7, nodes, 1.0);
    edge_init(nodes+8, nodes, 1.0);
    edge_init(nodes+9, nodes, 1.0);
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        srand(time(0));
        node *nodes= new node[12];
        init_graph(nodes);
        int e = traversal(nodes,atoi(argv[1]));
        cout << endl << "Number of e-access: " << e << endl;
        delete [] nodes;
    } else {
        cout << "Call with number of steps for traversal.\n";
    }
    return 0;
}


来源: stackexchange

问:
spring boot 1.5.4 basic authentication REST API only jsession fails
Am working with spring boot 1.5.4 and have a sringboot server basic authentication application.  The goal of the application is to login in with credentials and use the jsessionID received to verify authorization for each additional REST API calls made.

In my extended WebSecurityConfigurerAdapter class my configure method is:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    log.info("In configure");

    http.authorizeRequests()
            .antMatchers("/user/**").permitAll()
            .anyRequest().authenticated()
        //    .antMatchers("/weather/getAll").hasAnyRole("ROLE_USER","ROLE_ADMIN")
            .and().csrf().disable()
            .logout()
            .deleteCookies("JSESSIONID")
            .permitAll();
}
</code>```

Note: ROLE_USER and ROLE_ADMIN are the granted authoritites I have defined in my user table.  Testing with curl and the following command works:

```<code>>curl -i -d "user=test1&password=test2" http://localhost:8080/user/login -c t1.txt
</code>```

that is a 200 ok is returned along with a JSessionID.  I then attemt a call to get a specific weather record using curl as follows:

curl -i -v   http://localhost:8080/weather/get/760 -b t1.txt
  Curl's output shows the JSessionID received on login being passed to the server application.  Always get a 403 status message returned.  The weather get method is as follows:

```<code> @PreAuthorize("isAuthenticated()")
@GetMapping("get/{id}")
@JsonIgnore

public ResponseEntity<Weather> get(@PathVariable("id") Integer id){
    Weather weatherData = null;
    log.info("IN weatherTable get ");
    try{
        weatherData =  _weatherDao.getWeatherById(id);
    }catch(Exception e){
        System.out.println("get Exception = "+e.getMessage());
        return null;
    }
    return new ResponseEntity<Weather>(weatherData, HttpStatus.OK);
}
</code>```

Reduced the complexity of the configure overridden method to try and troubleshoot the cause. Removing the Preauthorize annotation from the get method does return the expected record, so the backing code is correct.

Can't seem to find information/documentation that helps explain why the JSessionID value from login is not working for the authorization check.  Are there other steps needed?  Any debugging hints would be very appreciated.

EDIT
added this bit of code to help debug the issue:

```<code>// @PreAuthorize("hasRole('ROLE_USER')")
    @RequestMapping(value="/getAll")
    @JsonIgnore
    public  ResponseEntity<List<Weather>> getAll(){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> ga = auth.getAuthorities();
        for (GrantedAuthority granted : ga){
            log.info("AUTHORITY = "+granted.getAuthority());
        }
        List<Weather> weatherData = null;
        try{
            weatherData = _weatherDao.getAll();
        }catch(Exception e){
            System.out.println("getAll Exception = "+e.getMessage());
        }
        return new ResponseEntity<List<Weather>>(weatherData,HttpStatus.OK);
    }
</code>```

I opened up the permissions for /weather/** to permitAll() and tested with a login for a user with ROLE_USER.  Then called /weather/getAll using the cookie returned via curl (see above).  The log shows that the granted authority for this call is "ROLE_ANONYMOUS".

Looks like I'm missing something to allow the jsessionid to be tracked.

答:
Have you tried removing ROLE_ from the authorization rule?

Spring Security 4 automatically prefixes any role with ROLE_.

Seems to me that when Spring Security tries to match your role it finds nothing and you get this 403 error.

EDIT

Just to make it clear, my suggestion is to leave your configuration rule like this:

```<code>antMatchers("/weather/getAll").hasAnyRole("USER","ADMIN")
</code>```

And keep your data in database like you have it now.

EDIT2:

There's a difference between hasAnyRole and hasAnyAuthority. Quoting from this blog:

Roles and authorities are similar in Spring.

The main difference is that, roles have special semantics – starting with Spring Security 4, the ‘ROLE_‘ prefix is automatically added (if it’s not already there) by any role related method.

So hasAuthority(‘ROLE_ADMIN’) is similar to hasRole(‘ADMIN’) because the ‘ROLE_‘ prefix gets added automatically.

That's why I asked you to remove the ROLE_ prefix from your rule.

EDIT 3:

Now I saw that your request is http://localhost:8080/weather/get/760

So your rule should be like this:

.antMatchers("/weather/get/**").hasAnyAuthority("ROLE_USER","ROLE_ADMIN")

ContentLicense: CC BY-SA 3.0

Body:
Am working with spring boot 1.5.4 and have a sringboot server basic authentication application.  The goal of the application is to login in with credentials and use the jsessionID received to verify authorization for each additional REST API calls made.

In my extended WebSecurityConfigurerAdapter class my configure method is:

@Override
protected void configure(HttpSecurity http) throws Exception {
    log.info("In configure");

    http.authorizeRequests()
            .antMatchers("/user/**").permitAll()
            .anyRequest().authenticated()
        //    .antMatchers("/weather/getAll").hasAnyRole("ROLE_USER","ROLE_ADMIN")
            .and().csrf().disable()
            .logout()
            .deleteCookies("JSESSIONID")
            .permitAll();
}

Note: ROLE_USER and ROLE_ADMIN are the granted authoritites I have defined in my user table.  Testing with curl and the following command works:

>curl -i -d "user=test1&password=test2" http://localhost:8080/user/login -c t1.txt

that is a 200 ok is returned along with a JSessionID.  I then attemt a call to get a specific weather record using curl as follows:

curl -i -v   http://localhost:8080/weather/get/760 -b t1.txt
  Curl's output shows the JSessionID received on login being passed to the server application.  Always get a 403 status message returned.  The weather get method is as follows:

 @PreAuthorize("isAuthenticated()")
@GetMapping("get/{id}")
@JsonIgnore

public ResponseEntity<Weather> get(@PathVariable("id") Integer id){
    Weather weatherData = null;
    log.info("IN weatherTable get ");
    try{
        weatherData =  _weatherDao.getWeatherById(id);
    }catch(Exception e){
        System.out.println("get Exception = "+e.getMessage());
        return null;
    }
    return new ResponseEntity<Weather>(weatherData, HttpStatus.OK);
}

Reduced the complexity of the configure overridden method to try and troubleshoot the cause. Removing the Preauthorize annotation from the get method does return the expected record, so the backing code is correct.

Can't seem to find information/documentation that helps explain why the JSessionID value from login is not working for the authorization check.  Are there other steps needed?  Any debugging hints would be very appreciated.

EDIT
added this bit of code to help debug the issue:

// @PreAuthorize("hasRole('ROLE_USER')")
    @RequestMapping(value="/getAll")
    @JsonIgnore
    public  ResponseEntity<List<Weather>> getAll(){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> ga = auth.getAuthorities();
        for (GrantedAuthority granted : ga){
            log.info("AUTHORITY = "+granted.getAuthority());
        }
        List<Weather> weatherData = null;
        try{
            weatherData = _weatherDao.getAll();
        }catch(Exception e){
            System.out.println("getAll Exception = "+e.getMessage());
        }
        return new ResponseEntity<List<Weather>>(weatherData,HttpStatus.OK);
    }

I opened up the permissions for /weather/** to permitAll() and tested with a login for a user with ROLE_USER.  Then called /weather/getAll using the cookie returned via curl (see above).  The log shows that the granted authority for this call is "ROLE_ANONYMOUS".

Looks like I'm missing something to allow the jsessionid to be tracked.

Body:
Have you tried removing ROLE_ from the authorization rule?

Spring Security 4 automatically prefixes any role with ROLE_.

Seems to me that when Spring Security tries to match your role it finds nothing and you get this 403 error.

EDIT

Just to make it clear, my suggestion is to leave your configuration rule like this:

antMatchers("/weather/getAll").hasAnyRole("USER","ADMIN")

And keep your data in database like you have it now.

EDIT2:

There's a difference between hasAnyRole and hasAnyAuthority. Quoting from this blog:

Roles and authorities are similar in Spring.

The main difference is that, roles have special semantics – starting with Spring Security 4, the ‘ROLE_‘ prefix is automatically added (if it’s not already there) by any role related method.

So hasAuthority(‘ROLE_ADMIN’) is similar to hasRole(‘ADMIN’) because the ‘ROLE_‘ prefix gets added automatically.

That's why I asked you to remove the ROLE_ prefix from your rule.

EDIT 3:

Now I saw that your request is http://localhost:8080/weather/get/760

So your rule should be like this:

.antMatchers("/weather/get/**").hasAnyAuthority("ROLE_USER","ROLE_ADMIN")


问:
System.Windows.Forms.Timer performance
We have an application containing a lot of user controls that update frequently based on a System.Windows.Forms.Timer. Am I safe to add a Timer instance to each control peformancewise? Or should I have one Singleton Timer that runs all the time that is to be used by all instances? What is acutally happening under the hood? Will there be a an additional thread (for counting) for each timer?</p>

答:
Do the timers fire at different times for each control? Do they each need a seperate timer?

Remember you can hook up several event handlers to a single event, so if you're using the timers to do some simple animation, you could perhaps do that with one timer firing events for many controls...

OwnerDisplayName: bitbonk

ContentLicense: CC BY-SA 2.5

Title: System.Windows.Forms.Timer performance

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Arjan Einbu


问:
Python- Remove all words that contain other words in a list
I have a list populated with words from a dictionary.  I want to find a way to remove all words, only considering root words that form at the beginning of the target word.

For example, the word "rodeo" would be removed from the list because it contains the English-valid word "rode."  "Typewriter" would be removed because it contains the English-valid word "type."  However, the word "snicker" is still valid even if it contains the word "nick" because "nick" is in the middle and not at the beginning of the word.

I was thinking something like this:

```<code> for line in wordlist:
        if line.find(...) --
</code>```

but I want that "if" statement to then run through every single word in the list checking to see if its found and, if so, remove itself from the list so that only root words remain.  Do I have to create a copy of wordlist to traverse?

答:
I don't want to provide an exact solution, but I think there are two key functions in Python that will help you greatly here.

The first, jkerian mentioned: string.startswith() http://docs.python.org/library/stdtypes.html#str.startswith

The second: filter() http://docs.python.org/library/functions.html#filter

With filter, you could write a conditional function that will check to see if a word is the base of another word and return true if so.

For each word in the list, you would need to iterate over all of the other words and evaluate the conditional using filter, which could return the proper subset of root words.

Body:
I have a list populated with words from a dictionary.  I want to find a way to remove all words, only considering root words that form at the beginning of the target word.

For example, the word "rodeo" would be removed from the list because it contains the English-valid word "rode."  "Typewriter" would be removed because it contains the English-valid word "type."  However, the word "snicker" is still valid even if it contains the word "nick" because "nick" is in the middle and not at the beginning of the word.

I was thinking something like this:

 for line in wordlist:
        if line.find(...) --

but I want that "if" statement to then run through every single word in the list checking to see if its found and, if so, remove itself from the list so that only root words remain.  Do I have to create a copy of wordlist to traverse?


问:
Cant get loop working in ASSEMBLY x64 nasm
Can someone please explain what's up with this code? I thought I understood this, but apparently I don't.

```<code>    global main
    extern printf
    extern scanf

section .data

numberFormat:   db '%d', 10, 0

section .text

  main:

    push rbp
    mov r8, 2

  loop:

    add r8, 1
    mov rdi, numberFormat
    mov rsi, r8
    mov rax, 0
    call printf

    cmp r8, 15
    jl loop

    mov rax, 0      ; normal exit
    ret
</code>```

my question is, why does this print out only number 3 instead of all numbers between 3 and 15

答: Because r8 is a volatile register (caller saved) and it is being overwritten by printf. You could use RBX, RBP, R12–R15 which are preserved across a function call. – Michael Petch</p>

Body:
Can someone please explain what's up with this code? I thought I understood this, but apparently I don't.

    global main
    extern printf
    extern scanf

section .data

numberFormat:   db '%d', 10, 0

section .text

  main:

    push rbp
    mov r8, 2

  loop:

    add r8, 1
    mov rdi, numberFormat
    mov rsi, r8
    mov rax, 0
    call printf

    cmp r8, 15
    jl loop

    mov rax, 0      ; normal exit
    ret

my question is, why does this print out only number 3 instead of all numbers between 3 and 15


问:
Use component props in onClick redux-thunk dispatch React-Redux
Trying to use props from <button> of component in the dispatch of a redux-thunk function that has been set up for Async process but I can't quite get how to use both props and the function (that's being connected to the component through react-redux connect in the mapDispatchToProps) but I just can't figure out how to call both the props and the function.

```<code>function loadData(dispatch, medium) {
    console.log(dispatch)
    return dispatch({type: 'LOADING_COMPONENT'})

  return axios.get(`/professionals/${medium}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}

const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick : () => dispatch(loadData()),
  }
}

const LoginButtons = ({props, LogInClick}) => (
    <button onClick={() => LogInClick(props.medium)} type="button">{props.buttonName}</button>
)

const LoginConnect = connect(null, mapDispatchToProps)(LoginButtons)
</code>```

And Then I export that and try to call it so it can be reused in the render file like

```<code><LoginConnect medium='suhhhh' buttonName='To log in to suhhh'/>
</code>```

答:
```<code>function loadData(dispatch, medium) {
    console.log(dispatch)
    return dispatch({type: 'LOADING_COMPONENT'})

  return axios.get(`/professionals/${medium}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}

const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick : () => dispatch(loadData()),
  }
}

const LoginButtons = ({medium, buttonName, LogInClick}) => (
    <button onClick={() => LogInClick(medium)} type="button">{buttonName}</button>
)

const LoginConnect = connect(null, mapDispatchToProps)(LoginButtons)
</code>```

This should work !! actually connect merges mapStateToProps, mapDispatchToProps into this.props. Read this documenation for better understanding https://github.com/reactjs/react-redux/blob/master/docs/api.md

Body:
Trying to use props from <button> of component in the dispatch of a redux-thunk function that has been set up for Async process but I can't quite get how to use both props and the function (that's being connected to the component through react-redux connect in the mapDispatchToProps) but I just can't figure out how to call both the props and the function.

function loadData(dispatch, medium) {
    console.log(dispatch)
    return dispatch({type: 'LOADING_COMPONENT'})

  return axios.get(`/professionals/${medium}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}

const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick : () => dispatch(loadData()),
  }
}

const LoginButtons = ({props, LogInClick}) => (
    <button onClick={() => LogInClick(props.medium)} type="button">{props.buttonName}</button>
)

const LoginConnect = connect(null, mapDispatchToProps)(LoginButtons)

And Then I export that and try to call it so it can be reused in the render file like

<LoginConnect medium='suhhhh' buttonName='To log in to suhhh'/>

Body:
function loadData(dispatch, medium) {
    console.log(dispatch)
    return dispatch({type: 'LOADING_COMPONENT'})

  return axios.get(`/professionals/${medium}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}

const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick : () => dispatch(loadData()),
  }
}

const LoginButtons = ({medium, buttonName, LogInClick}) => (
    <button onClick={() => LogInClick(medium)} type="button">{buttonName}</button>
)

const LoginConnect = connect(null, mapDispatchToProps)(LoginButtons)

This should work !! actually connect merges mapStateToProps, mapDispatchToProps into this.props. Read this documenation for better understanding https://github.com/reactjs/react-redux/blob/master/docs/api.md


问:
How to store different types of methods in a dictionary from different classes in C#

I'm building a windows app to be able to read a txt file that contains a lot of markup that explains what kind of information is provided. The markup used looks like "#FLAG xxx" where xxx is the information that is retrieved. The information is handled differently depending on the markup used and therefore I need different methods to extract it.

In my program I use a Dictionary to store all possible variations of markup that can be in the file can contain, and then I read every row in the file and compare if there is a hit in the Dictionary. As it is now, I hardcode what method to call but feel it must be a stupid way to solve this. I load everything contained in the Dictionaryn from another class (Settings), which means I can not access the methods I put in my first class (Form1).

I know I'm doing a lot of mistakes here, but I'm really new to C# and can't do a better solution myself. How would a better practise be to solve this problem. I don't want to write lots of if-statements if I don't need to.

The code below is a downward version of what I have written. Othervise it will be to messy to read. And yes, I removed the Excel-export part but hopefylly you can see what I'm trying to do anyway.

Forms1.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace MarkupReader
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    OpenFileDialog ofd = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "File (*.txt)|*.txt|All files (*.*)|*.*";

        ofd.Title = "Open file";
        ofd.Multiselect = false;

        if (ofd.ShowDialog() == DialogResult.OK)
        {

            StreamReader readFile = new StreamReader(File.OpenRead(ofd.FileName), Encoding.GetEncoding(437));
            ExportFile(readFile);
            readFile.Dispose();
        }
    }

    private void ExportFile(StreamReader readFile)
    {
        Dictionary<string, Tuple<string, int, string>> markup = new Dictionary<string, Tuple<string, int, string>>();

        readFile.DiscardBufferedData();
        readFile.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);

        Settings settings = new Settings();
        settings.SetMarkup(markup);

        string fileMarkup = "";
        string fileMarkupValues = "";
        string line = "";

        while (line != null)
        {
            line = readFile.ReadLine();
            if (line != null)
            {
                //Get markup
                fileMarkup = line.Trim().Split(' ').First();
                fileMarkupValues = line.Replace(fileMarkup, "");

                if (markup.ContainsKey(fileMarkup))
                {
                    /* markupItemX = X is content
                     * Item1 = User flag
                     * Item2 = Export to worksheet number
                     * Item3 = Extract method to call
                     * Item4 =
                     */

                    //Export to excel sheet 1
                    if (markup[fileMarkup].Item2 == 1)
                    {
                        if (markup[fileMarkup].Item3 == "extractDataOne") ExtractMethodOne(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataTwo") ExtractMethodTwo(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataThree") ExtractMethodThree(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFour") ExtractMethodFour(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFive") ExtractMethodFive(fileMarkupValues);
                    }
                    //Export to excel sheet 2
                    if (markup[fileMarkup].Item2 == 2)
                    {
                        if (markup[fileMarkup].Item3 == "extractDataOne") ExtractMethodOne(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataTwo") ExtractMethodTwo(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataThree") ExtractMethodThree(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFour") ExtractMethodFour(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFive") ExtractMethodFive(fileMarkupValues);
                    }
                }
            }
        }
    }

    public void ExtractMethodOne(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodTwo(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodThree(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodFour(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodFive(string markupData)
    {
        //Extract stuff and write to Excel
    }

}
}
</code>```

Setting.cs (it really contains alot more, this is just a example)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkupReader
{
class Settings
{
    public void SetMarkup(Dictionary<string, Tuple<string, int, string>> markup)
    {
        int workSheet = 1;
        markup.Add("#FLAG", new Tuple<string, int, string>("User flag", workSheet, "extractDataOne"));
        markup.Add("#FORMAT", new Tuple<string, int, string>("User format", workSheet, "extractDataOne"));
        markup.Add("#TYPE", new Tuple<string, int, string>("User type", workSheet, "extractDataOne"));
    }
}
}
</code>```

答:
extract from a current project of mine

```<code>private static Dictionary<string, Func<DataObj, string>> s_FormulaMap =
new Dictionary<string, Func<DataObj>, string>> {
    { "home", d=>GetHome(d) },
    { "shell", d=>MakeupShell(d) },
    { "user", d=>d.Get("User") }
};
</code>```

thss maps literals to Func's. The funcs take a DataObj and return a string.
Then do

```<code> var func = s_FormulaMap[keyWord];
            val = func(de);
</code>```

Body:
I'm building a windows app to be able to read a txt file that contains a lot of markup that explains what kind of information is provided. The markup used looks like "#FLAG xxx" where xxx is the information that is retrieved. The information is handled differently depending on the markup used and therefore I need different methods to extract it.

In my program I use a Dictionary to store all possible variations of markup that can be in the file can contain, and then I read every row in the file and compare if there is a hit in the Dictionary. As it is now, I hardcode what method to call but feel it must be a stupid way to solve this. I load everything contained in the Dictionaryn from another class (Settings), which means I can not access the methods I put in my first class (Form1).

I know I'm doing a lot of mistakes here, but I'm really new to C# and can't do a better solution myself. How would a better practise be to solve this problem. I don't want to write lots of if-statements if I don't need to.

The code below is a downward version of what I have written. Othervise it will be to messy to read. And yes, I removed the Excel-export part but hopefylly you can see what I'm trying to do anyway.

Forms1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace MarkupReader
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    OpenFileDialog ofd = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "File (*.txt)|*.txt|All files (*.*)|*.*";

        ofd.Title = "Open file";
        ofd.Multiselect = false;

        if (ofd.ShowDialog() == DialogResult.OK)
        {

            StreamReader readFile = new StreamReader(File.OpenRead(ofd.FileName), Encoding.GetEncoding(437));
            ExportFile(readFile);
            readFile.Dispose();
        }
    }

    private void ExportFile(StreamReader readFile)
    {
        Dictionary<string, Tuple<string, int, string>> markup = new Dictionary<string, Tuple<string, int, string>>();

        readFile.DiscardBufferedData();
        readFile.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);

        Settings settings = new Settings();
        settings.SetMarkup(markup);

        string fileMarkup = "";
        string fileMarkupValues = "";
        string line = "";

        while (line != null)
        {
            line = readFile.ReadLine();
            if (line != null)
            {
                //Get markup
                fileMarkup = line.Trim().Split(' ').First();
                fileMarkupValues = line.Replace(fileMarkup, "");

                if (markup.ContainsKey(fileMarkup))
                {
                    /* markupItemX = X is content
                     * Item1 = User flag
                     * Item2 = Export to worksheet number
                     * Item3 = Extract method to call
                     * Item4 =
                     */

                    //Export to excel sheet 1
                    if (markup[fileMarkup].Item2 == 1)
                    {
                        if (markup[fileMarkup].Item3 == "extractDataOne") ExtractMethodOne(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataTwo") ExtractMethodTwo(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataThree") ExtractMethodThree(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFour") ExtractMethodFour(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFive") ExtractMethodFive(fileMarkupValues);
                    }
                    //Export to excel sheet 2
                    if (markup[fileMarkup].Item2 == 2)
                    {
                        if (markup[fileMarkup].Item3 == "extractDataOne") ExtractMethodOne(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataTwo") ExtractMethodTwo(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataThree") ExtractMethodThree(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFour") ExtractMethodFour(fileMarkupValues);
                        if (markup[fileMarkup].Item3 == "extractDataFive") ExtractMethodFive(fileMarkupValues);
                    }
                }
            }
        }
    }

    public void ExtractMethodOne(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodTwo(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodThree(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodFour(string markupData)
    {
        //Extract stuff and write to Excel
    }

    public void ExtractMethodFive(string markupData)
    {
        //Extract stuff and write to Excel
    }

}
}

Setting.cs (it really contains alot more, this is just a example)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkupReader
{
class Settings
{
    public void SetMarkup(Dictionary<string, Tuple<string, int, string>> markup)
    {
        int workSheet = 1;
        markup.Add("#FLAG", new Tuple<string, int, string>("User flag", workSheet, "extractDataOne"));
        markup.Add("#FORMAT", new Tuple<string, int, string>("User format", workSheet, "extractDataOne"));
        markup.Add("#TYPE", new Tuple<string, int, string>("User type", workSheet, "extractDataOne"));
    }
}
}

Body:
extract from a current project of mine

private static Dictionary<string, Func<DataObj, string>> s_FormulaMap =
new Dictionary<string, Func<DataObj>, string>> {
    { "home", d=>GetHome(d) },
    { "shell", d=>MakeupShell(d) },
    { "user", d=>d.Get("User") }
};

thss maps literals to Func's. The funcs take a DataObj and return a string.
Then do

 var func = s_FormulaMap[keyWord];
            val = func(de);


问:
Swapping two variable value without using third variable
One of the very tricky questions asked in an interview.

Swap the values of two variables like a=10 and b=15.

Generally to swap two variables values, we need 3rd variable like:

```<code>temp=a;
a=b;
b=temp;
</code>```

Now the requirement is, swap values of two variables without using 3rd variable.

答:
```<code>#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
cout<<"\n==========Vikas==========";
cout<<"\n\nEnter the two no=:";
cin>>a>>b;
cout<<"\na"<<a<<"\nb"<<b;
a=a+b;
b=a-b;
a=a-b;

cout<<"\n\na="<<a<<"\nb="<<b;
getch();
}
</code>```

Body:
One of the very tricky questions asked in an interview.

Swap the values of two variables like a=10 and b=15.

Generally to swap two variables values, we need 3rd variable like:

temp=a;
a=b;
b=temp;

Now the requirement is, swap values of two variables without using 3rd variable.


问:
Streaming using camel JMS
I have a application which places message in JMS Queue.The message size can be upto 150 mb. JMS message contains byte array data with additional metadata as xml,once the message is placed in queue the camel route application picks the message and calls the external java api with the message.i would like to stream the message from the JMS Queue using camel jms component.
Can you please tell me if i can achieve it using camel.
Currently i am facing heap error issue.

Sample JMS message is as below.

```<code><request>
    <esb-metadata>
        <source-transaction-id>1234567890</source-transaction-id>
        <environment>Dev</environment>
        <message-type>REQ</message-type>
        <source-id>12345678</source-id>
        <master-id>mst-id1234</master-id>
    </esb-metadata>
    <message-body>
        <parameters>
            <info>
                <document-class>Document</document-class>

                <document-guid>idd_C0A5DF59-0000-C51C-BCDA-E76E9476D5C2</document-guid>
            </info>
        </parameters>
        <document>
            <document-mime-type>std/text</document-mime-type>
            <document-content>SGVhZGluZzEgQ2hhbmdlZCB0b2RheSBKYW4gMTEgc2FtcGxlIHRleHQgYmVsb3csDQpPbmNlIEkg
cmVjZWl2ZSB0aGlzIGluZm9ybWF0aW9uLCBJIHdpbGwgdGhlbiBjb250YWN0IHlvdSBpbW1lZGlh
dGVseSB0byBkaXNjdXNzIHRoZSByZXNvbHV0aW9uIG9mIHlvdXIgY2xhaW0uDQoNCg0KSGVhZGlu
ZzIgc2FtcGxlIHRleHQsDQpJZiBwb3NzaWJsZSwgSSBuZWVkIHRvIHJlY2VpdmUgdGhpcyBpbmZv
cm1hdGlvbiBmcm9tIHlvdSB3aXRoaW4gMzAgRGF5cy4NCg0KMQkxCTENCjIJMgkyDQozCTMJMw0K
NAk0CTQNCg0KSGVhZGluZzMgc2FtcGxlIHRleHQsDQpJIHdpbGwgYXNzdW1lIHlvdSBkbyBub3Qg
d2lzaCB0byBwdXJzdWUgdGhpcyBjbGFpbSBhbmQgSSB3aWxsIGNsb3NlIG15IGZpbGUuDQpBRERF
RCBUSElTIE5FVyBMSU5FIFRPIFNFRSBJRiBJVCBJUyBWSVNJQkxFDQoNCnRhYmxlIHN0YXJ0cyBo
ZXJlDQpwb2xpY3kgbnVtYmVyCWNsYWltIG51bWJlcglpbnN1cmVkDQpwMTIzCWMxMjMJYm9zY2gN
CnAzMjEJYzMyMQlibXcNCnRhYmxlIGVuZHMgaGVyZQ0KDQomIzk2Nzk7CUJ1bGxldCBwb2ludCAx
DQomIzk2Nzk7CUJ1bGxldCBwb2ludCAyDQomIzk2Nzk7CUJ1bGxldCBwb2ludCAzDQoNCjEuCU51
bWJlcmVkIHBvaW50IDENCjIuCU51bWJlcmVkIHBvaW50IDINCjMuCU51bWJlcmVkIHBvaW50IDMN
Cg==        </document-content>
        </document>
    </message-body>
</request>
</code>```

答: HornetQ has support for streaming large messages so that clients don't have to worry about hitting memory limits.  This support works in the HornetQ JMS implementation, but the JMS API doesn't directly support streaming large messages so a standard JMS component (e.g. one that Camel provides) likely won't work for this use-case.  You'd need to use a component written to support the HornetQ implementation specifically.  You can read about how HornetQ JMS clients can stream large messages in the documentation.</p>

ContentLicense: CC BY-SA 4.0

Title: Streaming using camel JMS

Body:
I have a application which places message in JMS Queue.The message size can be upto 150 mb. JMS message contains byte array data with additional metadata as xml,once the message is placed in queue the camel route application picks the message and calls the external java api with the message.i would like to stream the message from the JMS Queue using camel jms component.
Can you please tell me if i can achieve it using camel.
Currently i am facing heap error issue.

Sample JMS message is as below.

<request>
    <esb-metadata>
        <source-transaction-id>1234567890</source-transaction-id>
        <environment>Dev</environment>
        <message-type>REQ</message-type>
        <source-id>12345678</source-id>
        <master-id>mst-id1234</master-id>
    </esb-metadata>
    <message-body>
        <parameters>
            <info>
                <document-class>Document</document-class>

                <document-guid>idd_C0A5DF59-0000-C51C-BCDA-E76E9476D5C2</document-guid>
            </info>
        </parameters>
        <document>
            <document-mime-type>std/text</document-mime-type>
            <document-content>SGVhZGluZzEgQ2hhbmdlZCB0b2RheSBKYW4gMTEgc2FtcGxlIHRleHQgYmVsb3csDQpPbmNlIEkg
cmVjZWl2ZSB0aGlzIGluZm9ybWF0aW9uLCBJIHdpbGwgdGhlbiBjb250YWN0IHlvdSBpbW1lZGlh
dGVseSB0byBkaXNjdXNzIHRoZSByZXNvbHV0aW9uIG9mIHlvdXIgY2xhaW0uDQoNCg0KSGVhZGlu
ZzIgc2FtcGxlIHRleHQsDQpJZiBwb3NzaWJsZSwgSSBuZWVkIHRvIHJlY2VpdmUgdGhpcyBpbmZv
cm1hdGlvbiBmcm9tIHlvdSB3aXRoaW4gMzAgRGF5cy4NCg0KMQkxCTENCjIJMgkyDQozCTMJMw0K
NAk0CTQNCg0KSGVhZGluZzMgc2FtcGxlIHRleHQsDQpJIHdpbGwgYXNzdW1lIHlvdSBkbyBub3Qg
d2lzaCB0byBwdXJzdWUgdGhpcyBjbGFpbSBhbmQgSSB3aWxsIGNsb3NlIG15IGZpbGUuDQpBRERF
RCBUSElTIE5FVyBMSU5FIFRPIFNFRSBJRiBJVCBJUyBWSVNJQkxFDQoNCnRhYmxlIHN0YXJ0cyBo
ZXJlDQpwb2xpY3kgbnVtYmVyCWNsYWltIG51bWJlcglpbnN1cmVkDQpwMTIzCWMxMjMJYm9zY2gN
CnAzMjEJYzMyMQlibXcNCnRhYmxlIGVuZHMgaGVyZQ0KDQomIzk2Nzk7CUJ1bGxldCBwb2ludCAx
DQomIzk2Nzk7CUJ1bGxldCBwb2ludCAyDQomIzk2Nzk7CUJ1bGxldCBwb2ludCAzDQoNCjEuCU51
bWJlcmVkIHBvaW50IDENCjIuCU51bWJlcmVkIHBvaW50IDINCjMuCU51bWJlcmVkIHBvaW50IDMN
Cg==        </document-content>
        </document>
    </message-body>
</request>


问:
How to get number of neurons in TensorFlow layer?
Suppose I am trying to connect the output of a pooling layer to a dense layer. In order to do this, I need to flatten the pooled tensor. Consider the layers below:

```<code>def conv_layer(input, in_channels, out_channels, name="conv"):
    w = tf.get_variable("W", initializer=tf.truncated_normal([3, 3, in_channels, out_channels], stddev=0.1))
    b = tf.get_variable("B", initializer=tf.constant(0.1, shape=[out_channels]))
    conv = tf.nn.conv2d(input, w, strides=[1,1,1,1], padding="SAME")
    act = tf.nn.relu(conv + b)
    return act

def pool_layer(input, name="pool"):
    pool = tf.nn.max_pool(input, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")
    return pool

def dense_layer(input, size_in, size_out, name="dense"):
    w = tf.get_variable("W", initializer=tf.truncated_normal([size_in, size_out], stddev=0.1))
    b = tf.get_variable("B", initializer=tf.constant(0.1, shape=[size_out]))
    act = tf.nn.relu(tf.matmul(input, w) + b)
    return act
</code>```

I am using them to create a network:

```<code>def cnn_model(x):
    x_image = tf.reshape(x, [-1, nseries, present_window, 1])
    conv1 = conv_layer(x_image, 1, 32, "conv1")
    pool1 = pool_layer(conv1, "pool1")
    conv2 = conv_layer(pool1, 32, 64, "conv2")
    pool2 = pool_layer(conv2, "pool2")
    nflat = 17*15*64 # hard-coded
    flat  = tf.reshape(pool2, [-1, nflat])
    yhat = dense_layer(flat, nflat, future_window, "dense1")
    return yhat
</code>```

As you can see I am hard-coding the variable nflat. How to avoid this?

答:
If it's a tensor pool.get_shape() should work on Keras or Tensorflow.

This will actually return a tuple with the size of each dimension, so you need to choose from it, probably it's the 2nd in your case.

If input is actually your input (without any other layer), why are you max-pooling? aren't you looking for dropout ?

Indeed you will find a problem if your batch size is variable, since there's no way of telling the model the size of the reshape

Body:
Suppose I am trying to connect the output of a pooling layer to a dense layer. In order to do this, I need to flatten the pooled tensor. Consider the layers below:

def conv_layer(input, in_channels, out_channels, name="conv"):
    w = tf.get_variable("W", initializer=tf.truncated_normal([3, 3, in_channels, out_channels], stddev=0.1))
    b = tf.get_variable("B", initializer=tf.constant(0.1, shape=[out_channels]))
    conv = tf.nn.conv2d(input, w, strides=[1,1,1,1], padding="SAME")
    act = tf.nn.relu(conv + b)
    return act

def pool_layer(input, name="pool"):
    pool = tf.nn.max_pool(input, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")
    return pool

def dense_layer(input, size_in, size_out, name="dense"):
    w = tf.get_variable("W", initializer=tf.truncated_normal([size_in, size_out], stddev=0.1))
    b = tf.get_variable("B", initializer=tf.constant(0.1, shape=[size_out]))
    act = tf.nn.relu(tf.matmul(input, w) + b)
    return act

I am using them to create a network:

def cnn_model(x):
    x_image = tf.reshape(x, [-1, nseries, present_window, 1])
    conv1 = conv_layer(x_image, 1, 32, "conv1")
    pool1 = pool_layer(conv1, "pool1")
    conv2 = conv_layer(pool1, 32, 64, "conv2")
    pool2 = pool_layer(conv2, "pool2")
    nflat = 17*15*64 # hard-coded
    flat  = tf.reshape(pool2, [-1, nflat])
    yhat = dense_layer(flat, nflat, future_window, "dense1")
    return yhat

As you can see I am hard-coding the variable nflat. How to avoid this?


问:
create tutorial mode
I have a Qt application and want to show a little tutorial when the user access the application for the first time. Something like this:

How can I do something like this on Qt?

I'm using Qt 5.4 on Windows.

答:
There is nothing that will be of help to do this out of the box.

You can have an overlay widget that is normally hidden and only shows up during "tutorial" mode. You can easily punch a hole by using a QPainterPath to which you first add the rectangle of the entire widget and then add a circle where you want the hole, and then fill the resulting path.

You can get the absolute position of gui elements by mapping to the tutorial overlay widget.

I suggest you implement an abstract Tutorial class or at least a basic list of pointer/text pairs you implement for each widget you want to have a tutorial, then register each element of that widget in the tutorial - pointer to the gui element and the tutorial text. Then, when the tutorial for that widget is invoked, the overlay widget becomes visible and allows to iterate the particular elements of a widget that have information associated with them and redraw on iteration to show the circle and text.

Title: create tutorial mode


问:
Start Recording for Microsoft Coded UI Test 2017 is not selectable
I am just begining to learn about Coded UI test. Since it is still 2017, I figure Visual Studio 2017 is the best version I can try. Having a Visual Studio Enterprise license I decided to try it out. Turns out I have it installed even. Great. There are lots of tutorials that all seem to start the same way:

Start a new coded UI test builder project in Visual Studio.

generate coded ui test using test builder.

When the test builder pops up, most of the buttons on the tool including the record button are not selectable. There must be a configuration issue or a problem with my proceedure. What could be going wrong?

答:
It is possible that there are other answers to this question, but one resolution to the issue seems to be that I origionally launched the project by selecting Coded UI test project from the installed node of the tree view for launching a project... When I launched a new project from the C# language sub node, then it worked. This seems like a bug to me. Now when I try to repeat launching a new project from the installed node nothing happens.

So now that I select the selectable recording button it tells me to restart the computer. Thats fine... OK: it appears to be working.


问:
Event handle on customized ListView
```<code>public class ActivityForShow extends Activity

{
     //have a ListView layout
     ListView.setAdapter(SingleRowAdapter);
}

public class SingleRowAdapter extends ArrayAdapter
{
    //every row has a CheckBox ,a TextView and a Button
}
</code>```

Now I want to handle CheckBox and Button events,do some background work and show result in a dialog.

But how to getRefences of Checkbox and Button in ActivityForShow?

findViewById() will cause Exception.

答: Hope the following link may help you, event on an item of ListView custom row layout.</p>

Title: Event handle on customized ListView

Body:
public class ActivityForShow extends Activity

{
     //have a ListView layout
     ListView.setAdapter(SingleRowAdapter);
}

public class SingleRowAdapter extends ArrayAdapter
{
    //every row has a CheckBox ,a TextView and a Button
}

Now I want to handle CheckBox and Button events,do some background work and show result in a dialog.

But how to getRefences of Checkbox and Button in ActivityForShow?

findViewById() will cause Exception.


问:
The submitted data was invalid
I have this error when I refresh page content form then persistent object.

code handler: content function post when I create form with handle :

```<code>  public function post(array $parameters, bool $submitted = false, array $options = [])
        {

            $recruiter = $this->formHandler->handle(
                $this->factory->create(),
                $parameters,
                Request::METHOD_POST,
                $submitted,
                $options
            );
            if ($recruiter instanceof Recruiter) {

            $this->repository->save($recruiter);

            return $recruiter;
        }
    }
</code>```

code controller: use function post for handler and I use try and catch:

```<code>/**
         * @Template()
         * @Route("/register", name="register_recruiter")
         *
         * @param Request $request
         *
         * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
         */
        public function registerAction(Request $request)
        {
                  try {

                $quiz = $this->getHandler()->post($request->request->all());

                return $this->redirectToRoute('recruiter_quizs_index');

            }
            catch (InvalidFormException $e) {
                return [
                    'form' => $e->getForm()->createView(),
                    'edit' => false,
                ];
            }
</code>```

code twig content form :

```<code>{{ form(form) }}
</code>```

function handle for create form:

```<code>public function handle($object, array $parameters, string $method, bool $submited = false, array $options = [])
        {
            $options = array_replace_recursive([
                'method' => $method,
                'csrf_protection' => false,
            ], $options);
            $form = $this->formFactory->create(get_class($this->formType), $object, $options);
            if (!$submited) {

                throw new InvalidFormException($form);
            }
            $form->submit($parameters, 'PATCH' !== $method);
            if (!$form->isValid()) {
                throw new InvalidFormException($form);
            }

            return $form->getData();
        }
</code>```

答:
The problem is that you do not provide a value for the 2nd parameter $submitted, which should probably be true if the method is POST, PUT or PATCH.

The easy way to fix this is checking for the method in the action and provide the boolean parameter

```<code>    /**
     * @Template()
     * @Route("/register", name="register_recruiter")
     *
     * @param Request $request
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function registerAction(Request $request)
    {
        try {
            $submitted = ($request->isMethod('PATCH') || $request->isMethod('POST') || $request->isMethod('PUT'));
            $quiz = $this->getHandler()->post($request->request->all(), $submitted);
            return $this->redirectToRoute('recruiter_quizs_index');
        }
        catch (InvalidFormException $e) {
            return [
                'form' => $e->getForm()->createView(),
                'edit' => false,
            ];
        }
</code>```

Although I think this is a really bad solution. You should create an action for each HTTP method. Show the form with GET, submit it with POST/PUT/PATCH. Put the submit route before the GET route, so it will match first:

```<code>    /**
     * submit the recruiter form (on PATH, POST, PUT)
     *
     * @Template()
     * @Route("/register", name="register_recruiter_submit", methods={"PATCH","POST","PUT"})
     *
     * @param Request $request
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function registerSubmitAction(Request $request)
    {
        try {
            $quiz = $this->getHandler()->post($request->request->all(), true);
            return $this->redirectToRoute('recruiter_quizs_index');
        }
        catch (InvalidFormException $e) {
            return [
                'form' => $e->getForm()->createView(),
                'edit' => false,
            ];
        }
    }

    /**
     * show the recruiter form (route will match if method is not PATCH/PUT/POST
     *
     * @Template()
     * @Route("/register", name="register_recruiter_form")
     *
     * @param Request $request
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function registerFormAction(Request $request)
    {
        return [
            'form' => $this->formHandler->createView(),
            'edit' => false,
        ];
    }
</code>```

Title: The submitted data was invalid

Body:
I have this error when I refresh page content form then persistent object.

code handler: content function post when I create form with handle :

  public function post(array $parameters, bool $submitted = false, array $options = [])
        {

            $recruiter = $this->formHandler->handle(
                $this->factory->create(),
                $parameters,
                Request::METHOD_POST,
                $submitted,
                $options
            );
            if ($recruiter instanceof Recruiter) {

            $this->repository->save($recruiter);

            return $recruiter;
        }
    }

code controller: use function post for handler and I use try and catch:

/**
         * @Template()
         * @Route("/register", name="register_recruiter")
         *
         * @param Request $request
         *
         * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
         */
        public function registerAction(Request $request)
        {
                  try {

                $quiz = $this->getHandler()->post($request->request->all());

                return $this->redirectToRoute('recruiter_quizs_index');

            }
            catch (InvalidFormException $e) {
                return [
                    'form' => $e->getForm()->createView(),
                    'edit' => false,
                ];
            }

code twig content form :

{{ form(form) }}

function handle for create form:

public function handle($object, array $parameters, string $method, bool $submited = false, array $options = [])
        {
            $options = array_replace_recursive([
                'method' => $method,
                'csrf_protection' => false,
            ], $options);
            $form = $this->formFactory->create(get_class($this->formType), $object, $options);
            if (!$submited) {

                throw new InvalidFormException($form);
            }
            $form->submit($parameters, 'PATCH' !== $method);
            if (!$form->isValid()) {
                throw new InvalidFormException($form);
            }

            return $form->getData();
        }

Body:
The problem is that you do not provide a value for the 2nd parameter $submitted, which should probably be true if the method is POST, PUT or PATCH.

The easy way to fix this is checking for the method in the action and provide the boolean parameter

    /**
     * @Template()
     * @Route("/register", name="register_recruiter")
     *
     * @param Request $request
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function registerAction(Request $request)
    {
        try {
            $submitted = ($request->isMethod('PATCH') || $request->isMethod('POST') || $request->isMethod('PUT'));
            $quiz = $this->getHandler()->post($request->request->all(), $submitted);
            return $this->redirectToRoute('recruiter_quizs_index');
        }
        catch (InvalidFormException $e) {
            return [
                'form' => $e->getForm()->createView(),
                'edit' => false,
            ];
        }

Although I think this is a really bad solution. You should create an action for each HTTP method. Show the form with GET, submit it with POST/PUT/PATCH. Put the submit route before the GET route, so it will match first:

    /**
     * submit the recruiter form (on PATH, POST, PUT)
     *
     * @Template()
     * @Route("/register", name="register_recruiter_submit", methods={"PATCH","POST","PUT"})
     *
     * @param Request $request
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function registerSubmitAction(Request $request)
    {
        try {
            $quiz = $this->getHandler()->post($request->request->all(), true);
            return $this->redirectToRoute('recruiter_quizs_index');
        }
        catch (InvalidFormException $e) {
            return [
                'form' => $e->getForm()->createView(),
                'edit' => false,
            ];
        }
    }

    /**
     * show the recruiter form (route will match if method is not PATCH/PUT/POST
     *
     * @Template()
     * @Route("/register", name="register_recruiter_form")
     *
     * @param Request $request
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function registerFormAction(Request $request)
    {
        return [
            'form' => $this->formHandler->createView(),
            'edit' => false,
        ];
    }


问:
www.topstonesoftware.com is not forwarding to topstonesoftware.com on AWS static web site
I've been trying to follow the directions on the AWS page

Example: Setting up a Static Website Using a Custom Domain

I have created two S3 buckets: topstonesoftware.com and www.topstonesoftware.com.  The www bucket forwards to the topstonesoftware.com bucket

I've made the Amazon Route 53 entries (see below).

For reasons that I don't understand, http://topstonesoftware.com works, but http://www.topstonesoftware.com doesn't work (e.g., entering www.topstonesoftware.com just hangs the browser and never resolves the DNS).

When I run "dig" (dig www.topstonesoftware.com) it reports that there is no error in the DNS lookup. Dig also shows the DNS query resolving to the S3 bucket for www.topstonesoftware.com:

```<code>;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47363
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.topstonesoftware.com.  IN  A

;; ANSWER SECTION:
www.topstonesoftware.com. 300   IN  CNAME   www.topstonesoftware.com.s3-website-us-east-1.amazonaws.com.
www.topstonesoftware.com.s3-website-us-east-1.amazonaws.com. 60 IN CNAME s3-website-us-east-1.amazonaws.com.
s3-website-us-east-1.amazonaws.com. 5 IN A  52.216.17.170
</code>```

I've read thought Stackoverflow and the Amazon documentation, but so far, no joy.

Here's the DNS.  The alias record is for topstonesoftware.com and is the alias to the S3 bucket. The CNAME record details are shown.

Many thanks in advance.

答: If you review the AWS documentation from your link you will notice that the docs are using Type A - ALIAS. You are using a CNAME. Change your www entry to use Type A - ALIAS and select the correct S3 website endpoint. Sometimes it takes a minute or two to populate the drop down list.

Body:
I've been trying to follow the directions on the AWS page

Example: Setting up a Static Website Using a Custom Domain

I have created two S3 buckets: topstonesoftware.com and www.topstonesoftware.com.  The www bucket forwards to the topstonesoftware.com bucket

I've made the Amazon Route 53 entries (see below).

For reasons that I don't understand, http://topstonesoftware.com works, but http://www.topstonesoftware.com doesn't work (e.g., entering www.topstonesoftware.com just hangs the browser and never resolves the DNS).

When I run "dig" (dig www.topstonesoftware.com) it reports that there is no error in the DNS lookup. Dig also shows the DNS query resolving to the S3 bucket for www.topstonesoftware.com:

;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47363
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.topstonesoftware.com.  IN  A

;; ANSWER SECTION:
www.topstonesoftware.com. 300   IN  CNAME   www.topstonesoftware.com.s3-website-us-east-1.amazonaws.com.
www.topstonesoftware.com.s3-website-us-east-1.amazonaws.com. 60 IN CNAME s3-website-us-east-1.amazonaws.com.
s3-website-us-east-1.amazonaws.com. 5 IN A  52.216.17.170

I've read thought Stackoverflow and the Amazon documentation, but so far, no joy.

Here's the DNS.  The alias record is for topstonesoftware.com and is the alias to the S3 bucket. The CNAME record details are shown.

Many thanks in advance.


问:
Heroku postgres is very slow under load
I'm deploying an app to the Heroku that uses php and heroku-postgres. App performs about 70-80 queries to the small postgres database (about 10Mb).

I did some load testing using apache bench with 50 concurrent requests. And I found that queries execution time is about 5-8 times slower than without any load. Of course, I checked that tables have correct indexes and queries use them.

I also tried different heroku-postgres plans, but the problem still exists.

答:
I also tried different heroku-postgres plans, but the problem still exists.

Make sure the heroku-postgres plan uses the same region as the Heroku app! I spent a week trying to figure out why my app in the EU needed 80ms instead of 0.2ms to query my DB in the US.

Title: Heroku postgres is very slow under load


问:
Health check to detect redis master from google tcp load balancer
I am trying to setup a google TCP internal Load Balancer. Instance group behind this lb consists of redis-server processes listening on port 6379. Out of these redis instances, only one of them is master.

Problem: Add a TCP health check to detect the redis master and make lb divert all traffic to redis master only.

Approach:
Added a TCP Health Check for the port 6379.
In order to send the command role to redis-server process and parse the response, I am using the optional params provided in the health check. Please check the screenshot here.

Result: Health check is failing for all. If I remove the optional request/response params, health check starts passing for all.

Debugging:

Connected to lb using netcat and issued the command role, it sends the response starting with *3(for master) and *5(for slave) as expected.

Logged into instance and stopped redis-server process. Started listening on port 6379 using nc -l -p 6379 to check what exactly is being received at the instance's side in the health check. It does receive role\r\n.

After step 2, restarted redis-server and ran MONITOR command in redis-cli, to watch log of commands received by this process. Here there is no log of role.
This means, instance is receiving the data(role\r\n) over tcp but is not received by the process redis-cli(as per MONITOR command) or something else is happening. Please help.

答:
Unfortunately GCP's TCP health checks is pretty limited on what can be checked in the response. From https://cloud.google.com/sdk/gcloud/reference/compute/health-checks/create/tcp:

```<code>--response=RESPONSE
 An optional string of up to 1024 characters that the health checker expects to receive from the instance. If the response is not received exactly, the health check probe fails. If --response is configured, but not --request, the health checker will wait for a response anyway. Unless your system automatically sends out a message in response to a successful handshake, only configure --response to match an explicit --request.
</code>```

Note the word "exactly" in the help message. The response has to match the provided string in full. One can't specify a partial string to search for in the response.

As you can see on https://redis.io/commands/role, redis's ROLE command returns a bunch of text. Though the substring "master" is present in the response, it also has a bunch of other text that would vary from setup to setup (based on the number of slaves, their addresses, etc.).

You should definitely raise a feature request with GCP for regex matching on the response. A possible workaround until then is to have a little web app on each host that performs "redis-cli role | grep master" command locally and return the response. Then the health check can be configured to monitor this web app.

Body:
Unfortunately GCP's TCP health checks is pretty limited on what can be checked in the response. From https://cloud.google.com/sdk/gcloud/reference/compute/health-checks/create/tcp:

--response=RESPONSE
 An optional string of up to 1024 characters that the health checker expects to receive from the instance. If the response is not received exactly, the health check probe fails. If --response is configured, but not --request, the health checker will wait for a response anyway. Unless your system automatically sends out a message in response to a successful handshake, only configure --response to match an explicit --request.

Note the word "exactly" in the help message. The response has to match the provided string in full. One can't specify a partial string to search for in the response.

As you can see on https://redis.io/commands/role, redis's ROLE command returns a bunch of text. Though the substring "master" is present in the response, it also has a bunch of other text that would vary from setup to setup (based on the number of slaves, their addresses, etc.).

You should definitely raise a feature request with GCP for regex matching on the response. A possible workaround until then is to have a little web app on each host that performs "redis-cli role | grep master" command locally and return the response. Then the health check can be configured to monitor this web app.


问:
Exclude folder inside war directory in app engine Java
I have node_modules folder inside war folder of app engine java project. I do not want to deploy this folder into app engine. So i tried following

```<code><static-files>
   <exclude path="/node_modules/" />
</static-files>
</code>```

and

```<code><static-files>
   <exclude path="/node_modules/**" />
</static-files>
</code>```

Both does not work. How do i exclude the folder?

答:
Exclude this folder from both static and resource files:

<static-files>
  ...
  <exclude path="/node_modules/**" />
  ...
</static-files>

<resource-files>
  ...
  <exclude path="/node_modules/**" />
  ...
</resource-files>
```

Body:
I have node_modules folder inside war folder of app engine java project. I do not want to deploy this folder into app engine. So i tried following

<static-files>
   <exclude path="/node_modules/" />
</static-files>

and

<static-files>
   <exclude path="/node_modules/**" />
</static-files>

Both does not work. How do i exclude the folder?


问:
Admin console for hornetq
Is there any sort of admin UI available for hornetQ.
Below are the operations we would like to do with admin UI
I need to monitor the messages in the queue(message content as well)
Purging the messages.
Creating queues</p>

答: The HornetQ code-base was donated to the Apache ActiveMQ community several years ago and is now Apache ActiveMQ Artemis.  The latest versions of Apache ActiveMQ Artemis ship with a web-based administration console where you can do things like purge messages and create queues, etc.</p>

Title: Admin console for hornetq


问:
How can I have a constrained Finite State Machine in Haskell / Idris?
EDIT: Users @apocalisp and @BenjaminHodgson left awesome answers below, skip reading most of the question and jump to their answers.

TLDR of the Question: How can I go from the first picture, where FSM states combinatorial explode, to the second picture, where you're just required to visit all of them before moving on.

I would like to build a Finite State Machine (in Haskell really, but I'm trying Idris first to see if it can guide my Haskell) where there are some interim states that must be visited before a final state can be reached. It'd be great if I could arbitrarily constrain the FSM with predicates on some state.

In the following picture, there's an Initial state, 3 interim states A, B, C, and a Final state. If I'm not mistaken, in a "normal" FSM, you will always need n! interim states to represent each combination of possible paths.

This is undesirable.

Instead, using Type Families, and maybe Dependent types, I think it should be possible to have a sort of state that is carried around, and only when it passes certain predicates will you be allowed to travel to the final state. (Does that make it Push Down Automata instead of FSM?)

My code so far (idris), which by analogy, is adding ingredients to make a salad, and the order doesn't matter, but they all need to make it in:

```<code>data SaladState = Initial | AddingIngredients | ReadyToEat

record SaladBowl where
       constructor MkSaladBowl
       lettuce, tomato, cucumber : Bool

data HasIngredient : (ingredient : SaladBowl -> Bool) -> (bowl : SaladBowl ** ingredient bowl = True) -> Type where
     Bowl : HasIngredient ingredient bowl

data HasIngredients : (ingredients : List (SaladBowl -> Bool))
                     -> (bowl : SaladBowl ** (foldl (&&) True (map (\i => i bowl) ingredients) = True))
                     -> Type where
     Bowlx : HasIngredients ingredients bowl

data SaladAction : (ty : Type) -> SaladState -> (ty -> SaladState) -> Type where
     GetBowl     : SaladAction SaladBowl Initial (const Initial)
     AddLettuce  : SaladBowl -> SaladAction (bowl ** HasIngredient lettuce bowl)  st (const AddingIngredients)
     AddTomato   : SaladBowl -> SaladAction (bowl ** HasIngredient tomato bowl)   st (const AddingIngredients)
     AddCucumber : SaladBowl -> SaladAction (bowl ** HasIngredient cucumber bowl) st (const AddingIngredients)
     MixItUp     : SaladBowl -> SaladAction (bowl ** (HasIngredients [lettuce, tomato, cucumber] bowl)) AddingIngredients (const ReadyToEat)
     Pure : (res : ty) -> SaladAction ty (state_fn res) state_fn
     (>>=) : SaladAction a state1 state2_fn
           -> ((res : a) -> SaladAction b (state2_fn res) state3_fn)
           -> SaladAction b state1 state3_fn

emptyBowl : SaladBowl
emptyBowl = MkSaladBowl False False False

prepSalad1 : SaladAction SaladBowl Initial (const ReadyToEat)
prepSalad1 = do
           (b1 ** _) <- AddTomato emptyBowl
           (b2 ** _) <- AddLettuce b1
           (b3 ** _) <- AddCucumber b2
           MixItUp b3
</code>```

And counter example programs that the compiler should error on:

```<code>BAD : SaladAction SaladBowl Initial (const ReadyToEat)
BAD = do
           (b1 ** _) <- AddTomato emptyBowl
           (b2 ** _) <- AddTomato emptyBowl
           (b3 ** _) <- AddLettuce b2
           (b4 ** _) <- AddCucumber b3
           MixItUp b4

BAD' : SaladAction SaladBowl Initial (const ReadyToEat)
BAD' = do
           (b1 ** _) <- AddTomato emptyBowl
           MixItUp b1
</code>```

I eventually want the "ingredients" to be Sums instead of Bools (data Lettuce = Romaine | Iceberg | Butterhead), and more robust semantics where I can say things like "you must first add lettuce, or spinach, but not both".

Really, I feel so quite thoroughly lost, that I imagine my above code has gone in the completely wrong direction... How can I build this FSM (PDA?) to preclude bad programs? I'd especially like to use Haskell for it, perhaps using Indexed Monads?

答:
The indexed state monad does exactly this.

The regular State s monad models a state machine (a Mealy machine, specifically) whose state alphabet is the type s. This data type is really just a function:

```<code>newtype State s a = State { run :: s -> (a, s) }
</code>```

A function of type a -> State s b is a machine with input alphabet a and output alphabet b. But it's really just a function of type (a, s) -> (b, s).

Lining up the input type of one machine and output type of another machine, we can compose two machines:

```<code>(>>=) :: State s a -> (a -> State s b) -> State s b
m >>= f = State (\s1 -> let (a, s2) = run m s1 in run (f a) s2)
</code>```

In other words, State s is a monad.

But sometimes (as in your case), we need the type of the intermediate states to vary. This is where the indexed state monad comes in. It has two state alphabets. IxState i j a models a machine whose start state must be in i and end state will be in j:

```<code>newtype IxState i j a = IxState { run :: i -> (a, j) }
</code>```

The regular State s monad is then equivalent to IxState s s. We can compose IxState as easily as State. The implementation is the same as before, but the type signature is more general:

```<code>(>>>=) :: IxState i j a -> (a -> IxState j k b) -> IxState i k b
m >>>= f = IxState (\s1 -> let (a, s2) = run m s1 in run (f a) s2)
</code>```

IxState is not exactly a monad, but an indexed monad.

We now just need a way of specifying constraints on the type of our state. For the salad example, we want something like this:

```<code>mix :: IxState (Salad r) Ready ()
</code>```

This is a machine whose input state is some incomplete Salad consisting of ingredients r, and whose output state is Ready indicating that our salad is ready to eat.

Using type-level lists, we could say this:

```<code>data Salad xs = Salad
data Ready = Ready
data Lettuce
data Cucumber
data Tomato
</code>```

The empty salad has an empty list of ingredients.

```<code>emptyBowl :: IxState x (Salad '[]) ()
emptyBowl = iput Salad
</code>```

We can add Lettuce to any Salad:

```<code>addLettuce :: IxState (Salad r) (Salad (Lettuce ': r)) ()
addLettuce = iput Salad
</code>```

And we can repeat the same for Tomato and Cucumber.

Now the type of mix just needs to be:

```<code>mix :: IxState (Salad '[Lettuce, Cucumber, Tomato]) Ready ()
mix = const Ready
</code>```

We'll get a type error if we try to mix any salad that we haven't added Lettuce, Cucumber, and Tomato to, in that order. E.g. this will be a type error:

```<code>emptyBowl >>>= \_ -> addLettuce >>>= \_ -> mix
</code>```

But ideally we'd like to be able to add the ingredients in any order. So we need a constraint on our type-level list asking for evidence that a particular ingredient is somewhere in our salad:

```<code>class Elem xs x

instance {-# OVERLAPS #-} Elem (x ': xs) x
instance Elem xs x => Elem (y ': xs) x
</code>```

Elem xs x is now evidence that the type x is in the type-level list xs. The first instance (the base case) says that x is obviously an element of x ': xs. The second instance says that if the type x is an element of xs, then it's also an element of y ': xs for any type y. OVERLAPS is necessary to make sure Haskell knows to check the base case first.

Here's the complete listing:

```<code>{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}

import Control.Monad.Indexed
import Control.Monad.Indexed.State

data Lettuce
data Tomato
data Cucumber

data Ready = Ready

class Elem xs x

instance {-# OVERLAPS #-} Elem (x ': xs) x
instance Elem xs x => Elem (y ': xs) x

data Salad xs = Salad

emptyBowl :: IxState x (Salad '[]) ()
emptyBowl = iput Salad

addLettuce :: IxState (Salad r) (Salad (Lettuce ': r)) ()
addLettuce = iput Salad

addTomato :: IxState (Salad r) (Salad (Tomato ': r)) ()
addTomato = iput Salad

addCucumber :: IxState (Salad r) (Salad (Cucumber ': r)) ()
addCucumber = iput Salad

mix :: (Elem r Lettuce, Elem r Tomato, Elem r Cucumber)
    => IxState (Salad r) Ready ()
mix = imodify mix'
  where mix' = const Ready

x >>> y = x >>>= const y

-- Compiles
test = emptyBowl >>> addLettuce >>> addTomato >>> addCucumber >>> mix

-- Fails with a compile-time type error
fail = emptyBowl >>> addTomato >>> mix
</code>```

Body:
EDIT: Users @apocalisp and @BenjaminHodgson left awesome answers below, skip reading most of the question and jump to their answers.

TLDR of the Question: How can I go from the first picture, where FSM states combinatorial explode, to the second picture, where you're just required to visit all of them before moving on.

I would like to build a Finite State Machine (in Haskell really, but I'm trying Idris first to see if it can guide my Haskell) where there are some interim states that must be visited before a final state can be reached. It'd be great if I could arbitrarily constrain the FSM with predicates on some state.

In the following picture, there's an Initial state, 3 interim states A, B, C, and a Final state. If I'm not mistaken, in a "normal" FSM, you will always need n! interim states to represent each combination of possible paths.

This is undesirable.

Instead, using Type Families, and maybe Dependent types, I think it should be possible to have a sort of state that is carried around, and only when it passes certain predicates will you be allowed to travel to the final state. (Does that make it Push Down Automata instead of FSM?)

My code so far (idris), which by analogy, is adding ingredients to make a salad, and the order doesn't matter, but they all need to make it in:

data SaladState = Initial | AddingIngredients | ReadyToEat

record SaladBowl where
       constructor MkSaladBowl
       lettuce, tomato, cucumber : Bool

data HasIngredient : (ingredient : SaladBowl -> Bool) -> (bowl : SaladBowl ** ingredient bowl = True) -> Type where
     Bowl : HasIngredient ingredient bowl

data HasIngredients : (ingredients : List (SaladBowl -> Bool))
                     -> (bowl : SaladBowl ** (foldl (&&) True (map (\i => i bowl) ingredients) = True))
                     -> Type where
     Bowlx : HasIngredients ingredients bowl

data SaladAction : (ty : Type) -> SaladState -> (ty -> SaladState) -> Type where
     GetBowl     : SaladAction SaladBowl Initial (const Initial)
     AddLettuce  : SaladBowl -> SaladAction (bowl ** HasIngredient lettuce bowl)  st (const AddingIngredients)
     AddTomato   : SaladBowl -> SaladAction (bowl ** HasIngredient tomato bowl)   st (const AddingIngredients)
     AddCucumber : SaladBowl -> SaladAction (bowl ** HasIngredient cucumber bowl) st (const AddingIngredients)
     MixItUp     : SaladBowl -> SaladAction (bowl ** (HasIngredients [lettuce, tomato, cucumber] bowl)) AddingIngredients (const ReadyToEat)
     Pure : (res : ty) -> SaladAction ty (state_fn res) state_fn
     (>>=) : SaladAction a state1 state2_fn
           -> ((res : a) -> SaladAction b (state2_fn res) state3_fn)
           -> SaladAction b state1 state3_fn

emptyBowl : SaladBowl
emptyBowl = MkSaladBowl False False False

prepSalad1 : SaladAction SaladBowl Initial (const ReadyToEat)
prepSalad1 = do
           (b1 ** _) <- AddTomato emptyBowl
           (b2 ** _) <- AddLettuce b1
           (b3 ** _) <- AddCucumber b2
           MixItUp b3

And counter example programs that the compiler should error on:

BAD : SaladAction SaladBowl Initial (const ReadyToEat)
BAD = do
           (b1 ** _) <- AddTomato emptyBowl
           (b2 ** _) <- AddTomato emptyBowl
           (b3 ** _) <- AddLettuce b2
           (b4 ** _) <- AddCucumber b3
           MixItUp b4

BAD' : SaladAction SaladBowl Initial (const ReadyToEat)
BAD' = do
           (b1 ** _) <- AddTomato emptyBowl
           MixItUp b1

I eventually want the "ingredients" to be Sums instead of Bools (data Lettuce = Romaine | Iceberg | Butterhead), and more robust semantics where I can say things like "you must first add lettuce, or spinach, but not both".

Really, I feel so quite thoroughly lost, that I imagine my above code has gone in the completely wrong direction... How can I build this FSM (PDA?) to preclude bad programs? I'd especially like to use Haskell for it, perhaps using Indexed Monads?

Body:
The indexed state monad does exactly this.

The regular State s monad models a state machine (a Mealy machine, specifically) whose state alphabet is the type s. This data type is really just a function:

newtype State s a = State { run :: s -> (a, s) }

A function of type a -> State s b is a machine with input alphabet a and output alphabet b. But it's really just a function of type (a, s) -> (b, s).

Lining up the input type of one machine and output type of another machine, we can compose two machines:

(>>=) :: State s a -> (a -> State s b) -> State s b
m >>= f = State (\s1 -> let (a, s2) = run m s1 in run (f a) s2)

In other words, State s is a monad.

But sometimes (as in your case), we need the type of the intermediate states to vary. This is where the indexed state monad comes in. It has two state alphabets. IxState i j a models a machine whose start state must be in i and end state will be in j:

newtype IxState i j a = IxState { run :: i -> (a, j) }

The regular State s monad is then equivalent to IxState s s. We can compose IxState as easily as State. The implementation is the same as before, but the type signature is more general:

(>>>=) :: IxState i j a -> (a -> IxState j k b) -> IxState i k b
m >>>= f = IxState (\s1 -> let (a, s2) = run m s1 in run (f a) s2)

IxState is not exactly a monad, but an indexed monad.

We now just need a way of specifying constraints on the type of our state. For the salad example, we want something like this:

mix :: IxState (Salad r) Ready ()

This is a machine whose input state is some incomplete Salad consisting of ingredients r, and whose output state is Ready indicating that our salad is ready to eat.

Using type-level lists, we could say this:

data Salad xs = Salad
data Ready = Ready
data Lettuce
data Cucumber
data Tomato

The empty salad has an empty list of ingredients.

emptyBowl :: IxState x (Salad '[]) ()
emptyBowl = iput Salad

We can add Lettuce to any Salad:

addLettuce :: IxState (Salad r) (Salad (Lettuce ': r)) ()
addLettuce = iput Salad

And we can repeat the same for Tomato and Cucumber.

Now the type of mix just needs to be:

mix :: IxState (Salad '[Lettuce, Cucumber, Tomato]) Ready ()
mix = const Ready

We'll get a type error if we try to mix any salad that we haven't added Lettuce, Cucumber, and Tomato to, in that order. E.g. this will be a type error:

emptyBowl >>>= \_ -> addLettuce >>>= \_ -> mix

But ideally we'd like to be able to add the ingredients in any order. So we need a constraint on our type-level list asking for evidence that a particular ingredient is somewhere in our salad:

class Elem xs x

instance {-# OVERLAPS #-} Elem (x ': xs) x
instance Elem xs x => Elem (y ': xs) x

Elem xs x is now evidence that the type x is in the type-level list xs. The first instance (the base case) says that x is obviously an element of x ': xs. The second instance says that if the type x is an element of xs, then it's also an element of y ': xs for any type y. OVERLAPS is necessary to make sure Haskell knows to check the base case first.

Here's the complete listing:

{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}

import Control.Monad.Indexed
import Control.Monad.Indexed.State

data Lettuce
data Tomato
data Cucumber

data Ready = Ready

class Elem xs x

instance {-# OVERLAPS #-} Elem (x ': xs) x
instance Elem xs x => Elem (y ': xs) x

data Salad xs = Salad

emptyBowl :: IxState x (Salad '[]) ()
emptyBowl = iput Salad

addLettuce :: IxState (Salad r) (Salad (Lettuce ': r)) ()
addLettuce = iput Salad

addTomato :: IxState (Salad r) (Salad (Tomato ': r)) ()
addTomato = iput Salad

addCucumber :: IxState (Salad r) (Salad (Cucumber ': r)) ()
addCucumber = iput Salad

mix :: (Elem r Lettuce, Elem r Tomato, Elem r Cucumber)
    => IxState (Salad r) Ready ()
mix = imodify mix'
  where mix' = const Ready

x >>> y = x >>>= const y

-- Compiles
test = emptyBowl >>> addLettuce >>> addTomato >>> addCucumber >>> mix

-- Fails with a compile-time type error
fail = emptyBowl >>> addTomato >>> mix


问:
Yum Install Issue in Centos while installing Couchbase
I was trying to run the below command to install packages in Centos.

[cloudera@quickstart ~]$ sudo yum install -y pkgconfig

After running the above command getting the below error.

Loaded plugins: fastestmirror, security
Setting up Install Process
Error: File contains no section headers.
file: file:///etc/yum.repos.d/docker-ee.repo, line: 1
'<!doctype html>\n'

答: This is not related to Couchbase at all. Looks like your /etc/yum.repos.d/docker-ee.repo is not really plain text, and has HTML content instead. Try to remove this file and retry.


问:
You have not accepted the license agreements of the following SDK components
I downloaded the latest Android SDK tools version 24.4.1. I used the command line to install SDKs. I typed y when asked

Do you accept the license 'android-sdk-license-c81a61d9' [y/n]: y
  after that install succeeded.

But when using Gradle 3.1 to build, the follows shows up

You have not accepted the license agreements of the following SDK components:
    [Android SDK Platform 23, Android SDK Build-Tools 23.0.1].
    Before building your project, you need to accept the license agreements and complete the installation of the missing components using the Android Studio SDK Manager.
    Alternatively, to learn how to transfer the license agreements from one workstation to another, go to http://d.android.com/r/studio-ui/export-licenses.html

I checked ~/.android and /opt/android-sdk where Android tools are put. Neither contain folder named licenses.

答:
I have resolved the problem by using the command:

Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\tools\bin\ (If the folder is not available then download the Android SDK first, or
you can install it from the android studio installation process.)

Shift+Left click and Press W, then Enter to open CMD on the folder path

Type in the cmd: sdkmanager --licenses

Once press enter, you need to accept all the licenses by pressing y

Checking the licenses

Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\

Check the folder named licenses

```<code>android-googletv-license
android-sdk-license
android-sdk-preview-license
google-gdk-license
intel-android-extra-license
mips-android-sysimage-license
</code>```

AS NEW UPDATE FOLDER PATH (Current Android Studio)

Open Android Studio, Tools > Sdk Manager > Android SDK Command-Line Tools (Just Opt-in)

SDKManager will be store in :

Go to C:\Users\ [PC NAME] \AppData\Local\Android\Sdk\cmdline-tools\latest\bin

Type in the cmd: sdkmanager --licenses

Documentation to using the Android SDK: https://developer.android.com/studio/command-line/sdkmanager.html

Body:
I have resolved the problem by using the command:

Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\tools\bin\ (If the folder is not available then download the Android SDK first, or
you can install it from the android studio installation process.)

Shift+Left click and Press W, then Enter to open CMD on the folder path

Type in the cmd: sdkmanager --licenses

Once press enter, you need to accept all the licenses by pressing y

Checking the licenses

Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\

Check the folder named licenses

android-googletv-license
android-sdk-license
android-sdk-preview-license
google-gdk-license
intel-android-extra-license
mips-android-sysimage-license

AS NEW UPDATE FOLDER PATH (Current Android Studio)

Open Android Studio, Tools > Sdk Manager > Android SDK Command-Line Tools (Just Opt-in)

SDKManager will be store in :

Go to C:\Users\ [PC NAME] \AppData\Local\Android\Sdk\cmdline-tools\latest\bin

Type in the cmd: sdkmanager --licenses

Documentation to using the Android SDK: https://developer.android.com/studio/command-line/sdkmanager.html


问:
Understanding defaultRowPrefetch and defaultBatchValue in Oracle JDBC Driver
I have set defaultRowPrefetch to 40 and defaultBatchValue to 15 in my Connection Object. Now I run a 'single' query which should return a 'single' row.

```<code>// define database user/password
String dbUser = "mp";
String dbPassword = "mp2";
String dbURL = "jdbc:oracle:thin:@myserver:1521:scorpian";
// specify the Properties object
Properties props = new Properties();
props.put("user", dbUser);
props.put("password", dbPassword);
props.put("defaultRowPrefetch","40");
props.put("defaultBatchValue","15");
</code>```

Will the driver wait till it have 15 queries to run or run my query immediately ?Also, Since my query have to return only a single row , then how defaultRowPrefetch size comes into the picture.

答: defaultBatchValue is used in the context of DML batching. Since you're talking about queries that return rows I'm guessing that you're not doing JDBC DML batching at all and so this property isn't relevant. What is relevant is defaultRowPrefetch which tells the Oracle driver to fetch rows 40 by 40 (instead of the default which is 10). Given that you only care about the first row you can set the value to 1.</p>

Body:
I have set defaultRowPrefetch to 40 and defaultBatchValue to 15 in my Connection Object. Now I run a 'single' query which should return a 'single' row.

// define database user/password
String dbUser = "mp";
String dbPassword = "mp2";
String dbURL = "jdbc:oracle:thin:@myserver:1521:scorpian";
// specify the Properties object
Properties props = new Properties();
props.put("user", dbUser);
props.put("password", dbPassword);
props.put("defaultRowPrefetch","40");
props.put("defaultBatchValue","15");

Will the driver wait till it have 15 queries to run or run my query immediately ?Also, Since my query have to return only a single row , then how defaultRowPrefetch size comes into the picture.


问:
Angular if screen is above a certain breakpoint, show one div, else show another
On my html I have two divs with different layouts.
One is a table, and the other one is a several divs

```<code> <div class="firstView>
   <table class="table table-bordered">.....
     ..
    <tr *ngFor="let data of Data">
     <td>data.name</td>
    </tr>
   </table>
 </div>

 <div class="secondView">
  <div class="col-md-12" *ngFor="let data of Data">
     insert data here
  </div>
</code>```

I can use show and hidden to display or hide them at certain screen sizes.
But since I load data in both of them, I think it would be best if I could have an If statement, that displays and renders firstView if screensize > 992px
and the secondView if it's less than that.

How can I have an ngIf statement with breakpoints as values?

答:
If you really want to use an *ngIf to get rid of the DOM elements themselves, you could bind window.innerWidth to a variable on ngOnInit and then use this to conditionally hide or show a container based on an *ngIf.

If you also care about resizing you can bind a host listener to the window's resize event and reassign the variable when it fires!

Body:
On my html I have two divs with different layouts.
One is a table, and the other one is a several divs

.....
     ..

     data.name

     insert data here

I can use show and hidden to display or hide them at certain screen sizes.
But since I load data in both of them, I think it would be best if I could have an If statement, that displays and renders firstView if screensize > 992px
and the secondView if it's less than that.

How can I have an ngIf statement with breakpoints as values?


问:
Install app via usb: The device is temporarily restricted
When I toggle on the install via USB in developer mode:

it will pop the toast message said that the device is temporarily restricted

then toggle off the settings.

Is there any solution for this?

I searched through all the way like turning off MIUI optimization but still does not work. I cannot debug my application by Android Studio in this way......

答: I tried everything to no result, then read somewhere that you should use VPN and connect under China to unlock your phone's bootloader. Applied the same solution here and it worked!</p>