问:
Integrating HealthCheck endpoint into swagger (open API) UI on dotnet core
I am using Dotnet Core healthchecks as described here. In short, it looks like this:

First, you configure services like this:

services.AddHealthChecks()
    .AddSqlServer("connectionString", name: "SQlServerHealthCheck")
    ... // Add multiple other checks
```
<p>Then, you register an endpoint like this:</p>
<pre class="lang-cs prettyprint-override"><code>app.UseHealthChecks("/my/healthCheck/endpoint");
</code>```

We are also using Swagger (aka Open API) and we see all the endpoints via Swagger UI, but not the health check endpoint.

Is there a way to add this to a controller method so that Swagger picks up the endpoint automatically, or maybe integrate it with swagger in another way?

The best solution I found so far is to add a custom hardcoded endpoint (like described here), but it is not nice to maintain.

答:
There is no built-in support, either you manually develop a poor man's solution like in the accepted answer or you develop an extension like mentionned in this GitHub issue: NetCore 2.2 - Health Check Support

Swashbuckle is built on top of ApiExplorer, the API metadata component, that ships with ASP.NET Core.

If health-checks endpoints aren't surfaced by that, then they won't be surfaced by Swashbuckle. This is a fundamental aspect to the SB design and is unlikely to change anytime soon.

IMO, this sounds like a perfect candidate for a community add-on package (see https://github.com/domaindrivendev/Swashbuckle.AspNetCore#community-packages).

If there was a willing contributor, they could start a new project called Swashbuckle.AspNetCore.HealthChecks, that exposes an extension method on SwaggerGenOptions for enabling the functionality - e.g. EnableHealthCheckDescriptions. Then behind the scenes, this could be implemented as a Document Filter (see readme) that adds the relevant Operation descriptions to the Swagger/OAI document generated by Swashbuckle.

Body:
I am using Dotnet Core healthchecks as described here. In short, it looks like this:

First, you configure services like this:

services.AddHealthChecks()
    .AddSqlServer("connectionString", name: "SQlServerHealthCheck")
    ... // Add multiple other checks

Then, you register an endpoint like this:

app.UseHealthChecks("/my/healthCheck/endpoint");

We are also using Swagger (aka Open API) and we see all the endpoints via Swagger UI, but not the health check endpoint.

Is there a way to add this to a controller method so that Swagger picks up the endpoint automatically, or maybe integrate it with swagger in another way?

The best solution I found so far is to add a custom hardcoded endpoint (like described here), but it is not nice to maintain.


来源: stackexchange

问:
What's wrong with this template
I am doing c++ 6th edition the 6th exercise of 8th chapter. I have questions on this template. I don't know why it always shows the last string not shows the string that has the max length.  </p>

```<code>#include <iostream>
#include <cstring>

//8.6

using namespace std;

template <typename T> T Maxn(T *,int);

template <>  char * Maxn<>(char **,int );

int main()
{
    double arr_1[5] = { 0.0,3.0,1.0,4.0,5.0 };
    cout << "double max: " << Maxn(arr_1,5) << endl;

    int arr_2[4] = { 3,4,1,0 };
    cout << "int max: " << Maxn(arr_2, 4) << endl;

    const char *arr_3[4] = { "sdf","tttq","ttttrrsdss" ,"q12221"};
    cout << "char max:" << Maxn(arr_3, 4) << endl;

    return 0;
}

template <typename T>
T Maxn(T *p,int n)
{
    T max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (p[i] > max)
            max = p[i];
    }

    return max;
}

template <> char * Maxn<>(char **p, int n)
{
    char * max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (strlen(p[i]) > strlen(max))
        {
            max = p[i];
        }
    }
    return max;
}
</code>```

答:
Type of arr_3 is const char *, but not char *:

```<code>const char *arr_3[4] = { "sdf","tttq","ttttrrsdss" ,"q12221"};
</code>```

, so the first implementation of Maxn is called, where strlen is not used.

ContentLicense: CC BY-SA 4.0

Title: What's wrong with this template

Body:
I am doing c++ 6th edition the 6th exercise of 8th chapter. I have questions on this template. I don't know why it always shows the last string not shows the string that has the max length.

#include <iostream>
#include <cstring>

//8.6

using namespace std;

template <typename T> T Maxn(T *,int);

template <>  char * Maxn<>(char **,int );

int main()
{
    double arr_1[5] = { 0.0,3.0,1.0,4.0,5.0 };
    cout << "double max: " << Maxn(arr_1,5) << endl;

    int arr_2[4] = { 3,4,1,0 };
    cout << "int max: " << Maxn(arr_2, 4) << endl;

    const char *arr_3[4] = { "sdf","tttq","ttttrrsdss" ,"q12221"};
    cout << "char max:" << Maxn(arr_3, 4) << endl;

    return 0;
}

template <typename T>
T Maxn(T *p,int n)
{
    T max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (p[i] > max)
            max = p[i];
    }

    return max;
}

template <> char * Maxn<>(char **p, int n)
{
    char * max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (strlen(p[i]) > strlen(max))
        {
            max = p[i];
        }
    }
    return max;
}

Body:
Type of arr_3 is const char *, but not char *:

const char *arr_3[4] = { "sdf","tttq","ttttrrsdss" ,"q12221"};

, so the first implementation of Maxn is called, where strlen is not used.


问:
AWS SES - Changing AWS Accounts
I'm working with a client right now that has a legacy application hosted by a 3rd party vendor on their amazon account.  That legacy app was using Amazon SES for their mailing.

