问:
r tidycensus download all block groups
I am looking to automate the process of downloading Census data from all block groups from the US using the tidycensus package.  There is instructions from the developer to download all tracts within the US, however, block groups cannot be accessed using the same method.

Here is my current code that does not work

```<code>library(tidyverse)
library(tidycensus)
census_api_key("key here")

# create lists of state and county codes

data("fips_codes")
temp <- data.frame(state = as.character(fips_codes$state_code),
                   county = fips_codes$county_code,
                   stringsAsFactors = F)
temp <- aggregate(county~state, temp, c)
state <- temp$state
coun <- temp$county

# use map2_df to loop through the files, similar to the "tract" data pull

home <- map2_df(state, coun, function(x,y) {
get_acs(geography = "block group", variables = "B25038_001", #random var
state = x,county = y)
  })
</code>```

The resulting error is

```<code>No encoding supplied: defaulting to UTF-8.
Error: parse error: premature EOF

                     (right here) ------^
</code>```

A similar approach to convert the counties within each state into a list also does not work

```<code>temp <- aggregate(county~state, temp, c)
state <- temp$state
coun <- temp$county

df<- map2_df(state, coun, function(x,y) {
    get_acs(geography = "block group", variables = "B25038_001",
            state = x,county = y)
  })
</code>```

Error: Result 1 is not a length 1 atomic vector is returned.

Does anyone have an understanding of how this could be completed?  More than likely I am not using functions properly or syntax, and I am also not very good with loops.  Any help would be appreciated.

答:
Try this package: totalcensus at https://github.com/GL-Li/totalcensus. It downloads census data files to your own computer and extracts any data from these files. After set up folders and path, run  the code below if you want all block group data in 2015 ACS 5-year survey.

```<code>library(totalcensus)

# download the 2015 ACS 5-year survey data, which is about 50 GB.
download_census("acs5year", 2015)

# read block group data of variable B25038_001 from all states plus DC
block_groups <- read_acs5year(
    year = 2015,
    states = states_DC,
    table_contents = "B25038_001",
    summary_level = "block group"
)
</code>```

The extracted data of 217739 block groups of all states and DC:

```<code>    #                       GEOID       lon      lat state population B25038_001 GEOCOMP SUMLEV                                                              NAME
    #      1: 15000US020130001001 -164.1232 54.80448    AK        982         91     all    150     Block Group 1, Census Tract 1, Aleutians East Borough, Alaska
    #      2: 15000US020130001002 -161.1786 55.60224    AK       1116        247     all    150     Block Group 2, Census Tract 1, Aleutians East Borough, Alaska
    #      3: 15000US020130001003 -160.0655 55.13399    AK       1206        352     all    150     Block Group 3, Census Tract 1, Aleutians East Borough, Alaska
    #      4: 15000US020160001001  178.3388 51.95945    AK       1065        264     all    150 Block Group 1, Census Tract 1, Aleutians West Census Area, Alaska
    #      5: 15000US020160002001 -166.8899 53.85881    AK       2038        380     all    150 Block Group 1, Census Tract 2, Aleutians West Census Area, Alaska
    # ---
    # 217735: 15000US560459511001 -104.7889 43.99520    WY       1392        651     all    150          Block Group 1, Census Tract 9511, Weston County, Wyoming
    # 217736: 15000US560459511002 -104.4785 43.76853    WY       2050        742     all    150          Block Group 2, Census Tract 9511, Weston County, Wyoming
    # 217737: 15000US560459513001 -104.2575 43.88160    WY       1291        520     all    150          Block Group 1, Census Tract 9513, Weston County, Wyoming
    # 217738: 15000US560459513002 -104.1807 43.85406    WY       1046        526     all    150          Block Group 2, Census Tract 9513, Weston County, Wyoming
    # 217739: 15000US560459513003 -104.2601 43.84355    WY       1373        547     all    150          Block Group 3, Census Tract 9513, Weston County, Wyoming
</code>```

Title: r tidycensus download all block groups

Body:
I am looking to automate the process of downloading Census data from all block groups from the US using the tidycensus package.  There is instructions from the developer to download all tracts within the US, however, block groups cannot be accessed using the same method.

Here is my current code that does not work

library(tidyverse)
library(tidycensus)
census_api_key("key here")

# create lists of state and county codes

data("fips_codes")
temp <- data.frame(state = as.character(fips_codes$state_code),
                   county = fips_codes$county_code,
                   stringsAsFactors = F)
temp <- aggregate(county~state, temp, c)
state <- temp$state
coun <- temp$county

# use map2_df to loop through the files, similar to the "tract" data pull

home <- map2_df(state, coun, function(x,y) {
get_acs(geography = "block group", variables = "B25038_001", #random var
state = x,county = y)
  })

The resulting error is

No encoding supplied: defaulting to UTF-8.
Error: parse error: premature EOF

                     (right here) ------^

A similar approach to convert the counties within each state into a list also does not work

temp <- aggregate(county~state, temp, c)
state <- temp$state
coun <- temp$county

df<- map2_df(state, coun, function(x,y) {
    get_acs(geography = "block group", variables = "B25038_001",
            state = x,county = y)
  })

Error: Result 1 is not a length 1 atomic vector is returned.

Does anyone have an understanding of how this could be completed?  More than likely I am not using functions properly or syntax, and I am also not very good with loops.  Any help would be appreciated.

Body:
Try this package: totalcensus at https://github.com/GL-Li/totalcensus. It downloads census data files to your own computer and extracts any data from these files. After set up folders and path, run  the code below if you want all block group data in 2015 ACS 5-year survey.

library(totalcensus)

# download the 2015 ACS 5-year survey data, which is about 50 GB.
download_census("acs5year", 2015)

# read block group data of variable B25038_001 from all states plus DC
block_groups <- read_acs5year(
    year = 2015,
    states = states_DC,
    table_contents = "B25038_001",
    summary_level = "block group"
)

The extracted data of 217739 block groups of all states and DC:

    #                       GEOID       lon      lat state population B25038_001 GEOCOMP SUMLEV                                                              NAME
    #      1: 15000US020130001001 -164.1232 54.80448    AK        982         91     all    150     Block Group 1, Census Tract 1, Aleutians East Borough, Alaska
    #      2: 15000US020130001002 -161.1786 55.60224    AK       1116        247     all    150     Block Group 2, Census Tract 1, Aleutians East Borough, Alaska
    #      3: 15000US020130001003 -160.0655 55.13399    AK       1206        352     all    150     Block Group 3, Census Tract 1, Aleutians East Borough, Alaska
    #      4: 15000US020160001001  178.3388 51.95945    AK       1065        264     all    150 Block Group 1, Census Tract 1, Aleutians West Census Area, Alaska
    #      5: 15000US020160002001 -166.8899 53.85881    AK       2038        380     all    150 Block Group 1, Census Tract 2, Aleutians West Census Area, Alaska
    # ---
    # 217735: 15000US560459511001 -104.7889 43.99520    WY       1392        651     all    150          Block Group 1, Census Tract 9511, Weston County, Wyoming
    # 217736: 15000US560459511002 -104.4785 43.76853    WY       2050        742     all    150          Block Group 2, Census Tract 9511, Weston County, Wyoming
    # 217737: 15000US560459513001 -104.2575 43.88160    WY       1291        520     all    150          Block Group 1, Census Tract 9513, Weston County, Wyoming
    # 217738: 15000US560459513002 -104.1807 43.85406    WY       1046        526     all    150          Block Group 2, Census Tract 9513, Weston County, Wyoming
    # 217739: 15000US560459513003 -104.2601 43.84355    WY       1373        547     all    150          Block Group 3, Census Tract 9513, Weston County, Wyoming


来源: stackexchange

问:
What is the fastest way to pass a large amount of data from a C++ application to SQLServer Stored Procedure?
I am trying to pass a thousand rows from an xml object in a c++ application to a sqlserver stored procedure in the most efficient way possible.  There is some string processing/conversions that needs to happen to the xml elements before it is inserted into the database.  At the moment we are taking each individual xml node in the C++ application and then calling sqlserver to insert it (and doing this a thousand times).  To improve this I would like to send all 1000 records to sqlserver at the same time.   What is the fastest way to do this?

Also, I have seen that I can send xml straight to a stored procedure, but that would involve me doing a lot of processing to the data before I insert it into the database.  Is it more efficient to process strings in the C++ application and then send it via xml or send it to SQLServer in the unprocessed xml then process/convert the strings or is there another way to pass the data altogether?

答:
Set up a table-valued parameter, one row for each parameter set. And then use the rows of that parameter to call the stored procedure. Even if you were to submit the rows as a batch to a stored procedure each row would be a separate communication with the server but if you do it as a TVP the driver is able to bundle it into a single round trip (that is, all the data would be sent then the server would start processing, instead of one parameter set getting sent and the result returned for that parameter set).