I created the clients own amazon account (as I don't have access to continue the build out on clients account), and am now seeing the issue where I need to transition the SES DNS validation over to their account.

I'm wondering what kind of downtime I would see, or problems I'd create by updating the DNS entry of _amazonses.mydomain.com from what it was on the past account to this new account.

My concern is by updating that entry, I would break the legacy system which I don't have the ability to update.

Thank you

答:
You don't have any downtime, you can verify the domains in two different account, it just you need to add multiple TXT value to the record "_amazonses.mydomain.com".

e.g: _amazonses.mydomain.com
"txt-value-1"
"txt-value0-2"

As long as your clients are using their own credentials, emails flow just fine, once you confirm everything is good, you can remove your record from there.

If no,

You can still use SES sending authorization and allow them to use the domain verified in your account, doing this, they can only use your sending domain to send emails but emails will go from their account and they will be charged, their account should be in production.
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html

Title: AWS SES - Changing AWS Accounts


问:
Efficiently creating code to calculate relative error
The overall purpose of my code is calculate the pixel-scale relative errors after aggregating a fine-resolution map to a coarse-resolution map. To accomplish this, I have already created a data frame (here labelled as df) that at least put these numbers together. Next, I wanted to calculate the relative error for each coarse-resolution pixel, and to do that I need to calculate the root-mean squared error between the coarse pixel and the fine pixels it contains, as well as the mean of the fine pixels it contains. This then needs to iterate over all of the coarse pixels.

While I do have this problem solved with a for loop (see below), it is not the most optimal piece of code, especially because the data frame is rather large (mainly because I am looking over a large area of interest).

I believe the more efficient approach uses by() or maybe aggregate()?, but I am not sure how this can be performed. I have tried adapting the code (specifically the for loop) towards these function, but have had no success. Any thoughts on how to make it work with by()?

```<code>df <- as.data.frame(cbind(FineSP@data,extract$cells,extract$coarseval))

names(df)[1] <- "fine_res_values"
names(df)[2] <- "cellnumber"
names(df)[3] <- "coarse_res_values"

df$cellnumber <- as.character(df$cellnumber)

uniquecells<-unique(df$cellnumber)

rmse_user <- function(fine, coarse){ # user fuction to calculate root-mean squared error

  rmse_fun = sqrt( mean( (fine - coarse)^2, na.rm = TRUE) )

  return(rmse_fun)

}

relative_error_user <- function(fine, coarse){ # user fuction to calculate pixel-scale relative error

  relative_error_value <- round(rmse_user(fine, coarse) / mean(fine), 3)

  return(relative_error_value)

}

relerror_compile <- vector()
i<-1
for(i in 1:length(uniquecells)){

  filter <- df[which(df$cellnumber == uniquecells[i]),]  # subset data frame by matching cell numbers
  relerror_compile[i] <- relative_error_user(fine = filter$fine_res_values, coarse = filter$coarse_res_values) # apply the user-based function for relative error

}

# Initial (and unsuccessful) attempt to use by() as the alternative

by_test <-by (df$fine_res_values,list(df$cellnumber),FUN=function(z)
</code>```

答:
Aggregate can do this, but have you considered the plyr package? Personally, I find it more 'user-friendly':</p>

```<code>df <- data.frame(cellnumber=rep(1:3,each=4),
                 fine_res_value=rnorm(12,10,5),
                 coarse_res_value=rnorm(12,10,5))

library(plyr)
RE <- ddply(df,'cellnumber',function(x){round(sqrt( mean( (x$fine - x$coarse)^2, na.rm = TRUE) ) / mean(x$fine), 3)} )
</code>```

Body:
The overall purpose of my code is calculate the pixel-scale relative errors after aggregating a fine-resolution map to a coarse-resolution map. To accomplish this, I have already created a data frame (here labelled as df) that at least put these numbers together. Next, I wanted to calculate the relative error for each coarse-resolution pixel, and to do that I need to calculate the root-mean squared error between the coarse pixel and the fine pixels it contains, as well as the mean of the fine pixels it contains. This then needs to iterate over all of the coarse pixels.

While I do have this problem solved with a for loop (see below), it is not the most optimal piece of code, especially because the data frame is rather large (mainly because I am looking over a large area of interest).

I believe the more efficient approach uses by() or maybe aggregate()?, but I am not sure how this can be performed. I have tried adapting the code (specifically the for loop) towards these function, but have had no success. Any thoughts on how to make it work with by()?

df <- as.data.frame(cbind(FineSP@data,extract$cells,extract$coarseval))

names(df)[1] <- "fine_res_values"
names(df)[2] <- "cellnumber"
names(df)[3] <- "coarse_res_values"

df$cellnumber <- as.character(df$cellnumber)

uniquecells<-unique(df$cellnumber)

rmse_user <- function(fine, coarse){ # user fuction to calculate root-mean squared error

  rmse_fun = sqrt( mean( (fine - coarse)^2, na.rm = TRUE) )

  return(rmse_fun)

}

relative_error_user <- function(fine, coarse){ # user fuction to calculate pixel-scale relative error

  relative_error_value <- round(rmse_user(fine, coarse) / mean(fine), 3)

  return(relative_error_value)

}

relerror_compile <- vector()
i<-1
for(i in 1:length(uniquecells)){

  filter <- df[which(df$cellnumber == uniquecells[i]),]  # subset data frame by matching cell numbers
  relerror_compile[i] <- relative_error_user(fine = filter$fine_res_values, coarse = filter$coarse_res_values) # apply the user-based function for relative error

}

# Initial (and unsuccessful) attempt to use by() as the alternative

by_test <-by (df$fine_res_values,list(df$cellnumber),FUN=function(z)

Body:
Aggregate can do this, but have you considered the plyr package? Personally, I find it more 'user-friendly':

df <- data.frame(cellnumber=rep(1:3,each=4),
                 fine_res_value=rnorm(12,10,5),
                 coarse_res_value=rnorm(12,10,5))

library(plyr)
RE <- ddply(df,'cellnumber',function(x){round(sqrt( mean( (x$fine - x$coarse)^2, na.rm = TRUE) ) / mean(x$fine), 3)} )


问:
React state passes from one component to the next inconsistently
I have two components: LeagueSelect and TeamSelect.

All I'm trying to do right now is pass the checkedLeagues state from LeagueSelect to TeamSelect.

It's currently setup to have the checkboxes in TeamSelect be checked if the corresponding league is checked.

The issue: the state passes from LeagueSelect to TeamSelect inconsistently.

This is a video of what it looks like:
https://streamable.com/2i06g

When a box is unchecked, the state updates 'in team', as you can see in the console.log, but, when you try to check the same box again the state does not update in team.

I initially tried to implement this with redux, thought this issue was a redux issue, moved to directly passing state to the child component, and realized that the issue must be somewhere else.

This is my LeagueSelect component:

```<code>import React, { Component } from 'react';
import { View, Text, Modal, TouchableHighlight, FlatList, Button } from 'react-native'
import { loadLeagues } from '../actions'
import { connect } from 'react-redux'
import Check from './CheckBox'
import axios from "axios"
import { loadCards, loadTeams, changeLeagues } from '../actions'
import { Icon } from 'native-base'
import TeamSelect from './TeamSelect'

class LeagueSelect extends Component {
    constructor(props) {
        super(props)
        this.state = {
            modalVisible: false,
            checked: [],
            checkedLeagues: [],
            checkMessage: ''
        }
    }

    setModalVisible(visible) {
        this.setState({modalVisible: visible})
        if(this.state.checked.length === 0) {
            this.props.league.map(
                (v, i) => {
                    this.state.checked.push(true)
                    this.state.checkedLeagues.push(v.acronym)
                }
            )
        }
        this.setState({ checkMessage: '' })
    }

    changeCheck = (index, acronym) => {
        //local variable to create query param
        firstString = []
        //adds to local variable if not checked, takes out variable if checked
        if(!this.state.checkedLeagues.includes(acronym)) {
            firstString.push(acronym)
        } else {
            firstString.filter(v => { return v !== acronym})
        }
        //adds leagues that could be in the current state that were not just passed in
        this.state.checkedLeagues.map(
            (v, i) => {
                if(v !== acronym) {
                    firstString.push(v)
                }
            }
        )

        //updates checked leagues state
        //makes api call with parameters set
        //prevents all leagues being unselected
        if(acronym === this.state.checkedLeagues[0] && firstString.length === 0) {
            this.setState({ checkMessage: `Don't you want something to look at?` })
        } else {
            if(!this.state.checkedLeagues.includes(acronym)){
                this.state.checkedLeagues[this.state.checkedLeagues.length] = acronym
                this.setState({ checkedLeagues: this.state.checkedLeagues })
            } else {
                newChecked  = this.state.checkedLeagues.filter(v => { return v !== acronym})
                this.setState({checkedLeagues: newChecked})
            }

            //updating the check
            this.state.checked[index] = !this.state.checked[index]
            this.setState({ checked: this.state.checked })

            queryString = []

            firstString.map(
                (v, i) => {
                    if (queryString.length < 1) {
                        queryString.push(`?league=${v}`)
                    } else if (queryString.length >= 1 ) {
                        queryString.push(`&league=${v}`)
                    }
                }
            )

            axios.get(`http://localhost:4000/reports${queryString.join('')}`)
                    .then(response => {
                        this.props.loadCards(response.data)
                    })
        }
    }

    render() {

      return (

        <View style={{ position: 'relative'}}>
                        <Text
                            style={{
                                paddingTop: 8,
                                paddingLeft: 5,
                                fontSize: 15
                            }}
                        >Leagues</Text>
                        <View
                            style={{
                                flexDirection:"row",
                            }}
                        >
                            {this.props.league === null ?'' : this.props.league.map(
                                (v, i) => {
                                    return(
                                            <View
                                                key={i}
                                                style={{
                                                    alignSelf: 'flex-end',
                                                    flexDirection:"row",
                                                    top: 4,

                                                }}
                                            >
                                                <Check
                                                    checked={this.state.checked[i]}
                                                    index={i}
                                                    value={v.acronym}
                                                    changeCheck={this.changeCheck}
                                                />
                                                <Text
                                                    style={{
                                                        paddingLeft: 23,

                                                    }}
                                                >{v.acronym}</Text>
                                            </View>
                                    )
                                }
                            )}
                        </View>
                    <Text
                        style={{
                            paddingLeft: 10,
                            paddingTop: 12,
                            fontStyle: 'italic',
                            color: '#F4AF0D'
                        }}
                    >{this.state.checkMessage}</Text>
                    <TeamSelect  checkedLeagues={this.state.checkedLeagues}/>
                </View>
            </View>
      );
    }
  }

export default LeagueSelect
</code>```

This is my TeamSelect component:

```<code>import React, { Component } from 'react'
import { Text, View } from 'react-native'
import { connect } from 'react-redux'
import { loadTeams, loadLeagues } from '../actions'
import Check from './CheckBox'

class TeamSelect extends Component {
    constructor(props) {
        super(props)
        this.state = {
            checked: [],
            checkedTeams: [],
            setOnce: 0
        }
    }

    render() {
    console.log('in team', this.props.checkedLeagues)

        return(
          <View>
              {
                  this.props.team === null ?'' : this.props.team.map(
                      (v, i) => {
                         return(
                                <View key={i}>
                                    <Check
                                        checked={ this.props.checkedLeagues.includes(v.league.acronym) ? true : false }
                                        index={i}
                                        value={v.team_name}
                                        changeCheck={this.changeCheck}
                                    />

                                { v.team_name === undefined ? null :
                                    <Text>{v.team_name}</Text>}
                                </View>
                            )
                      }
                  )
             }
          </View>
        )
    }
}

export default TeamSelect
</code>```

答:
this.setState({ checkedLeagues: this.state.checkedLeagues })

Statements like these can cause issues as you are mutating and setting the state to the same object. The reference to checked leagues doesn't get updated and react may not trigger a render. Use this instead

this.setState({ checkedLeagues: [...this.state.checkedLeagues] })

But this whole approach to the problem is wrong, you should use one leagues object that has a checked property to it, and pass it down.

make you league object look like this,

```<code>const leagues = [
  {
  acronym: 'abc',
  checked: false,
  teams: [ ...array of teams here ]
  },
  ...
]
</code>```

When you pass it down to TeamSelect, you can map it like this

```<code>const { leagues } = this.props
{leagues && leagues.map((league, i) => league.teams.map((team, j) (
<View key={team.team_name}>
 <Check
  checked={league.checked}
  index={i + i * j}
  value={team.team_name}
  changeCheck={() => this.changeCheck(i, j)}
 />
 {team.team_name && <Text>{team.team_name}</Text>}
</View>)))}
</code>```

Same with leagueSelect, you can map leagues like this:

```<code>const { leagues } = this.state
{leagues.map((league, i) => (
  <View
    key={league.acronym}
    style={{
      alignSelf: 'flex-end',
      flexDirection:"row",
      top: 4,
    }}>
      <Check
        checked={league.checked}
        index={i}
        value={league.acronym}
        changeCheck={this.changeCheck}
      />
      <Text
       style={{
       paddingLeft: 23,
       }}
       >{league.acronym}</Text>
    </View>
  )
)}

</code>```

Note: leagues have to be copied from props to state for you to mutate it. I just typed this so it will need some changes before it runs, it's just meant to show you the "react way" of coding this.

https://reactjs.org/docs/lifting-state-up.html

Body:
I have two components: LeagueSelect and TeamSelect.

All I'm trying to do right now is pass the checkedLeagues state from LeagueSelect to TeamSelect.

It's currently setup to have the checkboxes in TeamSelect be checked if the corresponding league is checked.

The issue: the state passes from LeagueSelect to TeamSelect inconsistently.

This is a video of what it looks like:
https://streamable.com/2i06g

When a box is unchecked, the state updates 'in team', as you can see in the console.log, but, when you try to check the same box again the state does not update in team.

I initially tried to implement this with redux, thought this issue was a redux issue, moved to directly passing state to the child component, and realized that the issue must be somewhere else.

This is my LeagueSelect component:

import React, { Component } from 'react';
import { View, Text, Modal, TouchableHighlight, FlatList, Button } from 'react-native'
import { loadLeagues } from '../actions'
import { connect } from 'react-redux'
import Check from './CheckBox'
import axios from "axios"
import { loadCards, loadTeams, changeLeagues } from '../actions'
import { Icon } from 'native-base'
import TeamSelect from './TeamSelect'

class LeagueSelect extends Component {
    constructor(props) {
        super(props)
        this.state = {
            modalVisible: false,
            checked: [],
            checkedLeagues: [],
            checkMessage: ''
        }
    }

    setModalVisible(visible) {
        this.setState({modalVisible: visible})
        if(this.state.checked.length === 0) {
            this.props.league.map(
                (v, i) => {
                    this.state.checked.push(true)
                    this.state.checkedLeagues.push(v.acronym)
                }
            )
        }
        this.setState({ checkMessage: '' })
    }

    changeCheck = (index, acronym) => {
        //local variable to create query param
        firstString = []
        //adds to local variable if not checked, takes out variable if checked
        if(!this.state.checkedLeagues.includes(acronym)) {
            firstString.push(acronym)
        } else {
            firstString.filter(v => { return v !== acronym})
        }
        //adds leagues that could be in the current state that were not just passed in
        this.state.checkedLeagues.map(
            (v, i) => {
                if(v !== acronym) {
                    firstString.push(v)
                }
            }
        )

        //updates checked leagues state
        //makes api call with parameters set
        //prevents all leagues being unselected
        if(acronym === this.state.checkedLeagues[0] && firstString.length === 0) {
            this.setState({ checkMessage: `Don't you want something to look at?` })
        } else {
            if(!this.state.checkedLeagues.includes(acronym)){
                this.state.checkedLeagues[this.state.checkedLeagues.length] = acronym
                this.setState({ checkedLeagues: this.state.checkedLeagues })
            } else {
                newChecked  = this.state.checkedLeagues.filter(v => { return v !== acronym})
                this.setState({checkedLeagues: newChecked})
            }

            //updating the check
            this.state.checked[index] = !this.state.checked[index]
            this.setState({ checked: this.state.checked })

            queryString = []

            firstString.map(
                (v, i) => {
                    if (queryString.length < 1) {
                        queryString.push(`?league=${v}`)
                    } else if (queryString.length >= 1 ) {
                        queryString.push(`&league=${v}`)
                    }
                }
            )

            axios.get(`http://localhost:4000/reports${queryString.join('')}`)
                    .then(response => {
                        this.props.loadCards(response.data)
                    })
        }
    }

    render() {

      return (

        <View style={{ position: 'relative'}}>
                        <Text
                            style={{
                                paddingTop: 8,
                                paddingLeft: 5,
                                fontSize: 15
                            }}
                        >Leagues</Text>
                        <View
                            style={{
                                flexDirection:"row",
                            }}
                        >
                            {this.props.league === null ?'' : this.props.league.map(
                                (v, i) => {
                                    return(
                                            <View
                                                key={i}
                                                style={{
                                                    alignSelf: 'flex-end',
                                                    flexDirection:"row",
                                                    top: 4,

                                                }}
                                            >
                                                <Check
                                                    checked={this.state.checked[i]}
                                                    index={i}
                                                    value={v.acronym}
                                                    changeCheck={this.changeCheck}
                                                />
                                                <Text
                                                    style={{
                                                        paddingLeft: 23,

                                                    }}
                                                >{v.acronym}</Text>
                                            </View>
                                    )
                                }
                            )}
                        </View>
                    <Text
                        style={{
                            paddingLeft: 10,
                            paddingTop: 12,
                            fontStyle: 'italic',
                            color: '#F4AF0D'
                        }}
                    >{this.state.checkMessage}</Text>
                    <TeamSelect  checkedLeagues={this.state.checkedLeagues}/>
                </View>
            </View>
      );
    }
  }

export default LeagueSelect

This is my TeamSelect component:

import React, { Component } from 'react'
import { Text, View } from 'react-native'
import { connect } from 'react-redux'
import { loadTeams, loadLeagues } from '../actions'
import Check from './CheckBox'

class TeamSelect extends Component {
    constructor(props) {
        super(props)
        this.state = {
            checked: [],
            checkedTeams: [],
            setOnce: 0
        }
    }

    render() {
    console.log('in team', this.props.checkedLeagues)

        return(
          <View>
              {
                  this.props.team === null ?'' : this.props.team.map(
                      (v, i) => {
                         return(
                                <View key={i}>
                                    <Check
                                        checked={ this.props.checkedLeagues.includes(v.league.acronym) ? true : false }
                                        index={i}
                                        value={v.team_name}
                                        changeCheck={this.changeCheck}
                                    />

                                { v.team_name === undefined ? null :
                                    <Text>{v.team_name}</Text>}
                                </View>
                            )
                      }
                  )
             }
          </View>
        )
    }
}

export default TeamSelect

Body:
this.setState({ checkedLeagues: this.state.checkedLeagues })

Statements like these can cause issues as you are mutating and setting the state to the same object. The reference to checked leagues doesn't get updated and react may not trigger a render. Use this instead

this.setState({ checkedLeagues: [...this.state.checkedLeagues] })

But this whole approach to the problem is wrong, you should use one leagues object that has a checked property to it, and pass it down.

make you league object look like this,

const leagues = [
  {
  acronym: 'abc',
  checked: false,
  teams: [ ...array of teams here ]
  },
  ...
]

When you pass it down to TeamSelect, you can map it like this

const { leagues } = this.props
{leagues && leagues.map((league, i) => league.teams.map((team, j) (
<View key={team.team_name}>
 <Check
  checked={league.checked}
  index={i + i * j}
  value={team.team_name}
  changeCheck={() => this.changeCheck(i, j)}
 />
 {team.team_name && <Text>{team.team_name}</Text>}
</View>)))}

Same with leagueSelect, you can map leagues like this:

const { leagues } = this.state
{leagues.map((league, i) => (
  <View
    key={league.acronym}
    style={{
      alignSelf: 'flex-end',
      flexDirection:"row",
      top: 4,
    }}>
      <Check
        checked={league.checked}
        index={i}
        value={league.acronym}
        changeCheck={this.changeCheck}
      />
      <Text
       style={{
       paddingLeft: 23,
       }}
       >{league.acronym}</Text>
    </View>
  )
)}

Note: leagues have to be copied from props to state for you to mutate it. I just typed this so it will need some changes before it runs, it's just meant to show you the "react way" of coding this.

https://reactjs.org/docs/lifting-state-up.html


问:
drupal module statistics not counting recent page views
I have the the statistics module for drupal, but it seems to fail, it doesn't count the page views..
all remains in 0 if I want to show for example a total view for an article in a view,
and when I enter to admin and try to see the recent visits, it sais that there are no statistics
So it is obviously failing.
I did enable it with the proper permissions...
any iddeas?</p>

答:
It's dumb, but there is a settings page under the report hierarchy of the navigation menu. You must enable a few options in there for statistics to start tracking. In Drupal 7, it's admin/config/system/statistics.

Also make sure sure you're only tracking node views or it will fill you watchdog table up so fast you could cry.

ContentLicense: CC BY-SA 3.0


问:
How to wait for a multiple batch files to finish
Say I have 5 batch files that need to run simultaneously to save time; these 5 batch files are all currently called from the same MakeAll batch file with:

```<code>START /D PATH "Window Name" BATCH_FILE ARGUMENTS
</code>```

I then have 2 other batch files that need to run when all 5 of the previous group (MakeAll) are done running; these 2 batch files are called 4 times with different arguments from the same AssembleAll batch file with the same command above.

Ideally I'd like to create another batch file called DoAll that first runs MakeAll and waits for the 5 associated processes to finish and then calls AssembleAll.

Code

DoAll.bat:

```<code>START /D Folder9 "Window9" MakeAll.bat
:: Wait for the above to finish all 5 windows
START /D Folder10 "Window510" AssembleAll.bat
</code>```

MakeAll.bat:

```<code>START /D Folder1 "Window1" prog1.bat
START /D Folder2 "Window2" prog2.bat
START /D Folder3 "Window3" prog3.bat
START /D Folder4 "Window4" prog4.bat
START /D Folder5 "Window5" prog5.bat
</code>```

AssembleAll.bat:

```<code>START /D Folder5 "Window5" prog5.bat
START /D Folder6 "Window6" prog6.bat
START /D Folder7 "Window7" prog7.bat
START /D Folder8 "Window8" prog8.bat
</code>```

All progX.bat files contain:

```<code>ECHO Running
</code>```

答:
In despite of the question title, I don't think you want to "synchronize" Batch files, but to "wait for all batch files to finish before continue". I completed a simple search on this site with previous phrase and found a question named: How to wait all batch files to finish before exiting? that I think is the solution you are looking for:

```<code>echo MakeAll.bat starts
(
START /D Folder1 "Window1" prog1.bat
START /D Folder2 "Window2" prog2.bat
START /D Folder3 "Window3" prog3.bat
START /D Folder4 "Window4" prog4.bat
START /D Folder5 "Window5" prog5.bat
) | pause
echo MakeAll.bat ends

echo AssembleAll.bat starts
(
START /D Folder5 "Window5" prog5.bat
START /D Folder6 "Window6" prog6.bat
START /D Folder7 "Window7" prog7.bat
START /D Folder8 "Window8" prog8.bat
) | pause
echo AssembleAll.bat ends
</code>```

For an explanation on the method used, see the linked answer...

Body:
Say I have 5 batch files that need to run simultaneously to save time; these 5 batch files are all currently called from the same MakeAll batch file with:

START /D PATH "Window Name" BATCH_FILE ARGUMENTS

I then have 2 other batch files that need to run when all 5 of the previous group (MakeAll) are done running; these 2 batch files are called 4 times with different arguments from the same AssembleAll batch file with the same command above.

Ideally I'd like to create another batch file called DoAll that first runs MakeAll and waits for the 5 associated processes to finish and then calls AssembleAll.

Code

DoAll.bat:

START /D Folder9 "Window9" MakeAll.bat
:: Wait for the above to finish all 5 windows
START /D Folder10 "Window510" AssembleAll.bat

MakeAll.bat:

START /D Folder1 "Window1" prog1.bat
START /D Folder2 "Window2" prog2.bat
START /D Folder3 "Window3" prog3.bat
START /D Folder4 "Window4" prog4.bat
START /D Folder5 "Window5" prog5.bat

AssembleAll.bat:

START /D Folder5 "Window5" prog5.bat
START /D Folder6 "Window6" prog6.bat
START /D Folder7 "Window7" prog7.bat
START /D Folder8 "Window8" prog8.bat

All progX.bat files contain:

ECHO Running

Body:
In despite of the question title, I don't think you want to "synchronize" Batch files, but to "wait for all batch files to finish before continue". I completed a simple search on this site with previous phrase and found a question named: How to wait all batch files to finish before exiting? that I think is the solution you are looking for:

echo MakeAll.bat starts
(
START /D Folder1 "Window1" prog1.bat
START /D Folder2 "Window2" prog2.bat
START /D Folder3 "Window3" prog3.bat
START /D Folder4 "Window4" prog4.bat
START /D Folder5 "Window5" prog5.bat
) | pause
echo MakeAll.bat ends

echo AssembleAll.bat starts
(
START /D Folder5 "Window5" prog5.bat
START /D Folder6 "Window6" prog6.bat
START /D Folder7 "Window7" prog7.bat
START /D Folder8 "Window8" prog8.bat
) | pause
echo AssembleAll.bat ends

For an explanation on the method used, see the linked answer...


问:
How can I scrape Yahoo Finance by parsing through a text file containing a list of tickers?
I have a text file containing a list of company tickers.

My intention is to be able to scrape Yahoo Finance to get financial data for each of these tickers.