I don't know about the XML processing, that may well depend on the nature of the required manipulation, that part sounds like a job for profiling.

basically something like:

```<code>CREATE TYPE ARGS_TABLE TABLE (ID BIGINT, DATA XML);

CREATE PROCEDURE WRAPPER_PROC
@Args ARGS_TABLE READONLY
AS
BEGIN
DECLARE @ID BIGINT, @Data XML
DECLARE ArgCurs CURSOR FOR SELECT ID, DATA FROM @Args;
OPEN ArgsCurs ;
FETCH NEXT FROM ArgsCurs INTO @ID, @Data
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC dbo.REAL_PROC @ID, @Data
FETCH NEXT FROM ArgsCurs INTO @ID, @Data
END
CLOSE ArgsCurs
    DEALLOCATE ArgsCurs
END
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Set up a table-valued parameter, one row for each parameter set. And then use the rows of that parameter to call the stored procedure. Even if you were to submit the rows as a batch to a stored procedure each row would be a separate communication with the server but if you do it as a TVP the driver is able to bundle it into a single round trip (that is, all the data would be sent then the server would start processing, instead of one parameter set getting sent and the result returned for that parameter set).

I don't know about the XML processing, that may well depend on the nature of the required manipulation, that part sounds like a job for profiling.

basically something like:

CREATE TYPE ARGS_TABLE TABLE (ID BIGINT, DATA XML);

CREATE PROCEDURE WRAPPER_PROC
@Args ARGS_TABLE READONLY
AS
BEGIN
DECLARE @ID BIGINT, @Data XML
DECLARE ArgCurs CURSOR FOR SELECT ID, DATA FROM @Args;
OPEN ArgsCurs ;
FETCH NEXT FROM ArgsCurs INTO @ID, @Data
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC dbo.REAL_PROC @ID, @Data
FETCH NEXT FROM ArgsCurs INTO @ID, @Data
END
CLOSE ArgsCurs
    DEALLOCATE ArgsCurs
END


问:
How to reuse the same Redux Saga for multiple React components with their own state?
This is a bit of a lengthy one to explain. As briefly as possible: I have two components, Employees and AddEmployee - these are both attached to the routes /employees and employees/add respectively. A link from the Employee component will push employees/add to BrowserHistory, and vice versa (the AddEmployee component will also push /employees if the form is successfully submitted, or if the user clicks 'cancel').

If I navigate to /employees, the component works fine. If I click to navigate to /employees/add, that component works fine. If I click 'cancel' or submit the form to redirect back to /employees... the component breaks.

Through much debugging I've determined that this is because redux state for AddEmployee is persisting through to Employee. My guess would be this is because they both make use of the same saga. I've written a single get Redux saga to handle requests to the remote API. Employees obviously uses the get saga to retrieve all users, while AddEmployee uses the get saga to retrieve possible locations to assign the user to.

When Employees is loaded, the state of the apiGet saga contains the retrieved employees. When AddEmployee is loaded, the state of the apiGet saga contains the retrieved locations. When you then navigate back to Employees, the state of the apiGet saga still contains the retrieved locations and it does not run again to load the employees again.

How can I solve this?

I've done my best to condense the code below to the relevant portions.

The get Saga:

```<code>function getApi(endpoint, token) {
    return fetch(apiUrl + endpoint, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        }
    }).then(handleApiErrors)
      .then(response => response.json())
      .catch((error) => {throw error})
}

function* apiGetFlow(endpoint) {
    let response, token
    try {
        token = localStorage.getItem('token')
        token = JSON.parse(token)

        response = yield call(getApi, endpoint, token)

        yield put({ type: CLIENT_GET_SUCCESS, response: response })

    } catch(error) {
        ...
    }

    return response
}

function* apiGetWatcher() {
    while(true) {
        const { endpoint } = yield take(CLIENT_GET_REQUESTING)
        const task = yield fork(apiGetFlow, endpoint)
    }
}

export default apiGetWatcher
</code>```

The Employees component:

```<code>class Employees extends Component {

    componentDidMount() {
        this.usersGet()
    }

    usersGet() {
        this.props.apiGetRequest('users')
    }

    render() {
        ...
    }
}

const mapStateToProps = state => {
    return {
        users: state.apiGet,
    }
}

const connected = connect(mapStateToProps, { apiGetRequest })(Employees)

export default connected
</code>```

The AddEmployee component:

```<code>class AddEmployeeForm extends Component {

    componentDidMount() {
        this.locationsGet()
    }

    locationsGet() {
        this.props.apiGetRequest('locations')
    }

    render() {
        ...
    }
}

const mapStateToProps = state => {
    return {
        locations: state.apiGet,
        save: state.apiPost,
    }
}

const formed = reduxForm({
    form: 'addemployee',
})(AddEmployeeForm)

const connected = connect(mapStateToProps, { apiGetRequest, apiPostRequest })(formed)

export default connected
</code>```

答:
I suspect its because your React components aren't unmounting.  It looks like the components fire their api requests from inside the componentDidMount lifecycle method.

Say you start at /employees/, the Employees component mounts and dispatches the api request for users.

When you navigate to /employees/add, the AddEmployeeForm component mounts and dispatches the api request for locations.

When you press back, and your now back to /employees, the Employees component has already mounted.  Therefore it doesn't fire the request again for 'users'.

You can verify if this is the problem by implementing componentWillUnmount method in each component with a console.log.

That being said, in my opinion, you should not be sharing the state.apiGet reducer between components that expect the data to be completely different.  Different data should state maintained in their our reducers.

Say you refactored your components to successfully dispatch the API request when going back and forth, and state.apiGet updates accordingly.  Is that really what you want?  Will the API response be different every time the user presses forward and back?  Also, there will be lag from the api request and state.apiGet will have the wrong data initially until the request completes.

I would create a users reducer and a locations reducer.  Then create two sagas that wrap your getApi method and dispatch their specific actions.

For example:

```<code>function* getUsers(endpoint) {
    let response, token
    try {
        token = localStorage.getItem('token')
        token = JSON.parse(token)

        response = yield call(getApi, endpoint, token)

        yield put({ type: 'ADD_USERS', response: response })

    } catch(error) {
        ...
    }

    return response
}
</code>```

And

```<code>function* getLocations(endpoint) {
    let response, token
    try {
        token = localStorage.getItem('token')
        token = JSON.parse(token)

        response = yield call(getApi, endpoint, token)

        yield put({ type: 'ADD_LOCATIONS', response: response })

    } catch(error) {
        ...
    }
    return response
}
</code>```

In your components:

```<code>const mapStateToProps = state => {
    return {
        users: state.users,
    }
}