I do not know how to tell Python to go over each individual line in my text file, assign it to a variable and then scrape that particular Yahoo Finance page and retrieve its data and store it, repeating the process for how many tickers are contained in the text file.

I found some code online to be able to scrape data from Yahoo Finance.
Then I tried to add a for loop so that each ticker is added to a symbol variable (see code).

```<code>def scrape_table(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    table = tree.xpath('//table')
    assert len(table) == 1

    df = pd.read_html(lxml.etree.tostring(table[0], method='html'))[0]

    df = df.set_index(0)
    df = df.dropna()
    df = df.transpose()
    df = df.replace('-', '0')

    # The first column should be a date
    df[df.columns[0]] = pd.to_datetime(df[df.columns[0]])
    cols = list(df.columns)
    cols[0] = 'Date'
    df = df.set_axis(cols, axis='columns', inplace=False)

    numeric_columns = list(df.columns)[1::]
    df[numeric_columns] = df[numeric_columns].astype(np.float64)

    return df

symbol = []

tf = open("SMI_tickers.txt")
for line in tf.readlines():
   symbol.append(print(line))

balance_sheet_url = 'https://finance.yahoo.com/quote/' + symbol +
'/balance-sheet?p=' + symbol

df_balance_sheet = scrape_table(balance_sheet_url)
df_balance_sheet
</code>```

The error message I got was

TypeError: can only concatenate str (not "list") to str

My end goal is to be able to import financial data for each of these companies so that I can perform some calculations on each stock.

答:
You were trying to pass a list instead of a string. You need to iterate through all the symbols in your file, which you can do as follows. This code will append the results of the scraping function (which I have not tested) to a list balance_sheets.</p>

```<code>balance_sheets=[]
tf = open("SMI_tickers.txt")
for line in tf.readlines():
    symbol.append(line)
    balance_sheet_url = 'https://finance.yahoo.com/quote/' + line + '/balance-sheet?p=' + line
    balance_sheets.append(scrape_table(balance_sheet_url))
</code>```

Body:
I have a text file containing a list of company tickers.

My intention is to be able to scrape Yahoo Finance to get financial data for each of these tickers.

I do not know how to tell Python to go over each individual line in my text file, assign it to a variable and then scrape that particular Yahoo Finance page and retrieve its data and store it, repeating the process for how many tickers are contained in the text file.

I found some code online to be able to scrape data from Yahoo Finance.
Then I tried to add a for loop so that each ticker is added to a symbol variable (see code).

def scrape_table(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    table = tree.xpath('//table')
    assert len(table) == 1

    df = pd.read_html(lxml.etree.tostring(table[0], method='html'))[0]

    df = df.set_index(0)
    df = df.dropna()
    df = df.transpose()
    df = df.replace('-', '0')

    # The first column should be a date
    df[df.columns[0]] = pd.to_datetime(df[df.columns[0]])
    cols = list(df.columns)
    cols[0] = 'Date'
    df = df.set_axis(cols, axis='columns', inplace=False)

    numeric_columns = list(df.columns)[1::]
    df[numeric_columns] = df[numeric_columns].astype(np.float64)

    return df

symbol = []

tf = open("SMI_tickers.txt")
for line in tf.readlines():
   symbol.append(print(line))

balance_sheet_url = 'https://finance.yahoo.com/quote/' + symbol +
'/balance-sheet?p=' + symbol

df_balance_sheet = scrape_table(balance_sheet_url)
df_balance_sheet

The error message I got was

TypeError: can only concatenate str (not "list") to str

My end goal is to be able to import financial data for each of these companies so that I can perform some calculations on each stock.

Body:
You were trying to pass a list instead of a string. You need to iterate through all the symbols in your file, which you can do as follows. This code will append the results of the scraping function (which I have not tested) to a list balance_sheets.

balance_sheets=[]
tf = open("SMI_tickers.txt")
for line in tf.readlines():
    symbol.append(line)
    balance_sheet_url = 'https://finance.yahoo.com/quote/' + line + '/balance-sheet?p=' + line
    balance_sheets.append(scrape_table(balance_sheet_url))


问:
How can I default to IE for testing my ASP.NET application?
Three fine browsers I have installed: the inimitable Mozilla, the traditional Internet Explorer, and the hot new Chrome. I love them all dearly, but when testing my ASP.NET application, I would prefer to do so using IE.

Please note, I've not deployed this application. I'm merely launching it from the Visual Studio project in which it was conceived. Would someone here be so good as to suggest a way in which I might specify the browser it launches in? Thank you.

答:
Right-click on any .aspx page in Solution Explorer and choose Browse With...

You can then select Internet Explorer from the list and choose 'Set as Default' to make pages open with IE when you press F5.


问:
How to determine when the distance between two lines gets within a certain threshold?
I have a graph with the main data points(blue line) and the maxima (green) and minima (red).

Note that the x-values of the minima and maxima values are not the same, nor are they guaranteed to have the same count of values.

Now my goal is to determine when the distance along the y-axis (integral? sorry, its been a while since calculus in uni) between the maxima and minima lines gets below 10% (or any other arbitrary threshold) from the the average distance along the y-axis.

Here is the code used to generate:

```<code># Finding the min and max
c_max_index = argrelextrema(df.flow.values, np.greater, order=3)
c_min_index = argrelextrema(df.flow.values, np.less, order=3)

df['min_extreme'] = df.flow[c_min_index[0]]
df['max_extreme'] = df.flow[c_max_index[0]]

# Plotting the values for the graph above
plt.plot(df.flow.values)
upper_bound = plt.plot(c_max_index[0], df.flow.values[c_max_index[0]], linewidth=0.8, c='g')
lower_bound = plt.plot(c_min_index[0], df.flow.values[c_min_index[0]], linewidth=0.8, c='r')
</code>```

If it makes a difference, I'm using a Pandas Dataframe, scipy, and matplotlib.

答:
Your problem is that min_extreme and max_extreme are not aligned/defined all the way. We can solve it by interpolate:

```<code># this will interpolate values linearly, i.e data on the upper and lower lines
df = df.interpolate()

# vertical distance between upper and lower lines:
df['dist'] = df.max_extreme - df.min_extreme

# thresholding, thresh can be scalar or series
# thresh = 0.5 -- absolute value
# thresh = df.max_extreme / 2 -- relative to the current max_extreme

thresh = df.dist.quantile(0.5) # larger than 50% of the distances

df['too_far'] = df.dist.gt(thresh)

# visualize:
tmp_df = df[df.too_far]

upper_bound = plt.plot(c_max_index[0], df.flow.values[c_max_index[0]], linewidth=0.8, c='g')
lower_bound = plt.plot(c_min_index[0], df.flow.values[c_min_index[0]], linewidth=0.8, c='r')

df.flow.plot()

plt.scatter(tmp_df.index, tmp_df.min_extreme, s=10)
plt.scatter(tmp_df.index, tmp_df.max_extreme, s=10)
plt.show()
</code>```

Output:

Body:
I have a graph with the main data points(blue line) and the maxima (green) and minima (red).

Note that the x-values of the minima and maxima values are not the same, nor are they guaranteed to have the same count of values.

Now my goal is to determine when the distance along the y-axis (integral? sorry, its been a while since calculus in uni) between the maxima and minima lines gets below 10% (or any other arbitrary threshold) from the the average distance along the y-axis.

Here is the code used to generate:

# Finding the min and max
c_max_index = argrelextrema(df.flow.values, np.greater, order=3)
c_min_index = argrelextrema(df.flow.values, np.less, order=3)

df['min_extreme'] = df.flow[c_min_index[0]]
df['max_extreme'] = df.flow[c_max_index[0]]

# Plotting the values for the graph above
plt.plot(df.flow.values)
upper_bound = plt.plot(c_max_index[0], df.flow.values[c_max_index[0]], linewidth=0.8, c='g')
lower_bound = plt.plot(c_min_index[0], df.flow.values[c_min_index[0]], linewidth=0.8, c='r')

If it makes a difference, I'm using a Pandas Dataframe, scipy, and matplotlib.

Body:
Your problem is that min_extreme and max_extreme are not aligned/defined all the way. We can solve it by interpolate:

# this will interpolate values linearly, i.e data on the upper and lower lines
df = df.interpolate()

# vertical distance between upper and lower lines:
df['dist'] = df.max_extreme - df.min_extreme

# thresholding, thresh can be scalar or series
# thresh = 0.5 -- absolute value
# thresh = df.max_extreme / 2 -- relative to the current max_extreme

thresh = df.dist.quantile(0.5) # larger than 50% of the distances

df['too_far'] = df.dist.gt(thresh)

# visualize:
tmp_df = df[df.too_far]

upper_bound = plt.plot(c_max_index[0], df.flow.values[c_max_index[0]], linewidth=0.8, c='g')
lower_bound = plt.plot(c_min_index[0], df.flow.values[c_min_index[0]], linewidth=0.8, c='r')

df.flow.plot()

plt.scatter(tmp_df.index, tmp_df.min_extreme, s=10)
plt.scatter(tmp_df.index, tmp_df.max_extreme, s=10)
plt.show()

Output:


问:
fatal error: itkMultiScaleHessianBasedMeasureImageFilter.h: No such file or directory #include "itkMultiScaleHessianBasedMeasureImageFilter.h"
I am trying to run the itkMultiScaleHessianBasedMeasureImageFilter program for blood vessels segmentation given in the below link

https://itk.org/ITKExamples/src/Nonunit/Review/SegmentBloodVesselsWithMultiScaleHessianBasedMeasure/Documentation.html

But I am getting the following error.

fatal error: itkMultiScaleHessianBasedMeasureImageFilter.h: No such file or directory

I am unable to understand that for Input, 2D slice/image should give or 3D image series of CT scan?

Also, I tried the code from
https://itk.org/ITKExamples/src/Filtering/ImageFeature/SegmentBloodVessels/Documentation.html

but this is also not working.

Can Someone please provide the solution?

答: With ITK 4.x and earlier, some of the classes were in Review module, which is turned off by default. That means you need to set CMake variable Module_ITKReview to ON when configuring/compiling ITK.


问:
SQLSTATE[HY000] [2002] Permission denied Laravel PDO Driver (credentials working via artisan migrate)
I'm having a lot of trouble with the PDO driver on this new installation

This is the error I get when trying to do any db operation triggered by laravel.

```<code>ext Illuminate\Database\QueryException: SQLSTATE[HY000] [2002] Permission denied (SQL: select * from `users` where `email` = ethan@gmail.com limit 1) in /var/www/html/mypath/vendor/laravel/framework/src/Illuminate/Database/Connection.php:647
</code>```

What's really strange here, is that PDO is enabled in php, and we're using the same credentials that php artisan migrate used to create the tables (so I know credentials, mysql socket are all working)

This is the PDO error from the stack

```<code>at PDO->__construct('mysql:unix_socket=/mnt/volume_sfo2_01/mysql_data/mysqld.sock;dbname=testdb1', 'dbuser1', 'mypassword', array(0, 2, 0, false, false))
in Connector.php line 68
</code>```

Note that I did move the datadirectory of mysql and thus the change for the socket.  This config works running the migrate, so what am I missing to get it working with the laravel PDO driver?

On ubuntu server 16 as well.
Nginx + php7.1
apparmor has been disabled additional just for this testing.  Any ideas would be greatly appreciated.

答:
I had similar issue on Laravel/Lumen 5.5 / CentOS7 / php71 / mariaDB

using the 'setenforce to test' strategy outlined in the solution here, Permissions Issue with Laravel on CentOS you might want to test for the influence of SElinux.

I was connecting via port 3306 and was able to resolve with insight from this problem report (https://bugzilla.redhat.com/show_bug.cgi?id=1245295) that lead me to

```<code>sudo setsebool httpd_can_network_connect_db 1
</code>```

to make this change permenant you need to add -P switch

sudo setsebool -P httpd_can_network_connect_db 1

Body:
I'm having a lot of trouble with the PDO driver on this new installation

This is the error I get when trying to do any db operation triggered by laravel.

ext Illuminate\Database\QueryException: SQLSTATE[HY000] [2002] Permission denied (SQL: select * from `users` where `email` = ethan@gmail.com limit 1) in /var/www/html/mypath/vendor/laravel/framework/src/Illuminate/Database/Connection.php:647

What's really strange here, is that PDO is enabled in php, and we're using the same credentials that php artisan migrate used to create the tables (so I know credentials, mysql socket are all working)

This is the PDO error from the stack

at PDO->__construct('mysql:unix_socket=/mnt/volume_sfo2_01/mysql_data/mysqld.sock;dbname=testdb1', 'dbuser1', 'mypassword', array(0, 2, 0, false, false))
in Connector.php line 68

Note that I did move the datadirectory of mysql and thus the change for the socket.  This config works running the migrate, so what am I missing to get it working with the laravel PDO driver?

On ubuntu server 16 as well.
Nginx + php7.1
apparmor has been disabled additional just for this testing.  Any ideas would be greatly appreciated.

Body:
I had similar issue on Laravel/Lumen 5.5 / CentOS7 / php71 / mariaDB

using the 'setenforce to test' strategy outlined in the solution here, Permissions Issue with Laravel on CentOS you might want to test for the influence of SElinux.

I was connecting via port 3306 and was able to resolve with insight from this problem report (https://bugzilla.redhat.com/show_bug.cgi?id=1245295) that lead me to

sudo setsebool httpd_can_network_connect_db 1

to make this change permenant you need to add -P switch

sudo setsebool -P httpd_can_network_connect_db 1


问:
How to fix "value used in formula is wrong data type" error when trying to convert a range into an array?
I'm making a udf to convert the entered range into an array, and if done successfully, the function will return "worked" into the cell. However, it keeps returning #VALUE!, and says:

"a value used in the formula is of the wrong data type."

```<code>Function test(rng As Range) As String

Dim Arr() As Variant
Arr = Range(rng)

test="worked"

End Function
</code>```

答:
use:</p>

```<code>Function test(rng As Range) As String

    Dim Arr As Variant
    Arr = rng

    test = "worked"

End Function
</code>```

Body:
I'm making a udf to convert the entered range into an array, and if done successfully, the function will return "worked" into the cell. However, it keeps returning #VALUE!, and says:

"a value used in the formula is of the wrong data type."

Function test(rng As Range) As String

Dim Arr() As Variant
Arr = Range(rng)

test="worked"

End Function

Body:
use:

Function test(rng As Range) As String

    Dim Arr As Variant
    Arr = rng

    test = "worked"

End Function


问:
Creating an editable HTML table from 2D array
So I am trying to make a flashcards website, where users can add, edit, and delete flashcards. There are two cards - front and back. The user can already add words, but cannot edit or delete them. For the purposes of this question I will use an example array:

```<code>var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]]
</code>```

But I would like a more user-friendly way to edit the flashcards, preferably using a table like this:

```<code><table>
  <tr>
    <th>Front</th>
    <th>Back</th>
  </tr>
  <tr>
    <td><input type="text" name="flashcard" value="Uomo"> </td>
    <td><input type="text" name="flashcard" value="Man"></td>
  </tr>
    <tr>
    <td><input type="text" name="flashcard" value="Donna"></td>
    <td><input type="text" name="flashcard" value="Woman"></td>
  </tr>
      <tr>
    <td><input type="text" name="flashcard" value="Ragazzo"></td>
    <td><input type="text" name="flashcard" value="Boy"></td>
  </tr>
</table>

<button type="button">Add more</button>
<br>
<button type="button">Save changes</button>
</code>```

So they can update their flashcards editing the input fields, or clicking "add more" and it creating a new row. Clicking "save changes" updates the array to the content of the table.

I don't mind it not being a HTML table per se, but something that is easy to edit for the user.

I just cannot figure out the best way to approach this. Any advice?

答:
i think you can use In-Place Editing System and there's a good tutorial i found
Create an In-Place Editing System</p>

Body:
So I am trying to make a flashcards website, where users can add, edit, and delete flashcards. There are two cards - front and back. The user can already add words, but cannot edit or delete them. For the purposes of this question I will use an example array:

var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]]

But I would like a more user-friendly way to edit the flashcards, preferably using a table like this:

    Front
    Back

    <input type="text" name="flashcard" value="Uomo">
    <input type="text" name="flashcard" value="Man">

    <input type="text" name="flashcard" value="Donna">
    <input type="text" name="flashcard" value="Woman">

    <input type="text" name="flashcard" value="Ragazzo">
    <input type="text" name="flashcard" value="Boy">

<button type="button">Add more</button>

<button type="button">Save changes</button>

So they can update their flashcards editing the input fields, or clicking "add more" and it creating a new row. Clicking "save changes" updates the array to the content of the table.

I don't mind it not being a HTML table per se, but something that is easy to edit for the user.

I just cannot figure out the best way to approach this. Any advice?


问:
Chrome/Firefox opens PDF in new tab and does not save it in headless mode (Selenium+Python)
I have an issue with headless chrome when performing a test: a PDF file opens in a new tab when clicking on a button. If I run the test in NON-headless mode, all is fine. But when try to do the same in headless - file is not downloading.

```<code>options = ChromeOptions()
            options.add_argument('--no-sandbox')
            options.add_argument('--kiosk-printing')
            options.add_argument('--test-type')
            options.add_argument('--disable-infobars')
            options.add_argument('disable-gpu')
            options.add_argument('--verbose')
            options.add_argument('--disable-extensions')
            options.add_argument('--ignore-certificate-errors')
            options.add_experimental_option("prefs", {
                "profile.default_content_settings.popups": 0,
                "download.default_directory": dwnld_path,
                "download.prompt_for_download": False,
                "download.directory_upgrade": True,
                "safebrowsing.enabled": False,
                "plugins.always_open_pdf_externally": True,
                "plugins.plugins_disabled": ["Chrome PDF Viewer"]
            })
</code>```

I also found that:

```<code>wd.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')

params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': dwnld_path}}
        command_result = wd.execute("send_command", params)
</code>```

But it helps only if I get a request to download in headless mode, not if the file opens in browser.

答:
Try saving the url of the PDF file and download it with requests library, I think it will work.

Like this:

```<code>import urllib3
import PyPDF2
import certifi
import io

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
pdf_url = "http:\\XXXXXX.pdf"
r3 = http.request('GET', pdf_url)
with io.BytesIO(r3.data) as open_pdf_file:
      read_pdf = PyPDF2.PdfFileReader(open_pdf_file)
      num_pages = read_pdf.getNumPages()
</code>```

and then we need the second part of the code that you need to save pdf in a similar way

Body:
I have an issue with headless chrome when performing a test: a PDF file opens in a new tab when clicking on a button. If I run the test in NON-headless mode, all is fine. But when try to do the same in headless - file is not downloading.

options = ChromeOptions()
            options.add_argument('--no-sandbox')
            options.add_argument('--kiosk-printing')
            options.add_argument('--test-type')
            options.add_argument('--disable-infobars')
            options.add_argument('disable-gpu')
            options.add_argument('--verbose')
            options.add_argument('--disable-extensions')
            options.add_argument('--ignore-certificate-errors')
            options.add_experimental_option("prefs", {
                "profile.default_content_settings.popups": 0,
                "download.default_directory": dwnld_path,
                "download.prompt_for_download": False,
                "download.directory_upgrade": True,
                "safebrowsing.enabled": False,
                "plugins.always_open_pdf_externally": True,
                "plugins.plugins_disabled": ["Chrome PDF Viewer"]
            })

I also found that:

wd.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')

params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': dwnld_path}}
        command_result = wd.execute("send_command", params)

But it helps only if I get a request to download in headless mode, not if the file opens in browser.

Body:
Try saving the url of the PDF file and download it with requests library, I think it will work.

Like this:

import urllib3
import PyPDF2
import certifi
import io

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
pdf_url = "http:\\XXXXXX.pdf"
r3 = http.request('GET', pdf_url)
with io.BytesIO(r3.data) as open_pdf_file:
      read_pdf = PyPDF2.PdfFileReader(open_pdf_file)
      num_pages = read_pdf.getNumPages()

and then we need the second part of the code that you need to save pdf in a similar way


问:
What is the meaning of this []?
I can't understand the reason of using [0] in front of dish.id and dish.featured in the following code:

```<code>import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';

@Injectable()
export class DishService {

  constructor() { }

  getDishes(): Dish[] {
    return DISHES;
  }

  getDish(id: number): Dish {
    return DISHES.filter((dish) => (dish.id === id))[0];
  }

  getFeaturedDish(): Dish {
    return DISHES.filter((dish) => dish.featured)[0];
  }
}
</code>```

This is the  Dish class:

```<code>import { Comment } from './comment';

export class Dish {
    id: number;
    name: string;
    image: string;
    category: string;
    label: string;
    price: string;
    featured: boolean;
    description: string;
    comments: Comment[];
}
</code>```

答:
Read this .filter(). The reason why the dish.id and dish.featured has [0] in the end because filter always returns the result in an array.

var words = ['a','spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length == 1);

console.log(result);```

Title: What is the meaning of this []?

Body:
I can't understand the reason of using [0] in front of dish.id and dish.featured in the following code:

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';

@Injectable()
export class DishService {

  constructor() { }

  getDishes(): Dish[] {
    return DISHES;
  }

  getDish(id: number): Dish {
    return DISHES.filter((dish) => (dish.id === id))[0];
  }

  getFeaturedDish(): Dish {
    return DISHES.filter((dish) => dish.featured)[0];
  }
}

This is the  Dish class:

import { Comment } from './comment';

export class Dish {
    id: number;
    name: string;
    image: string;
    category: string;
    label: string;
    price: string;
    featured: boolean;
    description: string;
    comments: Comment[];
}


问:
Collapsible text height in pure css
Here's a snippet of what I have so far:

#expand {
  height: 0px;
  width: 0px;
  overflow: hidden;
  transition: height 0.5s, width 0.5s ease-in-out;
  background: #000000;
  color: #FFF;
}

input {
  display: none;
  visibility: hidden;
}

input:checked+label+#expand {
  height: 150px;
  width: 600px;
}

#toggle:checked~label::before {
  content: "-";
}

/* useless styling */

main {
  background: #EEE;
  width: 100px;
  margin: 20px auto;
  padding: 10px 0;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
}

section {
  padding: 0 20px;
}

label {
  display: block;
  padding: 0.5em;
  text-align: center;
  border-bottom: 1px solid #CCC;
  color: #666;
}

label:hover {
  color: #000;
}

label::before {
  font-family: Consolas, monaco, monospace;
  font-weight: bold;
  font-size: 15px;
  content: "+";
  vertical-align: text-top;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <input id="toggle" type="checkbox" />
  <label for="toggle">Hidden Kitten</label>
  <div id="expand">
    <section>
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
        desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    </section>
  </div>

  <input id="toggle1" type="checkbox" />
  <label for="toggle1">Hidden Kitten</label>
  <div id="expand">
    <section>
      <p>mew</p>
    </section>
  </div>
</main></code>```

You can see in the input:checked + label + #expand selector, the width and height are fixed.

I can set the width to a percentage just fine, but if I try to set the height to a percentage it ruins the animation. How do I fix this? I do not know the text's height beforehand. I would like to use only CSS for this.

答:
You can try using max-height instead of height.

#expand {
  max-height: 0px;
  width: 0px;
  overflow: hidden;
  transition: max-height 0.5s, width 0.5s ease-in-out;
  background: #000000;
  color: #FFF;
}

input {
  display: none;
  visibility: hidden;
}

input:checked+label+#expand {
  max-height: 150px;
  width: 600px;
}