const mapStateToProps = state => {
    return {
        locations: state.locations,
        save: state.apiPost,
    }
}
</code>```

There are specifics in the Official Redux Docs about how to create separate reducers.

Body:
This is a bit of a lengthy one to explain. As briefly as possible: I have two components, Employees and AddEmployee - these are both attached to the routes /employees and employees/add respectively. A link from the Employee component will push employees/add to BrowserHistory, and vice versa (the AddEmployee component will also push /employees if the form is successfully submitted, or if the user clicks 'cancel').

If I navigate to /employees, the component works fine. If I click to navigate to /employees/add, that component works fine. If I click 'cancel' or submit the form to redirect back to /employees... the component breaks.

Through much debugging I've determined that this is because redux state for AddEmployee is persisting through to Employee. My guess would be this is because they both make use of the same saga. I've written a single get Redux saga to handle requests to the remote API. Employees obviously uses the get saga to retrieve all users, while AddEmployee uses the get saga to retrieve possible locations to assign the user to.

When Employees is loaded, the state of the apiGet saga contains the retrieved employees. When AddEmployee is loaded, the state of the apiGet saga contains the retrieved locations. When you then navigate back to Employees, the state of the apiGet saga still contains the retrieved locations and it does not run again to load the employees again.

How can I solve this?

I've done my best to condense the code below to the relevant portions.

The get Saga:

function getApi(endpoint, token) {
    return fetch(apiUrl + endpoint, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        }
    }).then(handleApiErrors)
      .then(response => response.json())
      .catch((error) => {throw error})
}

function* apiGetFlow(endpoint) {
    let response, token
    try {
        token = localStorage.getItem('token')
        token = JSON.parse(token)

        response = yield call(getApi, endpoint, token)

        yield put({ type: CLIENT_GET_SUCCESS, response: response })

    } catch(error) {
        ...
    }

    return response
}

function* apiGetWatcher() {
    while(true) {
        const { endpoint } = yield take(CLIENT_GET_REQUESTING)
        const task = yield fork(apiGetFlow, endpoint)
    }
}

export default apiGetWatcher

The Employees component:

class Employees extends Component {

    componentDidMount() {
        this.usersGet()
    }

    usersGet() {
        this.props.apiGetRequest('users')
    }

    render() {
        ...
    }
}

const mapStateToProps = state => {
    return {
        users: state.apiGet,
    }
}

const connected = connect(mapStateToProps, { apiGetRequest })(Employees)

export default connected

The AddEmployee component:

class AddEmployeeForm extends Component {

    componentDidMount() {
        this.locationsGet()
    }

    locationsGet() {
        this.props.apiGetRequest('locations')
    }

    render() {
        ...
    }
}

const mapStateToProps = state => {
    return {
        locations: state.apiGet,
        save: state.apiPost,
    }
}

const formed = reduxForm({
    form: 'addemployee',
})(AddEmployeeForm)

const connected = connect(mapStateToProps, { apiGetRequest, apiPostRequest })(formed)

export default connected

Body:
I suspect its because your React components aren't unmounting.  It looks like the components fire their api requests from inside the componentDidMount lifecycle method.

Say you start at /employees/, the Employees component mounts and dispatches the api request for users.

When you navigate to /employees/add, the AddEmployeeForm component mounts and dispatches the api request for locations.

When you press back, and your now back to /employees, the Employees component has already mounted.  Therefore it doesn't fire the request again for 'users'.

You can verify if this is the problem by implementing componentWillUnmount method in each component with a console.log.

That being said, in my opinion, you should not be sharing the state.apiGet reducer between components that expect the data to be completely different.  Different data should state maintained in their our reducers.

Say you refactored your components to successfully dispatch the API request when going back and forth, and state.apiGet updates accordingly.  Is that really what you want?  Will the API response be different every time the user presses forward and back?  Also, there will be lag from the api request and state.apiGet will have the wrong data initially until the request completes.

I would create a users reducer and a locations reducer.  Then create two sagas that wrap your getApi method and dispatch their specific actions.

For example:

function* getUsers(endpoint) {
    let response, token
    try {
        token = localStorage.getItem('token')
        token = JSON.parse(token)

        response = yield call(getApi, endpoint, token)

        yield put({ type: 'ADD_USERS', response: response })

    } catch(error) {
        ...
    }

    return response
}

And

function* getLocations(endpoint) {
    let response, token
    try {
        token = localStorage.getItem('token')
        token = JSON.parse(token)

        response = yield call(getApi, endpoint, token)

        yield put({ type: 'ADD_LOCATIONS', response: response })

    } catch(error) {
        ...
    }
    return response
}

In your components:

const mapStateToProps = state => {
    return {
        users: state.users,
    }
}

const mapStateToProps = state => {
    return {
        locations: state.locations,
        save: state.apiPost,
    }
}

There are specifics in the Official Redux Docs about how to create separate reducers.


问:
Common way to compare timestamp in Oracle, PostgreSQL and SQL Server
I am writing an SQL query which involves finding if timestamp falls in particular range of days.

I have written that in the PostgreSQL but it doesn't works in Oracle and SQL Server:

```<code>AND creation_date < (CURRENT_TIMESTAMP - interval '5 days')
AND creation_date >= (CURRENT_TIMESTAMP - interval '15 days')
</code>```

Is there are common way to compare the timestamp across different databases?

答:
Again this is specific for Oracle, assume intime is TIMESTAMP(3) data type, you can do this</p>

```<code>select * from MYTABLE where intime >= to_timestamp('2014-10-01 7:00:56', 'YYYY-MM-dd HH24:MI:SS')
</code>```

Body:
I am writing an SQL query which involves finding if timestamp falls in particular range of days.

I have written that in the PostgreSQL but it doesn't works in Oracle and SQL Server:

AND creation_date < (CURRENT_TIMESTAMP - interval '5 days')
AND creation_date >= (CURRENT_TIMESTAMP - interval '15 days')

Is there are common way to compare the timestamp across different databases?

Body:
Again this is specific for Oracle, assume intime is TIMESTAMP(3) data type, you can do this

select * from MYTABLE where intime >= to_timestamp('2014-10-01 7:00:56', 'YYYY-MM-dd HH24:MI:SS')


问:
Cannot find R.layout.activity_main in main activity.java
I am developing an app, and have started working on main screen design but I am not able to test my app. When I want to test the app it suddenly stop all the time and error showing in catlog in the line

setContentView(R.layout.activity_main)

I have attached the screenshots in this question also.

答:
R.java is automatically generated on build, and it is automatically imported so you don't have to import it explicitly.

Try this:

delete generated sub folder in your app folder since R.java is in one of its sub folders

rebuild your project and generated folder will be generated again


问:
Prolog - Backtracking through a set of dynamic options
I'm trying to trigger backtracking on a goal but in a dynamic way, if it's possible. To better exemplify my issue let's say we have the following PROLOG code:

```<code>num(1).
num(2).
num(3).
num(4).
num(5).
</code>```

Then I head to SWI-Prolog and call: num(X). This triggers backtracking looking for all solutions, by typing ; .

What I would like is to remove those facts (num(1),num(2), etc) and replace that code with something thata generates those facts dynamically. Is there any way in which I can achieve this? Someting of the sorts,maybe?

```<code>num(X):- for X in 1..5
</code>```

that yields the same solutions as the code above?

As far as I know, the findall predicate returns a list, which is not what I'm looking for. I would like to backtrack through all answers and look through them using ; in the console.

答:
SWI-Prolog has the (non-ISO) predicate between/3 for that:

```<code>num(X) :- between(1, 5, X).
</code>```

You can implement the predicate (for other Prologs and for further tweaking) like this:

```<code>between2(A, A, A) :- !.  % green cut
between2(A, B, A) :- A < B.
between2(A, B, C) :-
    A < B,
    A1 is A + 1,
    between2(A1, B, C).
</code>```

The signature for both between/3 and between2/3 is (+From,+To,?X). It means that the From and To must be bound and X can be either bound or not. Also note that From and To must be integers such that From <= To. (Oh, and these integers must be written using Arabic numerals with an optional plus or minus sign before. And using ASCII. Is something non-obvious still missed? And the integers must not be too large or too small, although SWI-Prolog is usually compiled with unbounded integer support, so both between(1, 100000000000000000000000000000000000000000000, X) and between2(1, 100000000000000000000000000000000000000000000, X) usually work.)

Body:
I'm trying to trigger backtracking on a goal but in a dynamic way, if it's possible. To better exemplify my issue let's say we have the following PROLOG code:

num(1).
num(2).
num(3).
num(4).
num(5).

Then I head to SWI-Prolog and call: num(X). This triggers backtracking looking for all solutions, by typing ; .

What I would like is to remove those facts (num(1),num(2), etc) and replace that code with something thata generates those facts dynamically. Is there any way in which I can achieve this? Someting of the sorts,maybe?

num(X):- for X in 1..5

that yields the same solutions as the code above?

As far as I know, the findall predicate returns a list, which is not what I'm looking for. I would like to backtrack through all answers and look through them using ; in the console.

Body:
SWI-Prolog has the (non-ISO) predicate between/3 for that:

num(X) :- between(1, 5, X).

You can implement the predicate (for other Prologs and for further tweaking) like this:

between2(A, A, A) :- !.  % green cut
between2(A, B, A) :- A < B.
between2(A, B, C) :-
    A < B,
    A1 is A + 1,
    between2(A1, B, C).

The signature for both between/3 and between2/3 is (+From,+To,?X). It means that the From and To must be bound and X can be either bound or not. Also note that From and To must be integers such that From <= To. (Oh, and these integers must be written using Arabic numerals with an optional plus or minus sign before. And using ASCII. Is something non-obvious still missed? And the integers must not be too large or too small, although SWI-Prolog is usually compiled with unbounded integer support, so both between(1, 100000000000000000000000000000000000000000000, X) and between2(1, 100000000000000000000000000000000000000000000, X) usually work.)


问:
Android Volley- How to send raw text and get json response
I am new to android and using volley to communicate with web services.
Postman details

I found sending a raw text to the web service will only work on postman.I try using grant_type=password&username=myusername&password=mypassowrd getting myusername and mypassword from two editText from my mainActivity, .
Is there any better way to achieve this?

```<code>public class MainActivity extends AppCompatActivity {

Button btnLogin,btnFetch,btnExit;
EditText editTxtUsr,editTxtPass;
TextView txtView;
String uRL ="****";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnLogin=findViewById(R.id.buttonLogin);
    btnFetch=findViewById(R.id.buttonFetch);
    btnExit=findViewById(R.id.buttonExit);
    editTxtUsr=findViewById(R.id.editTextUsrname);
    editTxtPass=findViewById(R.id.editTextPassword);
    txtView=findViewById(R.id.textViewData);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String wsURL = uRL + "/authtoken";
            //final String appData = "grant_type=password&username=" + editTxtUsr + "&password=" + editTxtPass;

            StringRequest request = new StringRequest(Request.Method.POST, wsURL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if (response.equals("true")) {
                        Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Incorrect ", Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(MainActivity.this, "Some error occured" + volleyError, Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                public Map<String,String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/text");
                    headers.put("charset", "TYPE_UTF8_CHARSET");
                    return headers;

                }

                @Override
                protected Map<String,String> getParams() throws AuthFailureError {
                    Map<String, String> parameters = new HashMap<>();
                    parameters.put("grand_type", "SET_VALUE");
                    parameters.put("Username", editTxtUsr.getText().toString());
                    parameters.put("Password", editTxtPass.getText().toString());
                    return parameters;

                }
            };

            RequestQueue rQueue= Volley.newRequestQueue(MainActivity.this);
            rQueue.add(request);
        }
    });

    btnExit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
}
}
</code>```

I have tried various ways to achieve this, but with no luck. That's a sample of my code that I use to try to connect to the web service.

I get  [253] BasicNetwork.performRequest: Unexpected response code 400 for...

I searched thoroughly through StackOverflow but I can't seem to find the correct answer to my question.
Any help would be appreciated.

答:
Its been days I have been working on this but after I posted my question, I found the solution after some tries.
The answer is simpler than I have thought.
What you need to do is make an objectrequest and override the body with the text you want to post. Nothing had to change in headers or parameters.
I still can't find an answer using Stringrequest.

```<code>                @Override
                public byte[] getBody() {
                    try {
                        return requestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
</code>```

Where requestBody is the raw text you want to send as a string.

Body:
I am new to android and using volley to communicate with web services.
Postman details

I found sending a raw text to the web service will only work on postman.I try using grant_type=password&username=myusername&password=mypassowrd getting myusername and mypassword from two editText from my mainActivity, .
Is there any better way to achieve this?

public class MainActivity extends AppCompatActivity {

Button btnLogin,btnFetch,btnExit;
EditText editTxtUsr,editTxtPass;
TextView txtView;
String uRL ="****";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnLogin=findViewById(R.id.buttonLogin);
    btnFetch=findViewById(R.id.buttonFetch);
    btnExit=findViewById(R.id.buttonExit);
    editTxtUsr=findViewById(R.id.editTextUsrname);
    editTxtPass=findViewById(R.id.editTextPassword);
    txtView=findViewById(R.id.textViewData);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String wsURL = uRL + "/authtoken";
            //final String appData = "grant_type=password&username=" + editTxtUsr + "&password=" + editTxtPass;

            StringRequest request = new StringRequest(Request.Method.POST, wsURL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if (response.equals("true")) {
                        Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Incorrect ", Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(MainActivity.this, "Some error occured" + volleyError, Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                public Map<String,String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/text");
                    headers.put("charset", "TYPE_UTF8_CHARSET");
                    return headers;

                }

                @Override
                protected Map<String,String> getParams() throws AuthFailureError {
                    Map<String, String> parameters = new HashMap<>();
                    parameters.put("grand_type", "SET_VALUE");
                    parameters.put("Username", editTxtUsr.getText().toString());
                    parameters.put("Password", editTxtPass.getText().toString());
                    return parameters;

                }
            };

            RequestQueue rQueue= Volley.newRequestQueue(MainActivity.this);
            rQueue.add(request);
        }
    });

    btnExit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
}
}

I have tried various ways to achieve this, but with no luck. That's a sample of my code that I use to try to connect to the web service.

I get  [253] BasicNetwork.performRequest: Unexpected response code 400 for...

I searched thoroughly through StackOverflow but I can't seem to find the correct answer to my question.
Any help would be appreciated.

Body:
Its been days I have been working on this but after I posted my question, I found the solution after some tries.
The answer is simpler than I have thought.
What you need to do is make an objectrequest and override the body with the text you want to post. Nothing had to change in headers or parameters.
I still can't find an answer using Stringrequest.

                @Override
                public byte[] getBody() {
                    try {
                        return requestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        return null;
                    }
                }

Where requestBody is the raw text you want to send as a string.


问:
How to create a udf in PySpark which returns an array of strings?
I have a udf which returns a list of strings.  this should not be too hard.  I pass in the datatype when executing the udf since it returns an array of strings:  ArrayType(StringType).

Now, somehow this is not working:

the dataframe i'm operating on is df_subsets_concat and looks like this:

```<code>df_subsets_concat.show(3,False)
</code>```

+----------------------+
|col1                  |
+----------------------+
|oculunt               |
|predistposed          |
|incredulous           |
+----------------------+
only showing top 3 rows
```

<p>and the code is</p>

```from pyspark.sql.types import ArrayType, FloatType, StringType

my_udf = lambda domain: ['s','n']
label_udf = udf(my_udf, ArrayType(StringType))
df_subsets_concat_with_md = df_subsets_concat.withColumn('subset', label_udf(df_subsets_concat.col1))
```

<p>and the result is </p>

<pre class="lang-none prettyprint-override"><code>/usr/lib/spark/python/pyspark/sql/types.py in __init__(self, elementType, containsNull)
    288         False
    289         """
--> 290         assert isinstance(elementType, DataType), "elementType should be DataType"
    291         self.elementType = elementType
    292         self.containsNull = containsNull

AssertionError: elementType should be DataType
</code>```

It is my understanding that this was the correct way to do this.  Here are some resources:
pySpark Data Frames "assert isinstance(dataType, DataType), "dataType should be DataType"
How to return a "Tuple type" in a UDF in PySpark?

But neither of these have helped me resolve why this is not working.  i am using pyspark 1.6.1.

How to create a udf in pyspark which returns an array of strings?

答:
You need to initialize a StringType instance:

```<code>label_udf = udf(my_udf, ArrayType(StringType()))
#                                           ^^
df.withColumn('subset', label_udf(df.col1)).show()
+------------+------+
|        col1|subset|
+------------+------+
|     oculunt|[s, n]|
|predistposed|[s, n]|
| incredulous|[s, n]|
+------------+------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a udf which returns a list of strings.  this should not be too hard.  I pass in the datatype when executing the udf since it returns an array of strings:  ArrayType(StringType).

Now, somehow this is not working:

the dataframe i'm operating on is df_subsets_concat and looks like this:

df_subsets_concat.show(3,False)

+----------------------+
|col1                  |
+----------------------+
|oculunt               |
|predistposed          |
|incredulous           |
+----------------------+
only showing top 3 rows

and the code is

from pyspark.sql.types import ArrayType, FloatType, StringType

my_udf = lambda domain: ['s','n']
label_udf = udf(my_udf, ArrayType(StringType))
df_subsets_concat_with_md = df_subsets_concat.withColumn('subset', label_udf(df_subsets_concat.col1))

and the result is

/usr/lib/spark/python/pyspark/sql/types.py in __init__(self, elementType, containsNull)
    288         False
    289         """
--> 290         assert isinstance(elementType, DataType), "elementType should be DataType"
    291         self.elementType = elementType
    292         self.containsNull = containsNull

AssertionError: elementType should be DataType

It is my understanding that this was the correct way to do this.  Here are some resources:
pySpark Data Frames "assert isinstance(dataType, DataType), "dataType should be DataType"
How to return a "Tuple type" in a UDF in PySpark?

But neither of these have helped me resolve why this is not working.  i am using pyspark 1.6.1.

How to create a udf in pyspark which returns an array of strings?

Body:
You need to initialize a StringType instance:

label_udf = udf(my_udf, ArrayType(StringType()))
#                                           ^^
df.withColumn('subset', label_udf(df.col1)).show()
+------------+------+
|        col1|subset|
+------------+------+
|     oculunt|[s, n]|
|predistposed|[s, n]|
| incredulous|[s, n]|
+------------+------+


问:
Error: 'list' object is not callable
 I'm trying to make a program that will pick up randomly a name from a file. The user would be asked if he wants to pick up another one again (by pressing 1).
The names can't be picked up twice.
Once picked up, the names would be stocked in a list, written into a file.
When all the names are picked up, the program would be able to restart from the beginning.
I checked other similar problems, but I still don't get it...</p>

```<code>from random import *

#import a list of name from a txt file
def getL1():
    l1 = open("Employees.txt", "r")
    list1 = []
    x = 0
    for line in l1:
        list1.append(line)
        x = x+1
    list1 = [el.replace('\n', '') for el in list1]

    #print("list" 1 :",list)

    return list1
#import an empty list (that will be filled by tested employees) during
#execution of the program
def getL2():
    l2 = open("tested.txt", "r")
    list2 = []

    for line in l2:
        list2.append(line)
    list2 = [el.replace('\n', '') for el in list2]

    #print("list 2 :",list2)
    l2.close()
    return list2

def listCompare():
    employees = getL1()#acquire first list from employee file
    tested = getL2()#acquire second list from tested file
    notTested = []# declare list to hole the results of the compare
    for val in employees:
        if val not in tested: #find employee values not present in tested
            #print(val)
            notTested.append(val)#append value to the notTested list
    return notTested

def listCount():
    x=0
    employees = getL1()
    tested = getL2()
    for val in employees:
        if val not in tested:
            x = x+1

    return x
#add the names of tested employees the the second second file
def addTested(x):
    appendFile = open("tested.txt", "a")
    appenFile.write(x)
    appendFile.write('\n')
    appendFile.close()

def main():

    entry = 1
    while entry == 1:

        pickFrom = listCompare()
        if listCount() > 0:
            y = randint (0, (listCount ()-1))
            print ('\n' + "Random Employee to be tested is: ", pickFrom(y), "\n")
            addTested(pickFrom[y])
            try:
                entry = int(input("Would you like to test another employee? Enter 1:"))

            except:
                print("The entry must be a number")
                entry = 0
        else:
            print("\n/\ new cycle has begun")
            wipeFile = open("tested.txt", "w")

    print ("goodbye")
main()
</code>```

<p> The last error that I have is : </p>

```<code>Traceback (most recent call last):
  File "prog.py", line 78, in <module>
    main()
  File "prog.py", line 65, in main
    print ('\n' + "Random Employee to be tested is: ", pickFrom(y), "\n")
TypeError: 'list' object is not callable
</code>```

答: As per the code print pickFrom is a list and when you are referencing it in the print it needs to be called using [ ]. Change it to pickFrom[y]

Title: Error: 'list' object is not callable

Body:
 I'm trying to make a program that will pick up randomly a name from a file. The user would be asked if he wants to pick up another one again (by pressing 1).
The names can't be picked up twice.
Once picked up, the names would be stocked in a list, written into a file.
When all the names are picked up, the program would be able to restart from the beginning.
I checked other similar problems, but I still don't get it...

from random import *

#import a list of name from a txt file
def getL1():
    l1 = open("Employees.txt", "r")
    list1 = []
    x = 0
    for line in l1:
        list1.append(line)
        x = x+1
    list1 = [el.replace('\n', '') for el in list1]

    #print("list" 1 :",list)

    return list1
#import an empty list (that will be filled by tested employees) during
#execution of the program
def getL2():
    l2 = open("tested.txt", "r")
    list2 = []

    for line in l2:
        list2.append(line)
    list2 = [el.replace('\n', '') for el in list2]

    #print("list 2 :",list2)
    l2.close()
    return list2

def listCompare():
    employees = getL1()#acquire first list from employee file
    tested = getL2()#acquire second list from tested file
    notTested = []# declare list to hole the results of the compare
    for val in employees:
        if val not in tested: #find employee values not present in tested
            #print(val)
            notTested.append(val)#append value to the notTested list
    return notTested

def listCount():
    x=0
    employees = getL1()
    tested = getL2()
    for val in employees:
        if val not in tested:
            x = x+1

    return x
#add the names of tested employees the the second second file
def addTested(x):
    appendFile = open("tested.txt", "a")
    appenFile.write(x)
    appendFile.write('\n')
    appendFile.close()

def main():

    entry = 1
    while entry == 1:

        pickFrom = listCompare()
        if listCount() > 0:
            y = randint (0, (listCount ()-1))
            print ('\n' + "Random Employee to be tested is: ", pickFrom(y), "\n")
            addTested(pickFrom[y])
            try:
                entry = int(input("Would you like to test another employee? Enter 1:"))

            except:
                print("The entry must be a number")
                entry = 0
        else:
            print("\n/\ new cycle has begun")
            wipeFile = open("tested.txt", "w")

    print ("goodbye")
main()

 The last error that I have is :

Traceback (most recent call last):
  File "prog.py", line 78, in <module>
    main()
  File "prog.py", line 65, in main
    print ('\n' + "Random Employee to be tested is: ", pickFrom(y), "\n")
TypeError: 'list' object is not callable


问:
asp.net VB asp:DropDownList only returns default value
My DropDownList is only returning the default selected option. FYI not using code behind. The list populates from the database, but when you select any options it always returns 'NONE' which is the first option value. If I remove the selected 'NONE' Item from the list, then it returns no value at all.

The code:

```<code><asp:DropDownList runat="server" ID="sublist" AppendDataBoundItems="true" EnableViewState="true">
    <asp:ListItem Selected="True" Text="None" Value="NONE" />
</asp:DropDownList>
</code>```

Populating the list:

```<code>Sub GenCatList()
    If Not IsPostBack Then
        SQL2.CommandText = "select * from Categories where SubCategory is NUll order by CategoryTitle ASC"
        RS2 = SQL2.ExecuteReader()
        sublist.DataSource = RS2
        sublist.DataTextField = "CategoryTitle"
        sublist.DataValueField = "CategoryTitle"
        sublist.DataBind()
        RS2.Close()
    End If
End Sub
</code>```

Form submission:

```<code>Protected Sub AddCategory_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim subcat As String = sublist.SelectedValue
    Response.Write(subcat)
    Response.End()
End Sub
</code>```

答:
Annoyingly, all I had to do to solve this issue was add:

Imports System.Configuration

grumbles at ones own stupidity

Body:
My DropDownList is only returning the default selected option. FYI not using code behind. The list populates from the database, but when you select any options it always returns 'NONE' which is the first option value. If I remove the selected 'NONE' Item from the list, then it returns no value at all.

The code:

<asp:DropDownList runat="server" ID="sublist" AppendDataBoundItems="true" EnableViewState="true">
    <asp:ListItem Selected="True" Text="None" Value="NONE" />
</asp:DropDownList>

Populating the list:

Sub GenCatList()
    If Not IsPostBack Then
        SQL2.CommandText = "select * from Categories where SubCategory is NUll order by CategoryTitle ASC"
        RS2 = SQL2.ExecuteReader()
        sublist.DataSource = RS2
        sublist.DataTextField = "CategoryTitle"
        sublist.DataValueField = "CategoryTitle"
        sublist.DataBind()
        RS2.Close()
    End If
End Sub

Form submission:

Protected Sub AddCategory_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim subcat As String = sublist.SelectedValue
    Response.Write(subcat)
    Response.End()
End Sub


问:
How to allow entry in NumericUpDown only via up and down arrow
I have a NumericUpDown  where up and down arrows are there to enter integer. All that is set up but I want to disable entering the value manually by clicking. I want the user to be able to change value only via up and down arrow. can someone guide me how to achieve that.

Currently I have added ValueChanged Event to handle some of the logic. But that event does not get triggered when the value is manualy changed. Please guide me.

答:
In addition to handling key events, you can make the edit part of the control readonly:

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DirectCast(Me.NumericUpDown1.Controls(1), TextBox).ReadOnly= True
    DirectCast(Me.NumericUpDown1.Controls(1), TextBox).BackColor= Color.White
End Sub
</code>```

NumericUpDown is a composite control consisting a custom TextBox and a custom control for Buttons part. You can do anything with those controls. Handling those events, changing properties and so on.

Body:
In addition to handling key events, you can make the edit part of the control readonly:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DirectCast(Me.NumericUpDown1.Controls(1), TextBox).ReadOnly= True
    DirectCast(Me.NumericUpDown1.Controls(1), TextBox).BackColor= Color.White
End Sub

NumericUpDown is a composite control consisting a custom TextBox and a custom control for Buttons part. You can do anything with those controls. Handling those events, changing properties and so on.


问:
Why bother using lambda expressions in logging APIs if the compiler can possibly inline the logging call
Many logging frameworks (e.g., log4j) allow you to pass lambda expressions instead of Strings to the logging API. The argument is that if the string is particularly expressive to construct, the string construction can be lazily executed via the lambda expression. That way, the string is only constructed if the system's log level matches that of the call.

But, given that modern compilers do much method inlining automatically, is there really a point to using lambda expressions in this way? I'll supply a simplified example below to demonstrate this concern.

Suppose our traditional logging method looks like this:

```<code>void log(int level, String message) {
    if (level >= System.logLevel)
        System.out.println(message);
}
// ....
System.logLevel = Level.CRITICAL;
log(Level.FINE, "Very expensive string to construct ..." + etc);
</code>```

Let's suppose that FINE is less than CRITICAL, so, although an expensive string is constructed, it's all for not since the message is not outputted.

Lambda logging APIs help this situation so that the string is only evaluated (constructed) when necessary:

```<code>void log(int level, Supplier<String> message) {
    if (level >= System.logLevel)
        System.out.println(message.apply());
}
// ....
System.logLevel = Level.CRITICAL;
log(Level.FINE, () -> "Very expensive string to construct ..." + etc);
</code>```

But, it's feasible that the compiler can just inline the logging method so that the net effect is as follows:

```<code>System.logLevel = Level.CRITICAL;
if (Level.FINE >= System.logLevel)
    System.out.println("Very expensive string to construct..." + etc);
</code>```

In this case, we don't have to evaluate the string prior to the logging API call (because there is none), and presumably, we would gain performance from just the inlining.

In summary, my question is, how do lambda expressions help us in this situation given that the compiler can possibly inline logging API calls? The only thing I can think of is that, somehow, in the lambda case, the string is not evaluate if the logging level is not a match.

答:
This kind of optimisation-inlining would work for only really simple examples like you have provided (when it is just String concatenation).

In fact, this API can be used in more sophisticated way:

```<code> public void log(Level level, Supplier<String> msgSupplier)
</code>```

Let's say I have a dedicated supplier, which performs a quite expensive log-message producing:

```<code>    Supplier<String> supplier = () -> {
        // really complex stuff
    };
</code>```

and then I use it in several places:

```<code>LOGGER.log(Level.SEVERE, supplier);
...
LOGGER.log(Level.SEVERE, supplier);
</code>```

Then, what would you inline? Unwrapping-inlining it into

```<code>System.logLevel = Level.CRITICAL;
if (Level.FINE >= System.logLevel)
    System.out.println(supplier.get());
</code>```

doesn't make any sense.

As it said in java.util.logging.Logger class JavaDoc:

Log a message, which is only to be constructed if the logging level is
  such that the message will actually be logged.

So this is a purpose: if you can avoid construction, that you don't need to perform these calculations and pass the result as parameter.

Body:
Many logging frameworks (e.g., log4j) allow you to pass lambda expressions instead of Strings to the logging API. The argument is that if the string is particularly expressive to construct, the string construction can be lazily executed via the lambda expression. That way, the string is only constructed if the system's log level matches that of the call.

But, given that modern compilers do much method inlining automatically, is there really a point to using lambda expressions in this way? I'll supply a simplified example below to demonstrate this concern.

Suppose our traditional logging method looks like this:

void log(int level, String message) {
    if (level >= System.logLevel)
        System.out.println(message);
}
// ....
System.logLevel = Level.CRITICAL;
log(Level.FINE, "Very expensive string to construct ..." + etc);

Let's suppose that FINE is less than CRITICAL, so, although an expensive string is constructed, it's all for not since the message is not outputted.

Lambda logging APIs help this situation so that the string is only evaluated (constructed) when necessary:

void log(int level, Supplier<String> message) {
    if (level >= System.logLevel)
        System.out.println(message.apply());
}
// ....
System.logLevel = Level.CRITICAL;
log(Level.FINE, () -> "Very expensive string to construct ..." + etc);

But, it's feasible that the compiler can just inline the logging method so that the net effect is as follows:

System.logLevel = Level.CRITICAL;
if (Level.FINE >= System.logLevel)
    System.out.println("Very expensive string to construct..." + etc);

In this case, we don't have to evaluate the string prior to the logging API call (because there is none), and presumably, we would gain performance from just the inlining.

In summary, my question is, how do lambda expressions help us in this situation given that the compiler can possibly inline logging API calls? The only thing I can think of is that, somehow, in the lambda case, the string is not evaluate if the logging level is not a match.

Body:
This kind of optimisation-inlining would work for only really simple examples like you have provided (when it is just String concatenation).

In fact, this API can be used in more sophisticated way:

 public void log(Level level, Supplier<String> msgSupplier)

Let's say I have a dedicated supplier, which performs a quite expensive log-message producing:

    Supplier<String> supplier = () -> {
        // really complex stuff
    };

and then I use it in several places:

LOGGER.log(Level.SEVERE, supplier);
...
LOGGER.log(Level.SEVERE, supplier);

Then, what would you inline? Unwrapping-inlining it into

System.logLevel = Level.CRITICAL;
if (Level.FINE >= System.logLevel)
    System.out.println(supplier.get());

doesn't make any sense.

As it said in java.util.logging.Logger class JavaDoc:

Log a message, which is only to be constructed if the logging level is
  such that the message will actually be logged.

So this is a purpose: if you can avoid construction, that you don't need to perform these calculations and pass the result as parameter.


问:
ASP secure user login in different access level and restricted access pages
Im building an ASP website with user login. Does any one knows what is the best and must secure way to make login page and make pages restricted access? I know some ways and used them for some website but sometimes they were not that secure. There is couple access level for this website. Admin, User, Sales Team, and couple more. Thanks.</p>

答:
you can use session variables to store user level and then on asp code define what user can or can not see.
Or in database, I assume, you have field where level of access is defined as well.
Basically make your security level part of SQL query and show only data user should be able to see.

Basically you should have level of access in database, login page verify credentials and then store user level in session variable.
On any given page, while header loads, ASP retrives session variable and compare it to database.

If user have clearance to see that data he will if not-- display message that he is not authorized or redirect somewhere else where he can be.

ContentLicense: CC BY-SA 2.5


问:
K-means clustering doesn't find all clusters in data
The set of data I am using is shown below. As one can see you would think the k-means cluster analysis would find the centers of these clusters easily.

However, when I run K-means cluster analysis and plot the centers I get this.

I am using just the basic kmeans code:

```<code>cluster <- kmeans(mydata,90)
cluster$centers
</code>```

答:
As I mentioned in the comment, using hclust() to find the centers might be a viable approach.

```<code>set.seed(1)

l <- 1e4
v1 <- sample(1:10, l, replace=TRUE) + rnorm(l, 0, 0.05)
v2 <- sample(1:13, l, replace=TRUE) + rnorm(l, 0, 0.05)
dtf <- data.frame(v1, v2)

par(mar=c(2, 2, 1, 1))
plot(dtf, pch=16, cex=0.2, col="#00000044")

km <- kmeans(dtf, 10*13)
points(km$centers, cex=2, lwd=0.5, col="red")

hc <- hclust(dist(dtf))
hc <- cutree(hc, 10*13)
hcent <- aggregate(dtf, list(hc), mean)[, -1]

hckm <- kmeans(dtf, hcent)

points(hckm$centers, cex=3, lwd=0.5, col="blue")
</code>```

Body:
The set of data I am using is shown below. As one can see you would think the k-means cluster analysis would find the centers of these clusters easily.

However, when I run K-means cluster analysis and plot the centers I get this.

I am using just the basic kmeans code:

cluster <- kmeans(mydata,90)
cluster$centers

Body:
As I mentioned in the comment, using hclust() to find the centers might be a viable approach.

set.seed(1)

l <- 1e4
v1 <- sample(1:10, l, replace=TRUE) + rnorm(l, 0, 0.05)
v2 <- sample(1:13, l, replace=TRUE) + rnorm(l, 0, 0.05)
dtf <- data.frame(v1, v2)

par(mar=c(2, 2, 1, 1))
plot(dtf, pch=16, cex=0.2, col="#00000044")

km <- kmeans(dtf, 10*13)
points(km$centers, cex=2, lwd=0.5, col="red")

hc <- hclust(dist(dtf))
hc <- cutree(hc, 10*13)
hcent <- aggregate(dtf, list(hc), mean)[, -1]

hckm <- kmeans(dtf, hcent)

points(hckm$centers, cex=3, lwd=0.5, col="blue")


问:
How to enable bulk permission in SQL Server
I am trying to insert images using "bulk" into SQL Server 2012. But, am ending up with the error message stating tha:

Msg 4834, Level 16, State 1, Line 2
  You do not have permission to use the bulk load statement.

I have "sysadmin" access.

答:
SQL Server may also return this error if the service account does not have permission to read the file being imported. Ensure that the service account has read access to the file location. For example:

icacls D:\ImportFiles /Grant "NT Service\MSSQLServer":(OI)(CI)R


问:
Create XSL file to pull value of child element
I have this XML file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<wd:Report_Data xmlns:wd="urn:com.workday.report/xxxxxxxxxxxxxxxxx">
  <wd:Report_Entry>
    <wd:EmployerName>ABC Company</wd:EmployerName>
    <wd:EmployeeID>123456789</wd:EmployeeID>
    <wd:FirstName>Jane</wd:FirstName>
    <wd:LastName>Doe</wd:LastName>
    <wd:Email>jane.l.doe@emcins.com</wd:Email>
    <wd:SSN>111-22-3333</wd:SSN>
    <wd:PostalCode>54321</wd:PostalCode>
    <wd:Division>0</wd:Division>
    <wd:Group>Eligible</wd:Group>
    <wd:Country>0</wd:Country>
    <wd:HealthPlan>Non-Health Plan User</wd:HealthPlan>
    <wd:Location wd:Descriptor="Wichita Branch">
        <wd:ID wd:type="WID">zdf238f821r818890f54c9324ee609db</wd:ID>
        <wd:ID wd:type="Location_ID">Wichita Branch</wd:ID>
    </wd:Location>
    <wd:Region wd:Descriptor="Married (United States of America)">
        <wd:ID wd:type="WID">faf237f571f81088909963455816061f</wd:ID>
        <wd:ID wd:type="Marital_Status_ID">Married_United_States_of_America</wd:ID>
    </wd:Region>
    <wd:Store>2017-01-09-08:00</wd:Store>
    <wd:AgeRange>22</wd:AgeRange>
    <wd:BargainingUnit>Established</wd:BargainingUnit>
    <wd:Class wd:Descriptor="Salary">
        <wd:ID wd:type="WID">faf237f471f81567d35c25d274eef713</wd:ID>
        <wd:ID wd:type="Pay_Rate_Type_ID">Salary</wd:ID>
    </wd:Class>
    <wd:CurrentWalking>0</wd:CurrentWalking>
    <wd:Department wd:Descriptor="Human Resources - General">
        <wd:ID wd:type="WID">faf237f671f41589c20f6681d436e539</wd:ID>
        <wd:ID wd:type="Organization_Reference_ID">Human Resources - General</wd:ID>
        <wd:ID wd:type="Cost_Center_Reference_ID">Human Resources - General</wd:ID>
    </wd:Department>
    <wd:Gender wd:Descriptor="Female">
        <wd:ID wd:type="WID">faf571h561f810889012149c7346059p</wd:ID>
        <wd:ID wd:type="Gender_Code">Female</wd:ID>
    </wd:Gender>
    <wd:Status wd:Descriptor="Regular">
        <wd:ID wd:type="WID">fac242f671f8108555784cb0357608cc</wd:ID>
        <wd:ID wd:type="Employee_Type_ID">Regular</wd:ID>
    </wd:Status>
    <wd:BirthDate>1995-02-17-07:00</wd:BirthDate>
    <wd:RelationshipCode>0</wd:RelationshipCode>
    <wd:Address1 wd:Descriptor="1115 Bellflower Dr">
        <wd:ID wd:type="WID">c70dbf571214999732564dah2m1358f8</wd:ID>
    </wd:Address1>
    <wd:City>Des Moines</wd:City>
    <wd:State wd:Descriptor="Iowa">
        <wd:ID wd:type="WID">a9be12393ccd692ea44d58c678ce6c8b</wd:ID>
        <wd:ID wd:type="Country_Region_ID">USA-IA</wd:ID>
        <wd:ID wd:type="ISO_3166-2_Code">IA</wd:ID>
    </wd:State>
    <wd:spouseSId>s123456789</wd:spouseSId>
    <wd:spouseSFirstName>Tom</wd:spouseSFirstName>
    <wd:spouseSLastName>Doe</wd:spouseSLastName>
    <wd:spouseSDob>1990-05-12-08:00</wd:spouseSDob>
    <wd:spouseSPreferredEmail>tdoe@gmail.com</wd:spouseSPreferredEmail>
</wd:Report_Entry>
</wd:Report_Data>
</code>```

I created this XSL file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:wd="urn:com.workday.report/xxxxxxxxxxxxxxxxx" exclude-result-prefixes="xs"
version="2.0" xmlns:functx="http://www.functx.com">
<xsl:output method="text"/>
<xsl:param name="separator" select="','"/>
<xsl:param name="padding" select="' '"/>
<xsl:param name="spouse" select="'S'"/>
<xsl:variable name="allowednum" select="'0123456789-'"/>
<xsl:variable name="dateFormat" select="'[M01]/[D01]/[Y0001]'"/>
<xsl:variable name="spaces" select="concat('          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ')"/>
<xsl:template match="wd:Report_Data">
    <xsl:for-each select="wd:Report_Entry">
        <xsl:value-of select="substring(concat(wd:EmployerName,$spaces),1,13)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:EmployeeID,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:FirstName,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:LastName,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Email,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:SSN,$spaces),1,11)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:PostalCode,$spaces),1,5)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:JobCode,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Division,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Group,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Country,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:HealthPlan,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Region,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Store,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:AgeRange,$spaces),1,3)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:BargainingUnit,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Class,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:CurrentWalking,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Department,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:District,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Facility,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Gender,$spaces),1,6)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Status,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:BirthDate,$spaces),1,10)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:TerminationDate,$spaces),1,10)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:RelationshipCode,$spaces),1,1)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:SubscriberID,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Address1,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Address2,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:City,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:State,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:choose>
            <xsl:when test="wd:spouseSFirstName != ''">
                <xsl:text>
</xsl:text>
                <xsl:value-of select="substring(concat(wd:EmployerName,$spaces),1,13)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat($spouse,wd:EmployeeID,$spaces),1,10)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSFirstName,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSLastName,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSPreferredEmail,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSDob,$spaces),1,10)"/>
                <xsl:value-of select="$separator"/>
            </xsl:when>
            <xsl:otherwise>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

I need to read the value "Wichita Branch" from wd:Location/wd:ID wd:type="Location_ID".

```<code><wd:Location wd:Descriptor="Wichita Branch">
        <wd:ID wd:type="WID">zdf238f821r818890f54c9324ee609db</wd:ID>
        <wd:ID wd:type="Location_ID">Wichita Branch</wd:ID>
    </wd:Location>
</code>```

I have tried the following with no luck:

```<code><xsl:value-of select="substring(concat(wd:Location,$spaces),1,50)"/>
</code>```

The one above concatenates "faf237f827f810890f85c091c1fe09cc" with "Wichita Branch".  The three below return an empty value.

```<code><xsl:value-of select="substring(concat(wd:Location/ID[@type='Location_ID',$spaces),1,50)"/>

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID'],$spaces),1,50)"/>

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>
</code>```

I am new to creating XSL files and will admit I copied the basic format of the XSL file from another XSL file created at my company to get started.  I would appreciate help.  Thank you.

答:
this will select all text of all ID of type 'Location_ID'

```<code><xsl:value-of select="//wd:Location/wd:ID[@type = 'Location_ID')/text()"/>
</code>```

however @Haley commented you should consider the current node in which the select expression is evaluated

Body:
I have this XML file:

<?xml version="1.0" encoding="UTF-8"?>
<wd:Report_Data xmlns:wd="urn:com.workday.report/xxxxxxxxxxxxxxxxx">
  <wd:Report_Entry>
    <wd:EmployerName>ABC Company</wd:EmployerName>
    <wd:EmployeeID>123456789</wd:EmployeeID>
    <wd:FirstName>Jane</wd:FirstName>
    <wd:LastName>Doe</wd:LastName>
    <wd:Email>jane.l.doe@emcins.com</wd:Email>
    <wd:SSN>111-22-3333</wd:SSN>
    <wd:PostalCode>54321</wd:PostalCode>
    <wd:Division>0</wd:Division>
    <wd:Group>Eligible</wd:Group>
    <wd:Country>0</wd:Country>
    <wd:HealthPlan>Non-Health Plan User</wd:HealthPlan>
    <wd:Location wd:Descriptor="Wichita Branch">
        <wd:ID wd:type="WID">zdf238f821r818890f54c9324ee609db</wd:ID>
        <wd:ID wd:type="Location_ID">Wichita Branch</wd:ID>
    </wd:Location>
    <wd:Region wd:Descriptor="Married (United States of America)">
        <wd:ID wd:type="WID">faf237f571f81088909963455816061f</wd:ID>
        <wd:ID wd:type="Marital_Status_ID">Married_United_States_of_America</wd:ID>
    </wd:Region>
    <wd:Store>2017-01-09-08:00</wd:Store>
    <wd:AgeRange>22</wd:AgeRange>
    <wd:BargainingUnit>Established</wd:BargainingUnit>
    <wd:Class wd:Descriptor="Salary">
        <wd:ID wd:type="WID">faf237f471f81567d35c25d274eef713</wd:ID>
        <wd:ID wd:type="Pay_Rate_Type_ID">Salary</wd:ID>
    </wd:Class>
    <wd:CurrentWalking>0</wd:CurrentWalking>
    <wd:Department wd:Descriptor="Human Resources - General">
        <wd:ID wd:type="WID">faf237f671f41589c20f6681d436e539</wd:ID>
        <wd:ID wd:type="Organization_Reference_ID">Human Resources - General</wd:ID>
        <wd:ID wd:type="Cost_Center_Reference_ID">Human Resources - General</wd:ID>
    </wd:Department>
    <wd:Gender wd:Descriptor="Female">
        <wd:ID wd:type="WID">faf571h561f810889012149c7346059p</wd:ID>
        <wd:ID wd:type="Gender_Code">Female</wd:ID>
    </wd:Gender>
    <wd:Status wd:Descriptor="Regular">
        <wd:ID wd:type="WID">fac242f671f8108555784cb0357608cc</wd:ID>
        <wd:ID wd:type="Employee_Type_ID">Regular</wd:ID>
    </wd:Status>
    <wd:BirthDate>1995-02-17-07:00</wd:BirthDate>
    <wd:RelationshipCode>0</wd:RelationshipCode>
    <wd:Address1 wd:Descriptor="1115 Bellflower Dr">
        <wd:ID wd:type="WID">c70dbf571214999732564dah2m1358f8</wd:ID>
    </wd:Address1>
    <wd:City>Des Moines</wd:City>
    <wd:State wd:Descriptor="Iowa">
        <wd:ID wd:type="WID">a9be12393ccd692ea44d58c678ce6c8b</wd:ID>
        <wd:ID wd:type="Country_Region_ID">USA-IA</wd:ID>
        <wd:ID wd:type="ISO_3166-2_Code">IA</wd:ID>
    </wd:State>
    <wd:spouseSId>s123456789</wd:spouseSId>
    <wd:spouseSFirstName>Tom</wd:spouseSFirstName>
    <wd:spouseSLastName>Doe</wd:spouseSLastName>
    <wd:spouseSDob>1990-05-12-08:00</wd:spouseSDob>
    <wd:spouseSPreferredEmail>tdoe@gmail.com</wd:spouseSPreferredEmail>
</wd:Report_Entry>
</wd:Report_Data>

I created this XSL file:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:wd="urn:com.workday.report/xxxxxxxxxxxxxxxxx" exclude-result-prefixes="xs"
version="2.0" xmlns:functx="http://www.functx.com">
<xsl:output method="text"/>
<xsl:param name="separator" select="','"/>
<xsl:param name="padding" select="' '"/>
<xsl:param name="spouse" select="'S'"/>
<xsl:variable name="allowednum" select="'0123456789-'"/>
<xsl:variable name="dateFormat" select="'[M01]/[D01]/[Y0001]'"/>
<xsl:variable name="spaces" select="concat('          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ','          ')"/>
<xsl:template match="wd:Report_Data">
    <xsl:for-each select="wd:Report_Entry">
        <xsl:value-of select="substring(concat(wd:EmployerName,$spaces),1,13)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:EmployeeID,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:FirstName,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:LastName,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Email,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:SSN,$spaces),1,11)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:PostalCode,$spaces),1,5)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:JobCode,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Division,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Group,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Country,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:HealthPlan,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Region,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Store,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:AgeRange,$spaces),1,3)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:BargainingUnit,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Class,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:CurrentWalking,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Department,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:District,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Facility,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Gender,$spaces),1,6)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Status,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:BirthDate,$spaces),1,10)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:TerminationDate,$spaces),1,10)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:RelationshipCode,$spaces),1,1)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:SubscriberID,$spaces),1,9)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Address1,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:Address2,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:City,$spaces),1,50)"/>
        <xsl:value-of select="$separator"/>
        <xsl:value-of select="substring(concat(wd:State,$spaces),1,30)"/>
        <xsl:value-of select="$separator"/>
        <xsl:choose>
            <xsl:when test="wd:spouseSFirstName != ''">
                <xsl:text>
</xsl:text>
                <xsl:value-of select="substring(concat(wd:EmployerName,$spaces),1,13)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat($spouse,wd:EmployeeID,$spaces),1,10)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSFirstName,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSLastName,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSPreferredEmail,$spaces),1,30)"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="$separator"/>
                <xsl:value-of select="substring(concat(wd:spouseSDob,$spaces),1,10)"/>
                <xsl:value-of select="$separator"/>
            </xsl:when>
            <xsl:otherwise>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

I need to read the value "Wichita Branch" from wd:Location/wd:ID wd:type="Location_ID".

<wd:Location wd:Descriptor="Wichita Branch">
        <wd:ID wd:type="WID">zdf238f821r818890f54c9324ee609db</wd:ID>
        <wd:ID wd:type="Location_ID">Wichita Branch</wd:ID>
    </wd:Location>

I have tried the following with no luck:

<xsl:value-of select="substring(concat(wd:Location,$spaces),1,50)"/>

The one above concatenates "faf237f827f810890f85c091c1fe09cc" with "Wichita Branch".  The three below return an empty value.

<xsl:value-of select="substring(concat(wd:Location/ID[@type='Location_ID',$spaces),1,50)"/>

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID'],$spaces),1,50)"/>

<xsl:value-of select="substring(concat(wd:Location/wd:ID[@type='Location_ID']/text(),$spaces),1,50)"/>

I am new to creating XSL files and will admit I copied the basic format of the XSL file from another XSL file created at my company to get started.  I would appreciate help.  Thank you.

Body:
this will select all text of all ID of type 'Location_ID'

<xsl:value-of select="//wd:Location/wd:ID[@type = 'Location_ID')/text()"/>

however @Haley commented you should consider the current node in which the select expression is evaluated


问:
Running a crontab job from locally stored script
Having trouble running a crontab psql backup job from a locally stored script.  I added the job via crontab -e and when I used crontab -l, it shows up in the list of jobs.  The script that it is supposed to run works fine, checked that, runs as it should and dumps the output on the designated s3 bucket when using ./backup.sh

This is what I set the job as:

```<code>59 23 * * 7 /Users/myusername/backup.sh
</code>```

The job should run at 11:59PM every Sunday, but it doesn't.  I can't figure out what the issue is (do I need to leave line breaks/spaces in between each job, or just after the very lost job in my crontab list?

Any help would be very much appreciated.  Thanks.

答:
Depending on your distribution, you might want to check logs for Cron service.

Non-exhaustive list of possible problem reasons:

Cron service is not running at all and hence is not starting any of the tasks;

Usually Cron passes your script a very limited set of environment variables, so your script might fail because of some missing environment. That will probably be reflected in cron daemon logs

What can you do

Cron service: if your distro uses systemd then try running systemctl status cron (or systemctl status crond?) to check if it is running.

Your script is started but fails: here are several things to try.

Try checking cron service logs, maybe with something like journalctl --unit cron or journalctl -f before the script should be started;

Check if there is a dead.letter file in your home directory containing output of the failed script. When Cron starts your script and the script outputs something (which is considered a problem), that output is mailed to you. If mailing is not properly configured then it usually goes to that file.

Put something like this in the beginning of your script:

```<code>(
  date
  id -a
  set
  echo
) >> /tmp/myscript.log
</code>```

Then wait until cron runs your script and check if the file /tmp/myscript.log was created. Then try to run your script manually, replicating all the environment created by cron which you now know. I.e. unset all but the variables Cron leaves, and make sure id is correct.

Body:
Having trouble running a crontab psql backup job from a locally stored script.  I added the job via crontab -e and when I used crontab -l, it shows up in the list of jobs.  The script that it is supposed to run works fine, checked that, runs as it should and dumps the output on the designated s3 bucket when using ./backup.sh

This is what I set the job as:

59 23 * * 7 /Users/myusername/backup.sh

The job should run at 11:59PM every Sunday, but it doesn't.  I can't figure out what the issue is (do I need to leave line breaks/spaces in between each job, or just after the very lost job in my crontab list?

Any help would be very much appreciated.  Thanks.

Body:
Depending on your distribution, you might want to check logs for Cron service.

Non-exhaustive list of possible problem reasons:

Cron service is not running at all and hence is not starting any of the tasks;

Usually Cron passes your script a very limited set of environment variables, so your script might fail because of some missing environment. That will probably be reflected in cron daemon logs

What can you do

Cron service: if your distro uses systemd then try running systemctl status cron (or systemctl status crond?) to check if it is running.

Your script is started but fails: here are several things to try.

Try checking cron service logs, maybe with something like journalctl --unit cron or journalctl -f before the script should be started;

Check if there is a dead.letter file in your home directory containing output of the failed script. When Cron starts your script and the script outputs something (which is considered a problem), that output is mailed to you. If mailing is not properly configured then it usually goes to that file.

Put something like this in the beginning of your script:

(
  date
  id -a
  set
  echo
) >> /tmp/myscript.log

Then wait until cron runs your script and check if the file /tmp/myscript.log was created. Then try to run your script manually, replicating all the environment created by cron which you now know. I.e. unset all but the variables Cron leaves, and make sure id is correct.