#toggle:checked~label::before {
  content: "-";
}

/* useless styling */

main {
  background: #EEE;
  width: 100px;
  margin: 20px auto;
  padding: 10px 0;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
}

section {
  padding: 0 20px;
}

label {
  display: block;
  padding: 0.5em;
  text-align: center;
  border-bottom: 1px solid #CCC;
  color: #666;
}

label:hover {
  color: #000;
}

label::before {
  font-family: Consolas, monaco, monospace;
  font-weight: bold;
  font-size: 15px;
  content: "+";
  vertical-align: text-top;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <input id="toggle" type="checkbox" />
  <label for="toggle">Hidden Kitten</label>
  <div id="expand">
    <section>
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
        desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    </section>
  </div>

  <input id="toggle1" type="checkbox" />
  <label for="toggle1">Hidden Kitten</label>
  <div id="expand">
    <section>
      <p>mew</p>
    </section>
  </div>
</main></code>```

Title: Collapsible text height in pure css

Body:
Here's a snippet of what I have so far:

#expand {
  height: 0px;
  width: 0px;
  overflow: hidden;
  transition: height 0.5s, width 0.5s ease-in-out;
  background: #000000;
  color: #FFF;
}

input {
  display: none;
  visibility: hidden;
}

input:checked+label+#expand {
  height: 150px;
  width: 600px;
}

#toggle:checked~label::before {
  content: "-";
}

/* useless styling */

main {
  background: #EEE;
  width: 100px;
  margin: 20px auto;
  padding: 10px 0;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
}

section {
  padding: 0 20px;
}

label {
  display: block;
  padding: 0.5em;
  text-align: center;
  border-bottom: 1px solid #CCC;
  color: #666;
}

label:hover {
  color: #000;
}

label::before {
  font-family: Consolas, monaco, monospace;
  font-weight: bold;
  font-size: 15px;
  content: "+";
  vertical-align: text-top;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%);
}

  <input id="toggle" type="checkbox" />
  Hidden Kitten

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
        desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

  <input id="toggle1" type="checkbox" />
  Hidden Kitten

mew

You can see in the input:checked + label + #expand selector, the width and height are fixed.

I can set the width to a percentage just fine, but if I try to set the height to a percentage it ruins the animation. How do I fix this? I do not know the text's height beforehand. I would like to use only CSS for this.

Body:
You can try using max-height instead of height.

#expand {
  max-height: 0px;
  width: 0px;
  overflow: hidden;
  transition: max-height 0.5s, width 0.5s ease-in-out;
  background: #000000;
  color: #FFF;
}

input {
  display: none;
  visibility: hidden;
}

input:checked+label+#expand {
  max-height: 150px;
  width: 600px;
}

#toggle:checked~label::before {
  content: "-";
}

/* useless styling */

main {
  background: #EEE;
  width: 100px;
  margin: 20px auto;
  padding: 10px 0;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
}

section {
  padding: 0 20px;
}

label {
  display: block;
  padding: 0.5em;
  text-align: center;
  border-bottom: 1px solid #CCC;
  color: #666;
}

label:hover {
  color: #000;
}

label::before {
  font-family: Consolas, monaco, monospace;
  font-weight: bold;
  font-size: 15px;
  content: "+";
  vertical-align: text-top;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%);
}

<main>
  <input id="toggle" type="checkbox" />
  <label for="toggle">Hidden Kitten</label>
  <div id="expand">
    <section>
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
        desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    </section>
  </div>

  <input id="toggle1" type="checkbox" />
  <label for="toggle1">Hidden Kitten</label>
  <div id="expand">
    <section>
      <p>mew</p>
    </section>
  </div>
</main>


问:
Measure elapsed time in Swift
How can we measure the time elapsed for running a function in Swift? I am trying to display the elapsed time like this: "Elapsed time is .05 seconds". Saw that in Java, we can use System.nanoTime(), are there any equivalent methods available in Swift to accomplish this?

Please have a look at the sample program:

func isPrime(_ number: Int) -> Bool {
    var i = 0;
    for i=2; i<number; i++ {
        if number % i == 0, i != 0 {
            return false
        }
    }
    return true
}

var number = 5915587277

if isPrime(number) {
    print("Prime number")
} else {
    print("NOT a prime number")
}
```

答:
Just Copy and Paste this function. Written in swift 5.
Copying JeremyP here.

```<code>func calculateTime(block : (() -> Void)) {
        let start = DispatchTime.now()
        block()
        let end = DispatchTime.now()
        let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds
        let timeInterval = Double(nanoTime) / 1_000_000_000
        print("Time: \(timeInterval) seconds")
    }
</code>```

Use it like

```<code>calculateTime {
     exampleFunc()// function whose execution time to be calculated
}
</code>```

Title: Measure elapsed time in Swift

Body:
Just Copy and Paste this function. Written in swift 5.
Copying JeremyP here.

func calculateTime(block : (() -> Void)) {
        let start = DispatchTime.now()
        block()
        let end = DispatchTime.now()
        let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds
        let timeInterval = Double(nanoTime) / 1_000_000_000
        print("Time: \(timeInterval) seconds")
    }

Use it like

calculateTime {
     exampleFunc()// function whose execution time to be calculated
}


问:
Is `ng serve` command suitable for production?
I'm building a small project using Angular 7.  When you run

```<code>ng serve
</code>```

and a NodeJS server is spun up to handle requests, does each request block until processing is complete?  We are trying to evaluate how effective using this in production would be as opposed to using a more traditional application server.

答:
When using ng serve, you are spawning a backend nodejs environment with a web server to handle requests towards your angular application. That's great for reloading and quick startup when developing. But needing such resources for static pages is unnecessary.

At the end of the day Angular is just a framework telling you its opinion on how to build an SPA. No matter the framework or library you use, you will always end up with an index.xxx, Javascript files and other resource files from vendors or internally. Only these matters to the browser loading the webpage.

Hence, you need to build your app to generate the static files that will be served (i.e. ng build --prod). Then you have 2 good options:

Choose a web server that will serve the files (i.e. nginx) on a dedicated server (or even container).

Place the files behind a CDN provider. Since they are static, they will be cached and served to a browser requesting them based on its location.

I would opt for #2 as opposed to #1 forcing you to keep running resources (CPU, RAM, HDD) for files that will be requested not that often. I say not often because your SPA will be handling all routes within itself in the client's browser (and minimum once a day will request a cache refresh).

Body:
I'm building a small project using Angular 7.  When you run

ng serve

and a NodeJS server is spun up to handle requests, does each request block until processing is complete?  We are trying to evaluate how effective using this in production would be as opposed to using a more traditional application server.


答:
Filter returns an array so when you use [0] It means take the first selection.
You can read more here: Filter

Title: What is the meaning of this []?


问:
Is there a way to disable all warnings with a pragma?
I've started a new project and have decided to make sure it builds cleanly with the /Wall option enabled. The only problem is not all 3rd party libraries (like boost) compile without warnings, so I've resorted to doing this in a shared header:

```<code>#pragma warning(push)

#pragma warning(disable:4820)
#pragma warning(disable:4619)
#pragma warning(disable:4668)
#pragma warning(disable:4625)
#pragma warning(disable:4626)
#pragma warning(disable:4571)
#pragma warning(disable:4347)
#pragma warning(disable:4640)
#pragma warning(disable:4365)
#pragma warning(disable:4710)
#pragma warning(disable:4820)
#pragma warning(disable:4350)
#pragma warning(disable:4686)
#pragma warning(disable:4711)
#pragma warning(disable:4548)

#include <boost/array.hpp>
#include <boost/assert.hpp>
#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/function.hpp>
#include <boost/integer.hpp>
#include <boost/optional.hpp>
#include <boost/regex.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/utility.hpp>
#include <boost/variant.hpp>

#pragma warning(pop)
</code>```

This works well enough, but every time I add new boost headers I have to add whatever warnings they generate to the list. Is there a way to say disable all warnings for this stretch of code?

答:
Using the technique described in the Assaf Lavie's answer it is possible to create helper macros:

```<code>#define DISABLE_ALL_WARNINGS_BEGIN \
    __pragma(warning(push, 0))

#define DISABLE_ALL_WARNINGS_END \
    __pragma(warning(pop))
</code>```

They can be used in the following way (online demo):

```<code>DISABLE_ALL_WARNINGS_BEGIN
void foo(int a)
{
    // this function should generate the following warning
    // "warning C4100: 'a': unreferenced formal parameter"
    // unless it is wrapped inside "DISABLE_ALL_WARNINGS" section
}
DISABLE_ALL_WARNINGS_END
</code>```

OwnerDisplayName: Ferruccio

ContentLicense: CC BY-SA 2.5

Body:
I've started a new project and have decided to make sure it builds cleanly with the /Wall option enabled. The only problem is not all 3rd party libraries (like boost) compile without warnings, so I've resorted to doing this in a shared header:

#pragma warning(push)

#pragma warning(disable:4820)
#pragma warning(disable:4619)
#pragma warning(disable:4668)
#pragma warning(disable:4625)
#pragma warning(disable:4626)
#pragma warning(disable:4571)
#pragma warning(disable:4347)
#pragma warning(disable:4640)
#pragma warning(disable:4365)
#pragma warning(disable:4710)
#pragma warning(disable:4820)
#pragma warning(disable:4350)
#pragma warning(disable:4686)
#pragma warning(disable:4711)
#pragma warning(disable:4548)

#include <boost/array.hpp>
#include <boost/assert.hpp>
#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/function.hpp>
#include <boost/integer.hpp>
#include <boost/optional.hpp>
#include <boost/regex.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/utility.hpp>
#include <boost/variant.hpp>

#pragma warning(pop)

This works well enough, but every time I add new boost headers I have to add whatever warnings they generate to the list. Is there a way to say disable all warnings for this stretch of code?

Body:
Using the technique described in the Assaf Lavie's answer it is possible to create helper macros:

#define DISABLE_ALL_WARNINGS_BEGIN \
    __pragma(warning(push, 0))

#define DISABLE_ALL_WARNINGS_END \
    __pragma(warning(pop))

They can be used in the following way (online demo):

DISABLE_ALL_WARNINGS_BEGIN
void foo(int a)
{
    // this function should generate the following warning
    // "warning C4100: 'a': unreferenced formal parameter"
    // unless it is wrapped inside "DISABLE_ALL_WARNINGS" section
}
DISABLE_ALL_WARNINGS_END


问:
In JSX How to redirect on Handlesubmit from DataPicker?
I am passing the date picked to the this.state.value Getting a time stamp of Midnight that day, but I can not seem to get it to render a new page so I can build the booking page. Where it takes the time stamp and checks for available times that day. When I did return the Handlesubmit on a half successful rerender I got a white page and back to the main app page with a blank date to choose again.

I have tried to build this as a functional component in the handleSubmit But also tried to return a component from the handleSubmit.

Here is the last failed to compile attempt and the last successful compile

```<code> handleSubmit(event) {
    render(
      {
      const {bookingTime} = this.state.value;
      if (bookingTime) {
        return <Redirect to='/Bookingpage' />;
        }
      }
    event.preventDefault();
  }
</code>```

This fail was from doing something similar to https://github.com/salsita/redux-form-actions/issues/2#issuecomment-318774722

While this is the half successful runs code (Just a White Blank page for about 1s)

```<code>handleSubmit(event) {
    return <h1>{this.state.value}</h1>;
    event.preventDefault();
  }
</code>```

This is the last Successful run on StackBlitz
Check the components folder for and tool bar for files directly related to problem
https://react-dnudvg.stackblitz.io/
Please note the code is there but its not building the app.

I expected for this run render a new page with one
{this.state.value}
 as defined by the date picker

答:
It looks like the issue here is mixing up logic that should be rendered with logic that can go in an event handler method. In your first example, render is not a valid method that can be called from within handleSubmit, and in your second example, handleSubmit should not return components to be rendered.

You can get at your desired functionality by creating a state variable that indicates whether the user has submitted yet. Then you can check that variable when rendering (note that rendering is the return part of a functional component or the render method of a stateful component.

For example:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: null, // for the date picker
            wasSubmitted: false,
        }
    }

    handleSubmit = event => {
        event.preventDefault();
        this.setState({wasSubmitted: true});
    }

    render() {
        const { value, wasSubmitted } = this.state;

        if (wasSubmitted) {
            return <Redirect to='/Bookingpage' />
        } else {
            return //... your normal component
        }
    }
}
```

Body:
I am passing the date picked to the this.state.value Getting a time stamp of Midnight that day, but I can not seem to get it to render a new page so I can build the booking page. Where it takes the time stamp and checks for available times that day. When I did return the Handlesubmit on a half successful rerender I got a white page and back to the main app page with a blank date to choose again.

I have tried to build this as a functional component in the handleSubmit But also tried to return a component from the handleSubmit.

Here is the last failed to compile attempt and the last successful compile

 handleSubmit(event) {
    render(
      {
      const {bookingTime} = this.state.value;
      if (bookingTime) {
        return <Redirect to='/Bookingpage' />;
        }
      }
    event.preventDefault();
  }

This fail was from doing something similar to https://github.com/salsita/redux-form-actions/issues/2#issuecomment-318774722

While this is the half successful runs code (Just a White Blank page for about 1s)

handleSubmit(event) {
    return
{this.state.value}
;
    event.preventDefault();
  }

This is the last Successful run on StackBlitz
Check the components folder for and tool bar for files directly related to problem
https://react-dnudvg.stackblitz.io/
Please note the code is there but its not building the app.

I expected for this run render a new page with one
{this.state.value}
 as defined by the date picker


问:
Android - What is the name of this button?
When the soft keyboard is active, the back button is switched to this one

What is the name of the button? And what is the method that is called after pressing it?

答:
It's the same button, it just changes it's shape. Usually it will change it's function from going back to te previous activity to closing the keyboard.
The method it calls usually is onBackPressed() but in this case the keyboard will consume it's call, it will go to the onEditorAction() inside OnEditorActionListener, if you want to know how to intercept the action usually consumed by the keyboard you can read more in Intercept back button from soft keyboard


问:
fusionauth python client ModuleNotFoundError
when I follow https://github.com/FusionAuth/fusionauth-python-client and try to get fusionauth-client work, it fails to missing python module. Can you point me in right direction?

```<code>$ sudo pip3 install fusionauth-client
[sudo] heslo pro mlich:
Collecting fusionauth-client
  Downloading https://files.pythonhosted.org/packages/d6/88/da201734fb5898beb0ec34cc4dd132296f3465da85768ea1979669ef2103/fusionauth-client-1.6.0.tar.gz
Installing collected packages: fusionauth-client
  Running setup.py install for fusionauth-client ... done
Successfully installed fusionauth-client-1.6.0

$ python3
Python 3.7.0 (default, Sep 20 2018, 07:47:02)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from fusionauth.fusionauth_client import FusionAuthClient
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'fusionauth'
</code>```

I use Ubuntu 16.04

答: This issue was discovered recently and was resolved. Could you try uninstalling and reinstalling the package?</p>

Body:
when I follow https://github.com/FusionAuth/fusionauth-python-client and try to get fusionauth-client work, it fails to missing python module. Can you point me in right direction?

$ sudo pip3 install fusionauth-client
[sudo] heslo pro mlich:
Collecting fusionauth-client
  Downloading https://files.pythonhosted.org/packages/d6/88/da201734fb5898beb0ec34cc4dd132296f3465da85768ea1979669ef2103/fusionauth-client-1.6.0.tar.gz
Installing collected packages: fusionauth-client
  Running setup.py install for fusionauth-client ... done
Successfully installed fusionauth-client-1.6.0

$ python3
Python 3.7.0 (default, Sep 20 2018, 07:47:02)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from fusionauth.fusionauth_client import FusionAuthClient
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'fusionauth'

I use Ubuntu 16.04


问:
Java regex to replace in between text using a pattern
I am a newbie to Java regex. I have a long string which contains text like this(Below is only the part of my string which I would like to replace):

```<code>href="javascript:openWin('Images/DCRMBex_01B_ex01.jpg',480,640)"
href="javascript:openWin('Images/DCRMBex_01A_ex01.jpg',480,640)"
href="javascript:openWin('Images/DCRMBex_06A_ex06.jpg',480,640)"
</code>```

I would like to replace

```<code>Images
</code>```

with

```<code>http://google.com/Images
</code>```

For eg. my output should look like this:

```<code>href="javascript:openWin('http://google.com/Images/DCRMBex_01B_ex01.jpg',480,640)"
</code>```

Below is my Java program:

```<code>import java.io.FileReader;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main2 {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner in = new Scanner(new FileReader("C:\\Projects\\input.txt"));

        StringBuilder sb = new StringBuilder();
        while (in.hasNext()) {
            sb.append(in.next());
        }
        String patternString = "href=\"javascript:openWin(.+?)\"";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(sb);
        while (matcher.find()) {
            //System.out.println(matcher.group(1));
            //System.out.println(matcher.group(1).replaceAll("Images", "http://google.com/Images"));
            matcher.group(1).replaceAll("Images", "http://google.com/Images");

        }
        System.out.println(sb);
    }
}
</code>```

Below is my input file(input.txt). This is only a part of my file. The file is too long to paste here:

```<code> <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_01_ex01.pdf"><b>Example 1: Bible (Rusch)</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_01A_ex01.jpg',480,640)">Figure 1A. First page of text</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_01B_ex01.jpg',480,640)">Figure 1B. Source of supplied title</a></td>
                            <td valign="top">  </td>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_06_ex06.pdf"><b>Example 6: Angelo Carletti</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_06A_ex06.jpg',480,640)">Figure 6A. Title page</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_06B_ex06.jpg',480,640)">Figure 6B. Colophon showing use of i/j and u/v</a></td>
                          </tr>
                          <tr>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_02_ex02.pdf"><b>Example 2: Greek anthology</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_02A_ex02.jpg',480,640)">Figure 2A. First page of text</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_02B_ex02.jpg',480,640)">Figure 2B. Colophon</a></td>
                            <td valign="top">  </td>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_07_ex07.pdf"><b>Example 7: Erasmus</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_07A_ex07.jpg',480,640)">Figure 7A. Title page</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_07B_ex07.jpg',480,640)">Figure 7B. Colophon</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_07C_ex07.jpg',640,480)">Figure 7C. Running title</a></td>
                          </tr>
                          <tr>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_03_ex03.pdf"><b>Example 3: Heytesbury</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_03A_ex03.jpg',480,640)">Figure 3A. Title page</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_03B_ex03.jpg',480,640)">Figure 3B. Colophon showing use of i/j and u/v</a></td>
                            <td valign="top">  </td>
                            <td valign="top"><a href="http://www.google.com/cds/desktop/documents/DCRMBex/DCRMBex_08_ex08.pdf"><b>Example 8: Pliny</b></a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_08A_ex08.jpg',480,640)">Figure 8A. Title page</a> ï¿½ <a href="javascript:openWin('Images/DCRMBex_08B_ex08.jpg',480,640)">Figure 8B. Colophon</a></td>
</code>```

Output:

1) System.out.println(matcher.group(1))

```<code>('Images/DCRMBex_05_ex05.jpg',480,640)
</code>```

2)System.out.println(matcher.group(1).replaceAll("Images","http://google.com/Images"));

```<code> ('http://google.com/Images/DCRMBex_05_ex05.jpg',480,640)
</code>```

But when I print my struingbuilder, it doesn't show any replacement. What I am doing wrong here? Any help is appreciated. Thanks

答:
I would recommend using Files.lines() and Java Steam to modify the input. With your actual input you also don't need a regex:

```<code>try (Stream<String> lines = Files.lines(Paths.get("input.txt"))) {
    String result = lines
            .map(line -> line.replace("Images", "http://google.com/Images"))
            .collect(Collectors.joining("\n"));
    System.out.println(result);
}
</code>```

If you really want to use a regex I would recommend to use a pattern outside the loop, because String.replaceAll() internally compiles the pattern every time you call it. So the performance is much better if you do not do Pattern.compile() for each line:

```<code>Pattern pattern = Pattern.compile("(href=\"javascript:openWin.*)(Images.*\")");
try (Stream<String> lines = Files.lines(Paths.get("input.txt"))) {
    String result = lines
            .map(pattern::matcher)
            .map(matcher -> matcher.replaceAll("$1http://google.com/$2"))
            .collect(Collectors.joining("\n"));
    System.out.println(result);
}
</code>```

Using this regex for replacement it will create two groups (between ()). You can use this groups in your replacement string by using $index. So $1 will insert the first group.

The result in both cases will be:

```<code>href="javascript:openWin(&#39;http://google.com/Images/DCRMBex_01B_ex01.jpg&#39;,480,640)"
href="javascript:openWin(&#39;http://google.com/Images/DCRMBex_01A_ex01.jpg&#39;,480,640)"
href="javascript:openWin(&#39;http://google.com/Images/DCRMBex_06A_ex06.jpg&#39;,480,640)"
</code>```

Body:
I am a newbie to Java regex. I have a long string which contains text like this(Below is only the part of my string which I would like to replace):

href="javascript:openWin(&#39;Images/DCRMBex_01B_ex01.jpg&#39;,480,640)"
href="javascript:openWin(&#39;Images/DCRMBex_01A_ex01.jpg&#39;,480,640)"
href="javascript:openWin(&#39;Images/DCRMBex_06A_ex06.jpg&#39;,480,640)"

I would like to replace

Images

with

http://google.com/Images

For eg. my output should look like this:

href="javascript:openWin(&#39;http://google.com/Images/DCRMBex_01B_ex01.jpg&#39;,480,640)"

Below is my Java program:

import java.io.FileReader;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main2 {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner in = new Scanner(new FileReader("C:\\Projects\\input.txt"));

        StringBuilder sb = new StringBuilder();
        while (in.hasNext()) {
            sb.append(in.next());
        }
        String patternString = "href=\"javascript:openWin(.+?)\"";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(sb);
        while (matcher.find()) {
            //System.out.println(matcher.group(1));
            //System.out.println(matcher.group(1).replaceAll("Images", "http://google.com/Images"));
            matcher.group(1).replaceAll("Images", "http://google.com/Images");

        }
        System.out.println(sb);
    }
}

Below is my input file(input.txt). This is only a part of my file. The file is too long to paste here:

 Example 1: Bible (Rusch) ï¿½ Figure 1A. First page of text ï¿½ Figure 1B. Source of supplied title
                            &nbsp;&nbsp;
                            Example 6: Angelo Carletti ï¿½ Figure 6A. Title page ï¿½ Figure 6B. Colophon showing use of i/j and u/v

                            Example 2: Greek anthology ï¿½ Figure 2A. First page of text ï¿½ Figure 2B. Colophon
                            &nbsp;&nbsp;
                            Example 7: Erasmus ï¿½ Figure 7A. Title page ï¿½ Figure 7B. Colophon ï¿½ Figure 7C. Running title

                            Example 3: Heytesbury ï¿½ Figure 3A. Title page ï¿½ Figure 3B. Colophon showing use of i/j and u/v
                            &nbsp;&nbsp;
                            Example 8: Pliny ï¿½ Figure 8A. Title page ï¿½ Figure 8B. Colophon

Output:

1) System.out.println(matcher.group(1))

(&#39;Images/DCRMBex_05_ex05.jpg&#39;,480,640)

2)System.out.println(matcher.group(1).replaceAll("Images","http://google.com/Images"));

 (&#39;http://google.com/Images/DCRMBex_05_ex05.jpg&#39;,480,640)

But when I print my struingbuilder, it doesn't show any replacement. What I am doing wrong here? Any help is appreciated. Thanks

Body:
I would recommend using Files.lines() and Java Steam to modify the input. With your actual input you also don't need a regex:

try (Stream<String> lines = Files.lines(Paths.get("input.txt"))) {
    String result = lines
            .map(line -> line.replace("Images", "http://google.com/Images"))
            .collect(Collectors.joining("\n"));
    System.out.println(result);
}

If you really want to use a regex I would recommend to use a pattern outside the loop, because String.replaceAll() internally compiles the pattern every time you call it. So the performance is much better if you do not do Pattern.compile() for each line:

Pattern pattern = Pattern.compile("(href=\"javascript:openWin.*)(Images.*\")");
try (Stream<String> lines = Files.lines(Paths.get("input.txt"))) {
    String result = lines
            .map(pattern::matcher)
            .map(matcher -> matcher.replaceAll("$1http://google.com/$2"))
            .collect(Collectors.joining("\n"));
    System.out.println(result);
}

Using this regex for replacement it will create two groups (between ()). You can use this groups in your replacement string by using $index. So $1 will insert the first group.

The result in both cases will be:

href="javascript:openWin(&amp;#39;http://google.com/Images/DCRMBex_01B_ex01.jpg&amp;#39;,480,640)"
href="javascript:openWin(&amp;#39;http://google.com/Images/DCRMBex_01A_ex01.jpg&amp;#39;,480,640)"
href="javascript:openWin(&amp;#39;http://google.com/Images/DCRMBex_06A_ex06.jpg&amp;#39;,480,640)"


问:
Can etree.XMLParser in recover mode still throw a parse error?
I have a utility method that parses XML using a parser created as etree.XMLParser(recover=True). I would like to test failure scenarios in a unit test. Except for empty input throwing an lxml.etree.XMLSyntaxError, I can't seem to break the parser.

My question is: is it possible to construct a StringIO or BytesIO input for this parser such that the parser throws a parse error?

Here's some examples (tested with Python 3.5 and lxml 4.3.3):

from io import BytesIO
from lxml import etree

def parse(xml):
    parser = etree.XMLParser(recover=True)
    elem = etree.parse(BytesIO(xml), parser)
    print(etree.tostring(elem))

parse(b'<broken<')  # prints b'<broken/>'
parse(b'</lf|\jf>')  # prints None
parse('<?xml encoding="ascii"?><foo>æøå</foo>'.encode('utf-8'))  # prints b'<foo/>'
parse(b'')  # Throws lxml.etree.XMLSyntaxError
```

答:
If I slap a NULL character at the beginning of any of the bad inputs you show that don't raise an error, I do get an error. For instance:

```<code>parse(b'\0<broken<')
</code>```

produces:

```<code>Traceback (most recent call last):
  File "test.py", line 13, in <module>
    parse(b'\0<broken<')  # prints b'<broken/>'
  File "test.py", line 9, in parse
    elem = etree.parse(BytesIO(xml), parser)
  File "src/lxml/etree.pyx", line 3435, in lxml.etree.parse
  File "src/lxml/parser.pxi", line 1857, in lxml.etree._parseDocument
  File "src/lxml/parser.pxi", line 1877, in lxml.etree._parseMemoryDocument
  File "src/lxml/parser.pxi", line 1765, in lxml.etree._parseDoc
  File "src/lxml/parser.pxi", line 1127, in lxml.etree._BaseParser._parseDoc
  File "src/lxml/parser.pxi", line 601, in lxml.etree._ParserContext._handleParseResultDoc
  File "src/lxml/parser.pxi", line 711, in lxml.etree._handleParseResult
  File "src/lxml/parser.pxi", line 640, in lxml.etree._raiseParseError
  File "<string>", line 1
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1
</code>```

Body:
If I slap a NULL character at the beginning of any of the bad inputs you show that don't raise an error, I do get an error. For instance:

parse(b'\0<broken<')

produces:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    parse(b'\0<broken<')  # prints b'<broken/>'
  File "test.py", line 9, in parse
    elem = etree.parse(BytesIO(xml), parser)
  File "src/lxml/etree.pyx", line 3435, in lxml.etree.parse
  File "src/lxml/parser.pxi", line 1857, in lxml.etree._parseDocument
  File "src/lxml/parser.pxi", line 1877, in lxml.etree._parseMemoryDocument
  File "src/lxml/parser.pxi", line 1765, in lxml.etree._parseDoc
  File "src/lxml/parser.pxi", line 1127, in lxml.etree._BaseParser._parseDoc
  File "src/lxml/parser.pxi", line 601, in lxml.etree._ParserContext._handleParseResultDoc
  File "src/lxml/parser.pxi", line 711, in lxml.etree._handleParseResult
  File "src/lxml/parser.pxi", line 640, in lxml.etree._raiseParseError
  File "<string>", line 1
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1