问:
unknown error: failed to write prefs file
I keep getting the error while running functional tests using runner with following:

selenium 2.44

Chrome Driver

Windows Server 2008 R2 Enterprise

Error:

```<code>Error Description: Listening on 0.0.0.0:7000
Starting tunnel...
UnknownError: [POST http://test.com/wd/hub/session / {"de
siredCapabilities":{"browserName":"chrome","name":"tests/intern","idle-timeout":
60,"selenium-version":"2.44.0"}}] unknown error: failed to write prefs file
(Driver info: chromedriver=2.12.301325 (962dea43ddd90e7e4224a03fa3c36a421281ab
b7),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any
stacktrace information)
Command duration or timeout: 1.06 seconds
</code>```

Anyone have ever come across such issue? How do i fix this?

答:
It can be caused by executing ChromeDriver in parallel. Other errors as "failed to write first run file" or "cannot create default profile directory" may happen in that case.

My solution was to specify option user-data-dir. Two concurrent Chromedriver should not use same user data directory.

```<code>chromeOptions.AddArgument("--user-data-dir=C:\\tmp\\chromeprofiles\\profile" + someKindOfIdOrIndex);
</code>```

You can of course change the path for whatever you want :)

Body:
I keep getting the error while running functional tests using runner with following:

selenium 2.44

Chrome Driver

Windows Server 2008 R2 Enterprise

Error:

Error Description: Listening on 0.0.0.0:7000
Starting tunnel...
UnknownError: [POST http://test.com/wd/hub/session / {"de
siredCapabilities":{"browserName":"chrome","name":"tests/intern","idle-timeout":
60,"selenium-version":"2.44.0"}}] unknown error: failed to write prefs file
(Driver info: chromedriver=2.12.301325 (962dea43ddd90e7e4224a03fa3c36a421281ab
b7),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any
stacktrace information)
Command duration or timeout: 1.06 seconds

Anyone have ever come across such issue? How do i fix this?

Body:
It can be caused by executing ChromeDriver in parallel. Other errors as "failed to write first run file" or "cannot create default profile directory" may happen in that case.

My solution was to specify option user-data-dir. Two concurrent Chromedriver should not use same user data directory.

chromeOptions.AddArgument("--user-data-dir=C:\\tmp\\chromeprofiles\\profile" + someKindOfIdOrIndex);

You can of course change the path for whatever you want :)


来源: stackexchange

问:
Calling api inside map
I have two APIs which are written in action and reducer using redux.The first api fetches a list of user and the second api based on user id which comes from the first api.

The APIs are as follows
action.js

```<code>export const GET_EXPERT_LIST='GET_EXPERT_LIST';
export const GET_PROFILE_PHOTO='GET_PROFILE_PHOTO';
export const getExpertList=()=>{
    return(dispatch)=>{
        axios({
            method:'POST',
            url:Constants.URLConst+"/xyz",
            headers:Constants.headers,
            data:{
                "PageNum" : 1,
            }
        }).then((response)=>{
            return dispatch({
                type:GET_EXPERT_LIST,
                response
            })

        }).catch((error)=>{
            console.log(error);
        })
    }
}

export const getProfile=(userid)=>{
    return(dispatch)=>{
        axios({
             method:'GET',
             url:Constants.URLConst+"/UserProfileImage?enterpriseId="+userid,
             headers:Constants.headers
        }).then((response)=>{
             dispatch({
                type:GET_PROFILE_PHOTO,
                response
             })
        }).catch((error)=>{
            console.log(error);
        })
    }
}
</code>```

And in reducer.js, I have-

```<code>import {combineReducers} from 'redux';
import {ASK_EXPERT_DATA,GET_EXPERT_LIST,GET_PROFILE_PHOTO} from '../actions/ProfilePageActions.js';

export function getExpertList(state={},action){
    switch(action.type){
        case GET_EXPERT_LIST:
            return {...state, ...action.response}
            default:
                return state
    }
}

export function getProfile(state={},action){
    switch(action.type){
        case GET_PROFILE_PHOTO:
            return {...state, ...action.response}
            default:
                return state
    }
}

const data=combineReducers({
    getExpertList,
    getProfile
})

export default data;
</code>```

In the main javascript file, I am calling the first api in componentDidMount,
since the first api return an array which I am using map() for display.

```<code>import React,{Component} from 'react';
import ReactDom from 'react-dom';
import {getExpert,getExpertList} from './actions/ProfilePageActions.js';
import {connect} from 'react-redux';
import theme from './assets/react-toolbox/theme';
import ThemeProvider from 'react-toolbox/lib/ThemeProvider';
import Card from 'react-toolbox/lib/card/Card.js';
import CardTitle from 'react-toolbox/lib/card/CardTitle';
import CardMedia from 'react-toolbox/lib/card/CardMedia';
import Chip from 'react-toolbox/lib/chip/Chip.js';
import CardText from 'react-toolbox/lib/card/CardText';

class FindExpert extends Component{

    state={
        countries: ['ES-es', 'TH-th'],
        source:[],
        valueSelected:[],
        experts:[]
    }

    componentDidMount(){
        this.props.getExpertList();
    }

    componentWillReceiveProps(nextProps){

        if(nextProps.get_Expert_List && nextProps.get_Expert_List.data){
            this.setState({
                experts:[...nextProps.get_Expert_List.data.Experts]
            })
        }
    }

    getExpertInfo(){
        var i=1;
        if (this.state.experts && this.state.experts.length) {
            this.test = this.state.experts.map((expertUSer)=> {
                this.props.getProfile(expertUSer.UserId);
                console.log(this.props.get_profile);
                return(
                    <ThemeProvider theme={theme} key={i++}>
                        <Card className='experts'>

                            <CardTitle title={expertUSer.Name}
                                subtitle={expertUSer.Designation}/>
                            <CardText>{expertUSer.Country}</CardText>
                        </Card>
                    </ThemeProvider>
                    )
            });

            return this.test;
        }
        return null;
    }

    render(){
        if(this.props.ask_expert.data){
            return(
                <div className='expert-div' id='expert-div'>{this.getExpertInfo()}</div>
                    )
        }else{
            return null;
        }
    }
}

const mapStateToProps=(state)=>{
    console.log({getExpert: state.getProfile});
    return{
        get_Expert_List:state.getExpertList,
        get_profile:state.getProfile
    }
}

export default connect(mapStateToProps,{
    getExpertList,
    getProfile
})(FindExpert);
</code>```

So,in getExpertList's data, I am calling the getProfile by passing the user id of the individual user.But in this.props.getProfile(expertUSer.UserId);, I get the error that

getProfile is not a function

What should be done here?

答:
Pass current context to map:

```<code>this.state.experts.map(function(expertUSer) {...}, this)
</code>```

So your getExpertInfo() looks like this:

```<code>getExpertInfo(){
    var i=1;
    if (this.state.experts && this.state.experts.length) {
        this.test = this.state.experts.map((expertUSer)=> {
            this.props.getProfile(expertUSer.UserId);
            console.log(this.props.get_profile);
            return(
                <ThemeProvider theme={theme} key={i++}>
                    <Card className='experts'>

                        <CardTitle title={expertUSer.Name}
                            subtitle={expertUSer.Designation}/>
                        <CardText>{expertUSer.Country}</CardText>
                    </Card>
                </ThemeProvider>
                )
        }, this);

        return this.test;
    }
    return null;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Calling api inside map

Body:
I have two APIs which are written in action and reducer using redux.The first api fetches a list of user and the second api based on user id which comes from the first api.

The APIs are as follows
action.js

export const GET_EXPERT_LIST='GET_EXPERT_LIST';
export const GET_PROFILE_PHOTO='GET_PROFILE_PHOTO';
export const getExpertList=()=>{
    return(dispatch)=>{
        axios({
            method:'POST',
            url:Constants.URLConst+"/xyz",
            headers:Constants.headers,
            data:{
                "PageNum" : 1,
            }
        }).then((response)=>{
            return dispatch({
                type:GET_EXPERT_LIST,
                response
            })

        }).catch((error)=>{
            console.log(error);
        })
    }
}

export const getProfile=(userid)=>{
    return(dispatch)=>{
        axios({
             method:'GET',
             url:Constants.URLConst+"/UserProfileImage?enterpriseId="+userid,
             headers:Constants.headers
        }).then((response)=>{
             dispatch({
                type:GET_PROFILE_PHOTO,
                response
             })
        }).catch((error)=>{
            console.log(error);
        })
    }
}

And in reducer.js, I have-

import {combineReducers} from 'redux';
import {ASK_EXPERT_DATA,GET_EXPERT_LIST,GET_PROFILE_PHOTO} from '../actions/ProfilePageActions.js';

export function getExpertList(state={},action){
    switch(action.type){
        case GET_EXPERT_LIST:
            return {...state, ...action.response}
            default:
                return state
    }
}

export function getProfile(state={},action){
    switch(action.type){
        case GET_PROFILE_PHOTO:
            return {...state, ...action.response}
            default:
                return state
    }
}

const data=combineReducers({
    getExpertList,
    getProfile
})

export default data;

In the main javascript file, I am calling the first api in componentDidMount,
since the first api return an array which I am using map() for display.

import React,{Component} from 'react';
import ReactDom from 'react-dom';
import {getExpert,getExpertList} from './actions/ProfilePageActions.js';
import {connect} from 'react-redux';
import theme from './assets/react-toolbox/theme';
import ThemeProvider from 'react-toolbox/lib/ThemeProvider';
import Card from 'react-toolbox/lib/card/Card.js';
import CardTitle from 'react-toolbox/lib/card/CardTitle';
import CardMedia from 'react-toolbox/lib/card/CardMedia';
import Chip from 'react-toolbox/lib/chip/Chip.js';
import CardText from 'react-toolbox/lib/card/CardText';

class FindExpert extends Component{

    state={
        countries: ['ES-es', 'TH-th'],
        source:[],
        valueSelected:[],
        experts:[]
    }

    componentDidMount(){
        this.props.getExpertList();
    }

    componentWillReceiveProps(nextProps){

        if(nextProps.get_Expert_List && nextProps.get_Expert_List.data){
            this.setState({
                experts:[...nextProps.get_Expert_List.data.Experts]
            })
        }
    }

    getExpertInfo(){
        var i=1;
        if (this.state.experts && this.state.experts.length) {
            this.test = this.state.experts.map((expertUSer)=> {
                this.props.getProfile(expertUSer.UserId);
                console.log(this.props.get_profile);
                return(
                    <ThemeProvider theme={theme} key={i++}>
                        <Card className='experts'>

                            <CardTitle title={expertUSer.Name}
                                subtitle={expertUSer.Designation}/>
                            <CardText>{expertUSer.Country}</CardText>
                        </Card>
                    </ThemeProvider>
                    )
            });

            return this.test;
        }
        return null;
    }

    render(){
        if(this.props.ask_expert.data){
            return(

{this.getExpertInfo()}

                    )
        }else{
            return null;
        }
    }
}

const mapStateToProps=(state)=>{
    console.log({getExpert: state.getProfile});
    return{
        get_Expert_List:state.getExpertList,
        get_profile:state.getProfile
    }
}

export default connect(mapStateToProps,{
    getExpertList,
    getProfile
})(FindExpert);

So,in getExpertList's data, I am calling the getProfile by passing the user id of the individual user.But in this.props.getProfile(expertUSer.UserId);, I get the error that

getProfile is not a function

What should be done here?

Body:
Pass current context to map:

this.state.experts.map(function(expertUSer) {...}, this)

So your getExpertInfo() looks like this:

getExpertInfo(){
    var i=1;
    if (this.state.experts && this.state.experts.length) {
        this.test = this.state.experts.map((expertUSer)=> {
            this.props.getProfile(expertUSer.UserId);
            console.log(this.props.get_profile);
            return(
                <ThemeProvider theme={theme} key={i++}>
                    <Card className='experts'>

                        <CardTitle title={expertUSer.Name}
                            subtitle={expertUSer.Designation}/>
                        <CardText>{expertUSer.Country}</CardText>
                    </Card>
                </ThemeProvider>
                )
        }, this);

        return this.test;
    }
    return null;
}


问:
I have problems with my app alignment when i launch it
When I launch my app on my device every thing get ordered as right to left but when I launch it on the emulator it stays the way it is. I know that the problem is that my device's main language is Hebrew (and Hebrew is a language where you write from right to left ) and the emulator's language is English.

picture 1

picture 2

I want it to be the same in all languages.

Thanks in advance

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mahmood.morsecode.TextToMorse">

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginBottom="80dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent" />

<LinearLayout
    android:layout_width="344dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="BackSpace" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Space" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

答:
Go through your layout and change start to left, and end to right e.g. where you have layout_marginStart change to layout_marginLeft.

Doing so should change your layout to

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mahmood.morsecode.TextToMorse">

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginBottom="80dp"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent" />

<LinearLayout
    android:layout_width="344dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="BackSpace" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Space" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I launch my app on my device every thing get ordered as right to left but when I launch it on the emulator it stays the way it is. I know that the problem is that my device's main language is Hebrew (and Hebrew is a language where you write from right to left ) and the emulator's language is English.

picture 1

picture 2

I want it to be the same in all languages.

Thanks in advance

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mahmood.morsecode.TextToMorse">

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginBottom="80dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent" />

<LinearLayout
    android:layout_width="344dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="BackSpace" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Space" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>

Body:
Go through your layout and change start to left, and end to right e.g. where you have layout_marginStart change to layout_marginLeft.

Doing so should change your layout to

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mahmood.morsecode.TextToMorse">

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="0dp"
    android:layout_height="180dp"
    android:layout_marginBottom="80dp"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:ems="10"
    android:inputType="textMultiLine"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent" />

<LinearLayout
    android:layout_width="344dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="BackSpace" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Space" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>


问:
java: create runtime a pojo object from a properties file
Within a java project, I would like that my system to create runtime  an object (POJO) from a configuration file and then use it in a drools-based system.
Point to be noted here is that the pojo class too should be generated at runtime
If I understand this is the only way to make controls on a data structure that does not have a fixed structure
What is the best way to do this?
It would be interesting to be able to cache the java class obtained so you do not have to create it all the time but only when the property file changes
Can someone help me ?
I'm a bit confused
Thank you so much </p>

答:
You need to dynamically define your drl rule file.  In that file you can define types.  e.g.

```<code>declare MyEvent
   MyType : String
   MyValue : double
end
</code>```

So after you have created the drl file contents from your properties file see KieFileSystem for loading up the drl file from memory.
This will create a POJO that you can then access using kieContainer.getKieBase().getFactType to get the type and then you can create an instance and set properties on it.

Body:
You need to dynamically define your drl rule file.  In that file you can define types.  e.g.

declare MyEvent
   MyType : String
   MyValue : double
end

So after you have created the drl file contents from your properties file see KieFileSystem for loading up the drl file from memory.
This will create a POJO that you can then access using kieContainer.getKieBase().getFactType to get the type and then you can create an instance and set properties on it.


问:
PDFBox parser seems to parse, but empty output from text stripper
I have had some problems extracting the text from a document using PDFBox in Android. But the parser seems to be working fine (or at least, that's what I interpret its out to mean; googling "parsed=COSObject" gives no relevant results, unfortunately (for some documents the logcat is spammed and there seems to be no way to turn off this putput)). getCharactersByArticle returns empty output from this document, ie. vectorlistoftps is empty.

I have uploaded the document to: https://ufile.io/cnvoq

For most other documents I have tried, text extraction works fine, or I get errors unrelated to this one. But not here.

Here is the relevant code snippet.

```<code>private void extractTextPosition() throws FileNotFoundException, IOException {
    FileInputStream stream = new FileInputStream(var1);
    PDFParser parser = new PDFParser(stream);

    parser.parse();
    Log.d("Parser has ","parsed");
    StringWriter outString = new StringWriter();
    CustomPDFTextStripper stripper = new CustomPDFTextStripper();
    stripper.setStartPage(currentPage);
    stripper.setEndPage(currentPage);
    stripper.setSortByPosition(true);

    try {
        stripper.writeText(parser.getPDDocument(), outString);
    } catch (Exception e) {
        e.printStackTrace();
    }
Vector<List<TextPosition>> vectorlistoftps = stripper.getCharactersByArticle();
}
</code>```

CustomPDFTextStripper is the same as PDFTextStripper (I had changed it, but all of the changes have been commented out).

Here is the logcat output

Any help is appreciated.

答:
The PDF in question does not contain any text.

Ok, when you look at it, you see text glyphs but they actually are not drawn using text drawing commands (which take strings in some encoding and draw the matching glyphs) but instead each letter glyph is drawn using individual vector graphics operations (move to, line to, curve to, fill, ...).

(You also cannot copy&paste the text in Adobe Reader, you cannot even mark it for copying because there simply is no text to mark.)

Text extraction as done by the PDFBox PDFTextStripper (or similar text extraction classes of other PDF libraries) only works for text drawn using text drawing commands by decoding their string arguments.

Your PDF most likely will require OCR for text retrieval.

Body:
I have had some problems extracting the text from a document using PDFBox in Android. But the parser seems to be working fine (or at least, that's what I interpret its out to mean; googling "parsed=COSObject" gives no relevant results, unfortunately (for some documents the logcat is spammed and there seems to be no way to turn off this putput)). getCharactersByArticle returns empty output from this document, ie. vectorlistoftps is empty.

I have uploaded the document to: https://ufile.io/cnvoq

For most other documents I have tried, text extraction works fine, or I get errors unrelated to this one. But not here.

Here is the relevant code snippet.

private void extractTextPosition() throws FileNotFoundException, IOException {
    FileInputStream stream = new FileInputStream(var1);
    PDFParser parser = new PDFParser(stream);

    parser.parse();
    Log.d("Parser has ","parsed");
    StringWriter outString = new StringWriter();
    CustomPDFTextStripper stripper = new CustomPDFTextStripper();
    stripper.setStartPage(currentPage);
    stripper.setEndPage(currentPage);
    stripper.setSortByPosition(true);

    try {
        stripper.writeText(parser.getPDDocument(), outString);
    } catch (Exception e) {
        e.printStackTrace();
    }
Vector<List<TextPosition>> vectorlistoftps = stripper.getCharactersByArticle();
}

CustomPDFTextStripper is the same as PDFTextStripper (I had changed it, but all of the changes have been commented out).

Here is the logcat output

Any help is appreciated.


问:
Regex to test for restricted word in email address not working correctly
I have a regular expression that is giving me some trouble.    I want to restrict domains that have a certain word in them, such as 'foobar'.    I have a regex to test for a certain domain, such as foobar.com, but I also want to cover:

internal.foobar.com

foobarcorp.com

randomdomainwithfoobarinit.co.uk

foobar.net

Etc

So far my regex, covers almost everything correctly, except if there are characters before foobar   so myfoobar.com would not be caught, but foobarcorp.com would.    I have tried a mix of w+ and . and * after the @ sign with no luck finding the right combo.   Any ideas?   I tried to search around stack overflow, but most of the similar questions cover restricting a certain, already known domain where I am trying to cover domains I don't necessarily know about ahead of time.

Code:

```<code>var regex = /\w+@((?!foobar).)*\../i;
ngModel.$setValidity('restrict-email', regex.test(value));
</code>```

答:
```<code>\w+@?((?!foobar).)*\.
</code>```

Just missing an optional parameter ?

To be more specific you can list the domains out yourself like so:

```<code>\w+@?((?!foobar).)*\.(com|net|co\.uk)
</code>```

https://regexr.com/3h68s

But that's obviously a decision you can make based on the security you're looking to offer.

Body:
I have a regular expression that is giving me some trouble.    I want to restrict domains that have a certain word in them, such as 'foobar'.    I have a regex to test for a certain domain, such as foobar.com, but I also want to cover:

internal.foobar.com

foobarcorp.com

randomdomainwithfoobarinit.co.uk

foobar.net

Etc

So far my regex, covers almost everything correctly, except if there are characters before foobar   so myfoobar.com would not be caught, but foobarcorp.com would.    I have tried a mix of w+ and . and * after the @ sign with no luck finding the right combo.   Any ideas?   I tried to search around stack overflow, but most of the similar questions cover restricting a certain, already known domain where I am trying to cover domains I don't necessarily know about ahead of time.

Code:

var regex = /\w+@((?!foobar).)*\../i;
ngModel.$setValidity('restrict-email', regex.test(value));

Body:
\w+@?((?!foobar).)*\.

Just missing an optional parameter ?

To be more specific you can list the domains out yourself like so:

\w+@?((?!foobar).)*\.(com|net|co\.uk)

https://regexr.com/3h68s

But that's obviously a decision you can make based on the security you're looking to offer.


问:
Split string every nth character from the right?
I have different very large sets of files which I'd like to put in different subfolders. I already have an consecutive ID for every folder I want to use.
I want to split the ID from the right to always have 1000 folders in the deeper levels.

Example:

id: 100243 => resulting_path: './100/243'

id: 1234567890 => resulting path: '1/234/567/890'

I found Split string every nth character?, but all solutions are from left to right and I also did not want to import another module for one line of code.

My current (working) solution looks like this:

```<code>import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))
</code>```

Output is: /home/made/00/024/102/442

The current algorithm looks awkward and complicated for the simple thing I want to do.
I wonder if there is a better solution. If not it might help others, anyway.

Update:

I really like Joe Iddons solution. Using .join and mod makes it faster and more readable.

In the end I decided that I never want to have a /in front. To get rid of the preceeding /in case len(s)%3is zero, I changed the line to

```<code>'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])
</code>```

Thank you for your great help!

Update 2:

If you are going to use os.path.join (like in my previous code) its even simpler since os.path.jointakes care of the format of the args itself:

```<code>ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))
</code>```

答:
You could use regex and modulo to split the strings into groups of three. This solution should get you started:

```<code>import re
s = [100243, 1234567890]
final_s = ['./'+'/'.join(re.findall('.{2}.', str(i))) if len(str(i))%3 == 0 else str(i)[:len(str(i))%3]+'/'+'/'.join(re.findall('.{2}.', str(i)[len(str(i))%3:])) for i in s]
</code>```

Output:

```<code>['./100/243', '1/234/567/890']
</code>```

Body:
I have different very large sets of files which I'd like to put in different subfolders. I already have an consecutive ID for every folder I want to use.
I want to split the ID from the right to always have 1000 folders in the deeper levels.

Example:

id: 100243 => resulting_path: './100/243'

id: 1234567890 => resulting path: '1/234/567/890'

I found Split string every nth character?, but all solutions are from left to right and I also did not want to import another module for one line of code.

My current (working) solution looks like this:

import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))

Output is: /home/made/00/024/102/442

The current algorithm looks awkward and complicated for the simple thing I want to do.
I wonder if there is a better solution. If not it might help others, anyway.

Update:

I really like Joe Iddons solution. Using .join and mod makes it faster and more readable.

In the end I decided that I never want to have a /in front. To get rid of the preceeding /in case len(s)%3is zero, I changed the line to

'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])

Thank you for your great help!

Update 2:

If you are going to use os.path.join (like in my previous code) its even simpler since os.path.jointakes care of the format of the args itself:

ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))

Body:
You could use regex and modulo to split the strings into groups of three. This solution should get you started:

import re
s = [100243, 1234567890]
final_s = ['./'+'/'.join(re.findall('.{2}.', str(i))) if len(str(i))%3 == 0 else str(i)[:len(str(i))%3]+'/'+'/'.join(re.findall('.{2}.', str(i)[len(str(i))%3:])) for i in s]

Output:

['./100/243', '1/234/567/890']


问:
How to refactor my angularjs function with if validations and 2 foreach loops
I've written this function in order to loop through some files and their children items depending on certain criteria. Depending on what the criteria is for the file, it will return true or false.

I've made a variable validFile to keep track of the return value.

I feel like there is a cleaner way to make the function more fluid....if someone can give me some pointers on how i can make this function more simple that'd be great.

```<code>function checkFile() {
    // track file validity value
    var validFile;

    // check to see if files exists
    if($scope.files.length) {
      angular.forEach($scope.files, function(file) {
         // check to see that file has a child item
         if(file.item && file.item.child.length > 1) {
          angular.forEach(file.item.child, function(item) {
            if(item.child.code === 8) {
              validFile = true;
            }
          });
        } else {
          validFile = false;
        }

      });
    } else {
      validFile = false;
    }

    return validFile;
  }
</code>```

PS. the function works fine....just want to clean it up and refactor it to be neater

EDIT:

example of files goes something like this...

```<code> $scope.files = [{
      length: 1,
      type: pdf,
      item: {
        child:[{
           type: pdf,
           code: 8
        }]
      }
    }]
</code>```

The validFile will be true if

$scope.files and file.item.child exists

item.child.code has a value of 8

thanks

答:
The function name is a bit of a misnomer, since you're checking files not a single file. Break it out then call your function in a loop.

You can also remove a few lines by just initially setting validFile to false.

```<code>function checkFile(file) {
  var validFile = false;
  if(file.item && file.item.child.length > 1) {
    angular.forEach(file.item.child, function(item) {
      if(item.child.code === 8) {
        validFile = true;
      }
    });
  }
  return validFile;
}

angular.forEach($scope.files, checkFile); // ok to have length of 0
</code>```

Body:
I've written this function in order to loop through some files and their children items depending on certain criteria. Depending on what the criteria is for the file, it will return true or false.

I've made a variable validFile to keep track of the return value.

I feel like there is a cleaner way to make the function more fluid....if someone can give me some pointers on how i can make this function more simple that'd be great.

function checkFile() {
    // track file validity value
    var validFile;

    // check to see if files exists
    if($scope.files.length) {
      angular.forEach($scope.files, function(file) {
         // check to see that file has a child item
         if(file.item && file.item.child.length > 1) {
          angular.forEach(file.item.child, function(item) {
            if(item.child.code === 8) {
              validFile = true;
            }
          });
        } else {
          validFile = false;
        }

      });
    } else {
      validFile = false;
    }

    return validFile;
  }

PS. the function works fine....just want to clean it up and refactor it to be neater

EDIT:

example of files goes something like this...

 $scope.files = [{
      length: 1,
      type: pdf,
      item: {
        child:[{
           type: pdf,
           code: 8
        }]
      }
    }]

The validFile will be true if

$scope.files and file.item.child exists

item.child.code has a value of 8

thanks

Body:
The function name is a bit of a misnomer, since you're checking files not a single file. Break it out then call your function in a loop.

You can also remove a few lines by just initially setting validFile to false.

function checkFile(file) {
  var validFile = false;
  if(file.item && file.item.child.length > 1) {
    angular.forEach(file.item.child, function(item) {
      if(item.child.code === 8) {
        validFile = true;
      }
    });
  }
  return validFile;
}

angular.forEach($scope.files, checkFile); // ok to have length of 0


问:
C++ Set Iterator in Class
I have a class, which has a member named _Emails. It is of the type set<PEmail*>. When I'm in a member function, and run the following code, it works as expected:

```<code>for( set<PEmail*>::iterator it=this->_Emails->begin(); it!=this->_Emails->end(); ++it )
  {
    cout << "Email: " << (*it)->getEmail() << endl;
  }
</code>```

That is, it yields a list of email addresses. Now, I'd like to be able to add to this set as the class grows, and not lose my place of last iteration. I attempted to make another member of my class, named _EmailItr, of type set<PEmail*>::iterator. I initialize it in my constructor, right after my _Emails, like so:

```<code>this->_Emails = new set<PEmail*>;
this->_EmailItr = this->_Emails->begin();
</code>```

Then, attempting to do a similar for loop:

```<code>// send the max queue amount, or until there are no more emails
for( int i=0;  i<this->_QueueSize || i==_Emails->size(); ++i )
  {
    cout << "i: " << i << endl;
    cout << "QueueSize: " << this->_QueueSize << endl;
    cout << "Emails: " << this->_Emails->size() << endl;

    cout << (*_EmailItr)->getEmail() << endl;
  }
</code>```

I get the following output:

```<code>i: 0
QueueSize: 2
Emails: 2
Segmentation fault
</code>```

What gives? Am I trying to use iterators in an improper way?

答:
When you get this->_Emails->begin() right after creating the std::map, the iterator you get is the end iterator (because there are no elements in the std::map, its size is zero and begin() == end()).  You cannot dereference or increment an end iterator.  It doesn't point to "the beginning of the container;" it points to "the element currently at the beginning" or if the container is empty, it returns the end iterator.

(On an unrelated note, it looks like you are doing way too much dynamic allocation.  Why are you creating the std::set object dynamically (using new)?  Why not just have a std::set as a member of the class?)

ContentLicense: CC BY-SA 2.5

Title: C++ Set Iterator in Class

Body:
I have a class, which has a member named _Emails. It is of the type set<PEmail*>. When I'm in a member function, and run the following code, it works as expected:

for( set<PEmail*>::iterator it=this->_Emails->begin(); it!=this->_Emails->end(); ++it )
  {
    cout << "Email: " << (*it)->getEmail() << endl;
  }

That is, it yields a list of email addresses. Now, I'd like to be able to add to this set as the class grows, and not lose my place of last iteration. I attempted to make another member of my class, named _EmailItr, of type set<PEmail*>::iterator. I initialize it in my constructor, right after my _Emails, like so:

this->_Emails = new set<PEmail*>;
this->_EmailItr = this->_Emails->begin();

Then, attempting to do a similar for loop:

// send the max queue amount, or until there are no more emails
for( int i=0;  i<this->_QueueSize || i==_Emails->size(); ++i )
  {
    cout << "i: " << i << endl;
    cout << "QueueSize: " << this->_QueueSize << endl;
    cout << "Emails: " << this->_Emails->size() << endl;

    cout << (*_EmailItr)->getEmail() << endl;
  }

I get the following output:

i: 0
QueueSize: 2
Emails: 2
Segmentation fault

What gives? Am I trying to use iterators in an improper way?


问:
Handling Promise rejection in gulp code
I am trying to minify JS and CSS files using gulp. The script is working for minifying JS files but it's giving below error when I try to minify CSS file

(node:10533) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: write callback called multiple times

(node:10533) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The gulp file is as below:

```<code>var gulp = require('gulp');
var concat = require('gulp-concat');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var ngmin = require('gulp-ngmin');
var minify_css = require('gulp-minify-css');
var import_css = require('gulp-cssimport');

// ================== Configure this path as per the deployed server ===============
var dev_static_path = '/home/shan/';
var minified_static_path = '/home/shan/minified_assets/';

var ngFiles_site = [
    dev_static_path+'/angular/js/abc.js',
    dev_static_path+'/angular/js/abc-configurator.js',
    dev_static_path+'/angular/js/controller/hostme-ctrl.js',
    dev_static_path+'/angular/js/controller/static-page-ctrl.js'

];
var cssFiles = [
    dev_static_path+'/css/bootstrap.css',
    dev_static_path+'/css/settings.css',
    dev_static_path+'/css/style.css',
    dev_static_path+'/css/custom.css',
    dev_static_path+'/css/site-custom.css'
];
//
//==================================================================================
// minify css files
gulp.task('build-css', function(){
gulp.src(cssFiles)
    .pipe(import_css())
    .pipe(minify_css())
    .pipe(concat('abc.min.css'))
    .pipe(gulp.dest(minified_static_path))
});
// minify site module js files
gulp.task('build-site-js', function(){
gulp.src(ngFiles_site)
    .pipe(ngAnnotate())
    .pipe(concat('abc.min.js'))
    .pipe(uglify({mangle: false}))
    .pipe(gulp.dest(minified_static_path))
});

// ============================= This is the main execution manager =========================
gulp.task('abcsite',['build-css']);
</code>```

I am not an expert in node JS and I tried changing it to

```<code>gulp.task('abcsite',['build-css']).catch(function(err){
   console.log(err)
});
</code>```

in a hope to get a promise, but it gave

TypeError: gulp.task(...).catch is not a function

There are no links available to tell me how to handle promise for a gulp task.

Can anyone help me with this ?

UPDATE 1: tried below, didnt work. same error

```<code>gulp.task('turacos',function(){
  return gulp.src(cssFiles)
    .pipe(import_css())
    .pipe(minify_css())
    .pipe(concat('turacos.min.css'))
    .pipe(gulp.dest(minified_static_path))
 }).catch(function(err){
console.log(err)
 })
</code>```

答:
You need to return the gulp.src() call, so gulp will know when the child task has completed:

```<code>gulp.task('build-css', function(){
    return gulp.src(cssFiles)
    .pipe(import_css())
    ...
</code>```

Title: Handling Promise rejection in gulp code

Body:
I am trying to minify JS and CSS files using gulp. The script is working for minifying JS files but it's giving below error when I try to minify CSS file

(node:10533) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: write callback called multiple times

(node:10533) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The gulp file is as below:

var gulp = require('gulp');
var concat = require('gulp-concat');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var ngmin = require('gulp-ngmin');
var minify_css = require('gulp-minify-css');
var import_css = require('gulp-cssimport');

// ================== Configure this path as per the deployed server ===============
var dev_static_path = '/home/shan/';
var minified_static_path = '/home/shan/minified_assets/';

var ngFiles_site = [
    dev_static_path+'/angular/js/abc.js',
    dev_static_path+'/angular/js/abc-configurator.js',
    dev_static_path+'/angular/js/controller/hostme-ctrl.js',
    dev_static_path+'/angular/js/controller/static-page-ctrl.js'

];
var cssFiles = [
    dev_static_path+'/css/bootstrap.css',
    dev_static_path+'/css/settings.css',
    dev_static_path+'/css/style.css',
    dev_static_path+'/css/custom.css',
    dev_static_path+'/css/site-custom.css'
];
//
//==================================================================================
// minify css files
gulp.task('build-css', function(){
gulp.src(cssFiles)
    .pipe(import_css())
    .pipe(minify_css())
    .pipe(concat('abc.min.css'))
    .pipe(gulp.dest(minified_static_path))
});
// minify site module js files
gulp.task('build-site-js', function(){
gulp.src(ngFiles_site)
    .pipe(ngAnnotate())
    .pipe(concat('abc.min.js'))
    .pipe(uglify({mangle: false}))
    .pipe(gulp.dest(minified_static_path))
});

// ============================= This is the main execution manager =========================
gulp.task('abcsite',['build-css']);

I am not an expert in node JS and I tried changing it to

gulp.task('abcsite',['build-css']).catch(function(err){
   console.log(err)
});

in a hope to get a promise, but it gave

TypeError: gulp.task(...).catch is not a function

There are no links available to tell me how to handle promise for a gulp task.

Can anyone help me with this ?

UPDATE 1: tried below, didnt work. same error

gulp.task('turacos',function(){
  return gulp.src(cssFiles)
    .pipe(import_css())
    .pipe(minify_css())
    .pipe(concat('turacos.min.css'))
    .pipe(gulp.dest(minified_static_path))
 }).catch(function(err){
console.log(err)
 })

Body:
You need to return the gulp.src() call, so gulp will know when the child task has completed:

gulp.task('build-css', function(){
    return gulp.src(cssFiles)
    .pipe(import_css())
    ...


问:
Importing Requests causes print() to print twice
I'm running Python 3.6.3 on Windows 10 and installed Requests via pip.

```<code>#!python
import requests
print('Hello')
</code>```

Results in "Hello" printing twice on PowerShell as well as Command Prompt. When I don't import requests, print works as expected.

Launching Python and importing from the prompt however causes no issue.

答: There must be something in the requests library that hiccups on a filename named "html.py".

Body:
I'm running Python 3.6.3 on Windows 10 and installed Requests via pip.

#!python
import requests
print('Hello')

Results in "Hello" printing twice on PowerShell as well as Command Prompt. When I don't import requests, print works as expected.

Launching Python and importing from the prompt however causes no issue.


问:
what is the purpose of '&' in insert statement while entering multiple records
Example :

```<code> INSERT into values(&id,'&name',&age);
</code>```

While executing the statement , it's showing a popup like 'please enter the substitution variable'

So my question :
what does substitution variable means ? And what is inner process happening with '&' symbol?

答: & symbol indicates to oracle that you want to specify a value for that column before oracle processes the query

Body:
Example :

 INSERT into values(&id,'&name',&age);

While executing the statement , it's showing a popup like 'please enter the substitution variable'

So my question :
what does substitution variable means ? And what is inner process happening with '&' symbol?


问:
Make JVM dialog a child window of native top-level window
I have a legacy, X/Motif, C++ application for which new windows have been added using Java/JNI.

New Java windows have been either top level windows or dialogs with no parent.

Is there any reasonable way to get a child window created by the JVM, such as a JDialog, to have as its parent a window created on the native side using X/Motif, and if yes then how? This would still be useful even if Java AWT/Swing is not aware of the parenting structure and the window manager just kept the dialog on top of the top-level window (of course, having all the normal control over windows in Java would be preferable, just not strictly necessary for all uses of my question).

I am thinking the answer might be "No, not in any reasonable way. You would have to do epic surgery on both your native side and within the JVM." If that is the answer, then so be it. But I am hoping someone has an answer along the lines of "If you make this X call or that window manager call, you can get the window manager to supply certain dialog properties with the argument top-level window as the parent."

Essentially, I am looking to increase the integration between the C++ and Java user interfaces as much as possible. Right now, they are run as one application by using JNI, but the GUI windows/components are essentially separate, despite sharing data.

One benefit of this, already mentioned, is having dialogs not show up behind what the user perceives as the top level window.

Another thing I have considered, though I probably will not do (tell me how crazy you think it is), is to make it appear as though Java components are in the C++ window by getting the screen coordinates of a component on the C++ side, displaying a borderless window on the Java side at that screen location, so it looks like it's part of the C++ application. I can think of so many negative side effects of this, though, that I would not do it unless there was a simple way to negate them (focus issues, a window displaying between this dummy window and the real top level window, and other things would affect user experience). Even avoiding this, though, there are still benefits to an affirmative answer to my question.

答:
If you're using the XToolkit (Java 1.7+), you can proceed as follows:

Get the numeric id of the native peer of a java.awt.Window instance (see this answer).

Find the corresponding X11 Window struct by its id by iterating the clients of the X server (see the sources of xwininfo and xlsclients utilities, also Select_Window_Args(int*, char**)).

Use XReparentWindow().


问:
Can COUNTIFS include simple formula as criteria (x - y > z)
Excel 2010

I have a COUNTIFS formula I'm creating.  So far, I have the following, which works great:

```<code>=COUNTIFS(Manager, $A7, Created Date,"<="& variable date, Closed Date, "<="& variable date)
</code>```

The problem is I need to add another if-clause that counts only if 'variable date - Created Date > 14'.  I can't figure out if it's possible or how I would do it.  If it is possible, what criteria_range would I use and what would be the proper syntax (including quote marks) for the formula portion.

Any ideas?

答:
In case anyone is interested, after some additional research, I ended up with the following formula:

```<code>=SUMPRODUCT(--(Manager=$A7),--(variable date-Created Date>14),--(Closed Date>variable date))
</code>```

I don't completely understand the resulting formula but it did do what I needed it to do.

Body:
Excel 2010

I have a COUNTIFS formula I'm creating.  So far, I have the following, which works great:

=COUNTIFS(Manager, $A7, Created Date,"<="& variable date, Closed Date, "<="& variable date)

The problem is I need to add another if-clause that counts only if 'variable date - Created Date > 14'.  I can't figure out if it's possible or how I would do it.  If it is possible, what criteria_range would I use and what would be the proper syntax (including quote marks) for the formula portion.

Any ideas?

Body:
In case anyone is interested, after some additional research, I ended up with the following formula:

=SUMPRODUCT(--(Manager=$A7),--(variable date-Created Date>14),--(Closed Date>variable date))

I don't completely understand the resulting formula but it did do what I needed it to do.


问:
Chrome is being controlled by automated test software
I am running automated tests in Chrome with Serenity BDD (Selenium).

I had to download a new ChromeDriver, because my tests could not run -> The test would open ChromeDriver but could not "Browse as user". When I googled the issue, they said I had to update ChromeDriver.

So I updated ChromeDriver to version 2.28 and I also updated the Chrome version to Version 57.0.2987.98.

But now - EVERY TIME I run my tests this annoying text comes up:

Chrome is being controlled by automated test software

And it asks me if I want to save password. (I can't add pictures because I don't have enough "points")

In the previous version, I had managed to block these 2 things by:

```<code>public class CustomChromeDriver implements DriverSource {

    @Override
    public WebDriver newDriver() {
        try {
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            Proxy proxy = new Proxy();
            String proxyServer = String.format("AProxyIDontWantToDisplay", System.getenv("proxy.username"), System.getenv("proxy.password"));
            proxy.setHttpProxy(proxyServer);
            capabilities.setCapability("proxy", proxy);
            ChromeOptions options = new ChromeOptions();
            options.addArguments(Arrays.asList("--no-sandbox","--ignore-certificate-errors","--homepage=about:blank","--no-first-run"));
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            ChromeDriver driver = new ChromeDriver(capabilities);
            return driver;
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    @Override
    public boolean takesScreenshots() {
        return true;
    }
}
</code>```

I know there is this one (A link to same issue),
but there are too many answers that don't work.

Anybody that knows how to remove that?

答:
While the disable-infobars route will work, it will likely suppress the infobar in all cases (as suggested here), not just the case that the OP is referring to. This is overkill at best, and could lead to unexpected and inexplicable behavior in the future if you are not getting some important message.

I think it's better to leverage the provided enable-automation switch by disabling it in the excludeSwitches area of your config/setup while doing nothing with regards to disable-inforbars. The enable-automation switch's description:

Inform users that their browser is being controlled by an automated test.

For nightwatch.conf.js it would look something like this (and worked for me):

```<code>desiredCapabilities: {
  ...
  chromeOptions: {
    excludeSwitches: ['enable-automation'],
    ...
  }
}
</code>```

This should only do what we are after: getting rid of that specific pesky message!

Edit [2017-11-14]: This is now causing an even more annoying Disable Developer Mode Extensions alert/warning. I've tried every relevant-looking flag/switch I could find that might help, but to no avail. I've filed a bug with Chromium, so we'll see and I'll try to swing back through here if I get a resolution.

Body:
I am running automated tests in Chrome with Serenity BDD (Selenium).

I had to download a new ChromeDriver, because my tests could not run -> The test would open ChromeDriver but could not "Browse as user". When I googled the issue, they said I had to update ChromeDriver.

So I updated ChromeDriver to version 2.28 and I also updated the Chrome version to Version 57.0.2987.98.

But now - EVERY TIME I run my tests this annoying text comes up:

Chrome is being controlled by automated test software

And it asks me if I want to save password. (I can't add pictures because I don't have enough "points")

In the previous version, I had managed to block these 2 things by:

public class CustomChromeDriver implements DriverSource {

    @Override
    public WebDriver newDriver() {
        try {
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            Proxy proxy = new Proxy();
            String proxyServer = String.format("AProxyIDontWantToDisplay", System.getenv("proxy.username"), System.getenv("proxy.password"));
            proxy.setHttpProxy(proxyServer);
            capabilities.setCapability("proxy", proxy);
            ChromeOptions options = new ChromeOptions();
            options.addArguments(Arrays.asList("--no-sandbox","--ignore-certificate-errors","--homepage=about:blank","--no-first-run"));
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            ChromeDriver driver = new ChromeDriver(capabilities);
            return driver;
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    @Override
    public boolean takesScreenshots() {
        return true;
    }
}

I know there is this one (A link to same issue),
but there are too many answers that don't work.

Anybody that knows how to remove that?

Body:
While the disable-infobars route will work, it will likely suppress the infobar in all cases (as suggested here), not just the case that the OP is referring to. This is overkill at best, and could lead to unexpected and inexplicable behavior in the future if you are not getting some important message.

I think it's better to leverage the provided enable-automation switch by disabling it in the excludeSwitches area of your config/setup while doing nothing with regards to disable-inforbars. The enable-automation switch's description:

Inform users that their browser is being controlled by an automated test.

For nightwatch.conf.js it would look something like this (and worked for me):

desiredCapabilities: {
  ...
  chromeOptions: {
    excludeSwitches: ['enable-automation'],
    ...
  }
}

This should only do what we are after: getting rid of that specific pesky message!

Edit [2017-11-14]: This is now causing an even more annoying Disable Developer Mode Extensions alert/warning. I've tried every relevant-looking flag/switch I could find that might help, but to no avail. I've filed a bug with Chromium, so we'll see and I'll try to swing back through here if I get a resolution.


问:
Format string as UK phone number
I'm looking for a routine that will format a string of numbers as a UK phone number. The routine should account for UK area codes that require different formatting (i.e. London compared to Edinburgh compared to Worcester) as well as mobile numbers.

My phone numbers are stored in the database as strings, containing only numeric characters.

So far I have come up with this, but the performance seems poor.

```<code>/// <summary>
/// Formats a string as a UK phone number
/// </summary>
/// <remarks>
/// 02012345678 becomes 020 1234 5678
/// 01311234567 becomes 0131 123 4567
/// 01905123456 becomes 01905 123456
/// 07816123456 becomes 07816 123456
/// </remarks>
public static string FormatPhoneNumber(string phoneNumber)
{
    string formattedPhoneNumber = null;

    if (!string.IsNullOrEmpty(phoneNumber))
    {
        System.Text.RegularExpressions.Regex area1 = new System.Text.RegularExpressions.Regex(@"^0[1-9]0");
        System.Text.RegularExpressions.Regex area2 = new System.Text.RegularExpressions.Regex(@"^01[1-9]1");

        string formatString;

        if (area1.Match(phoneNumber).Success)
        {
            formatString = "0{0:00 0000 0000}";
        }
        else if (area2.Match(phoneNumber).Success)
        {
            formatString = "0{0:000 000 0000}";
        }
        else
        {
            formatString = "0{0:0000 000000}";
        }

        formattedPhoneNumber = string.Format(formatString, Int64.Parse(phoneNumber));
    }

    return formattedPhoneNumber;
}
</code>```

Thoughts welcomed on how to improve this...

Edit

My initial thoughts are that I should store phone numbers as numeric fields in the database, then I can go without the Int64.Parse and know that they are truly numeric.

Edit 2

The phone numbers will all be UK geographic or UK mobile numbers, so special cases like 0800 do not need to be considered

答:
I'd be tempted to use a tighter set of rules that only check the bear minimum; So on the assumption the leading zero is in the database, pseudo code would be:

```<code>if( phoneNumber.substring(1,1) == "2" )
{
    // 000 0000 0000
}
else if( phoneNumber.substring(1,1) == "1" && (phoneNumber.substring(1,1) == "2" || phoneNumber.substring(3,1) = "1") )
{
    // 0000 000 0000
}
else
{
    // 00000 000000
}
</code>```

NB. your patterns are slightly wrong 023 is a three digit code, and 0800 is not

OwnerDisplayName: Richard E

Title: Format string as UK phone number

Body:
I'm looking for a routine that will format a string of numbers as a UK phone number. The routine should account for UK area codes that require different formatting (i.e. London compared to Edinburgh compared to Worcester) as well as mobile numbers.

My phone numbers are stored in the database as strings, containing only numeric characters.

So far I have come up with this, but the performance seems poor.

///
/// Formats a string as a UK phone number
///
/// <remarks>
/// 02012345678 becomes 020 1234 5678
/// 01311234567 becomes 0131 123 4567
/// 01905123456 becomes 01905 123456
/// 07816123456 becomes 07816 123456
/// </remarks>
public static string FormatPhoneNumber(string phoneNumber)
{
    string formattedPhoneNumber = null;

    if (!string.IsNullOrEmpty(phoneNumber))
    {
        System.Text.RegularExpressions.Regex area1 = new System.Text.RegularExpressions.Regex(@"^0[1-9]0");
        System.Text.RegularExpressions.Regex area2 = new System.Text.RegularExpressions.Regex(@"^01[1-9]1");

        string formatString;

        if (area1.Match(phoneNumber).Success)
        {
            formatString = "0{0:00 0000 0000}";
        }
        else if (area2.Match(phoneNumber).Success)
        {
            formatString = "0{0:000 000 0000}";
        }
        else
        {
            formatString = "0{0:0000 000000}";
        }

        formattedPhoneNumber = string.Format(formatString, Int64.Parse(phoneNumber));
    }

    return formattedPhoneNumber;
}

Thoughts welcomed on how to improve this...

Edit

My initial thoughts are that I should store phone numbers as numeric fields in the database, then I can go without the Int64.Parse and know that they are truly numeric.

Edit 2

The phone numbers will all be UK geographic or UK mobile numbers, so special cases like 0800 do not need to be considered

LastEditorDisplayName: Richard E

Body:
I'd be tempted to use a tighter set of rules that only check the bear minimum; So on the assumption the leading zero is in the database, pseudo code would be:

if( phoneNumber.substring(1,1) == "2" )
{
    // 000 0000 0000
}
else if( phoneNumber.substring(1,1) == "1" && (phoneNumber.substring(1,1) == "2" || phoneNumber.substring(3,1) = "1") )
{
    // 0000 000 0000
}
else
{
    // 00000 000000
}

NB. your patterns are slightly wrong 023 is a three digit code, and 0800 is not

OwnerDisplayName: Rowland Shaw


答:
When you first create the set _Emails, and then set _EmailItr to _Emails->begin(), the iterator is not pointing to anything.  In fact, it is pointing to _Emails->end(), since when the set is empty, begin() and end() are the same.

So later, you attempt to dereference an iterator which points to end(), which is undefined behavior and leads to your crash.

You seem to be assuming that the iterator is actually somehow "updating" behind the scenes as you add new objects to the list.  It's not.  It's always pointing to end().  You need to set it to _Emails->begin() after you insert elements into the set.

Also, unrelated to your question, but: is there some reason you need to allocate _Emails on the heap?

Title: C++ Set Iterator in Class


问:
How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?
I like to be sure that everything will work just by copying the contents of the Java folder and setting the environment variables.

I usually run the installer in a virtual machine, zip the \java folder contents, go back to a snapshot of the virtual machine, and then unzip the compressed file.

I couldn't find a place where the latest JRE / JDK is available as a zip file...

http://java.sun.com/javase/downloads/index.jsp

http://download.java.net/jdk6/

Alternately, is it safe to assume that exe installer from sun just will just unzip the whole thing, without messing around with the registry, environment variables, etc...?

Related: Installing Java manually on Windows?

--
After all this time I found this site that seems to be exactly what I was looking for (2018-05-22)

答:
JDK's can be downloaded from here as zip file nor .exe
http://installbuilder.bitrock.com/java/ </p>


问:
How can I use if/else in a dictionary comprehension?
Does there exist a way in Python 2.7+ to make something like the following?

```<code>{ something_if_true if condition else something_if_false for key, value in dict_.items() }
</code>```

I know you can make anything with just 'if':

```<code>{ something_if_true for key, value in dict_.items() if condition}
</code>```

答:
@Marcin's answer covers it all, but just in case someone wants to see an actual example, I add two below:

Let's say you have the following dictionary of sets

```<code>d = {'key1': {'a', 'b', 'c'}, 'key2': {'foo', 'bar'}, 'key3': {'so', 'sad'}}
</code>```

and you want to create a new dictionary whose keys indicate whether the string 'a' is contained in the values or not, you can use

```<code>dout = {"a_in_values_of_{}".format(k) if 'a' in v else "a_not_in_values_of_{}".format(k): v for k, v in d.items()}
</code>```

which yields

```<code>{'a_in_values_of_key1': {'a', 'b', 'c'},
 'a_not_in_values_of_key2': {'bar', 'foo'},
 'a_not_in_values_of_key3': {'sad', 'so'}}
</code>```

Now let's suppose you have two dictionaries like this

```<code>d1 = {'bad_key1': {'a', 'b', 'c'}, 'bad_key2': {'foo', 'bar'}, 'bad_key3': {'so', 'sad'}}
d2 = {'good_key1': {'foo', 'bar', 'xyz'}, 'good_key2': {'a', 'b', 'c'}}
</code>```

and you want to replace the keys in d1 by the keys of d2 if there respective values are identical, you could do

```<code># here we assume that the values in d2 are unique
# Python 2
dout2 = {d2.keys()[d2.values().index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()}

# Python 3
dout2 = {list(d2.keys())[list(d2.values()).index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()}
</code>```

which gives

```<code>{'bad_key2': {'bar', 'foo'},
 'bad_key3': {'sad', 'so'},
 'good_key2': {'a', 'b', 'c'}}
</code>```

Body:
Does there exist a way in Python 2.7+ to make something like the following?

{ something_if_true if condition else something_if_false for key, value in dict_.items() }

I know you can make anything with just 'if':

{ something_if_true for key, value in dict_.items() if condition}

Body:
@Marcin's answer covers it all, but just in case someone wants to see an actual example, I add two below:

Let's say you have the following dictionary of sets

d = {'key1': {'a', 'b', 'c'}, 'key2': {'foo', 'bar'}, 'key3': {'so', 'sad'}}

and you want to create a new dictionary whose keys indicate whether the string 'a' is contained in the values or not, you can use

dout = {"a_in_values_of_{}".format(k) if 'a' in v else "a_not_in_values_of_{}".format(k): v for k, v in d.items()}

which yields

{'a_in_values_of_key1': {'a', 'b', 'c'},
 'a_not_in_values_of_key2': {'bar', 'foo'},
 'a_not_in_values_of_key3': {'sad', 'so'}}

Now let's suppose you have two dictionaries like this

d1 = {'bad_key1': {'a', 'b', 'c'}, 'bad_key2': {'foo', 'bar'}, 'bad_key3': {'so', 'sad'}}
d2 = {'good_key1': {'foo', 'bar', 'xyz'}, 'good_key2': {'a', 'b', 'c'}}

and you want to replace the keys in d1 by the keys of d2 if there respective values are identical, you could do

# here we assume that the values in d2 are unique
# Python 2
dout2 = {d2.keys()[d2.values().index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()}

# Python 3
dout2 = {list(d2.keys())[list(d2.values()).index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()}

which gives

{'bad_key2': {'bar', 'foo'},
 'bad_key3': {'sad', 'so'},
 'good_key2': {'a', 'b', 'c'}}


答:
What is happening is the requests library is importing a file named html. Since your file is also named html.py and is on the import path it is loaded twice.

Use the convention

```<code>if __name__ == '__main__':
    print("HI")
</code>```

to avoid this.

See this question for more details: What does if __name__ == "__main__": do?

Title: Importing Requests causes print() to print twice

Body:
What is happening is the requests library is importing a file named html. Since your file is also named html.py and is on the import path it is loaded twice.

Use the convention

if __name__ == '__main__':
    print("HI")

to avoid this.

See this question for more details: What does if __name__ == "__main__": do?


问:
I have temporary table which stores delete statement, I need to create a stored procedure during runtime which contain these delete statement
temporary table data:

```<code>Delete from RISKASSESSMENTRULEOVERRIDE
where RISKASSESSMENTRULEOVERRIDE.ApplicationNumber=@ApplicationNumber;

Delete from NONPANELMORTGAGEPRODUCT
where NONPANELMORTGAGEPRODUCT.ApplicationNumber=@ApplicationNumber;
</code>```

and so on...

I need to create a stored procedure which stores these delete statement inside that stored proc, so as when I get multiple values of  @ApplicationNumber, I don't need to iterate over each row, I can just have my query plan saved, as it may increase performance.

I am not sure is it possible?

答:
Rather than trying to create a stored proc, why not just run delete statements with a join to your temp table?

Assuming you have a temp table called #applications_to_delete, with a column called DeleteApplicationNumber, you could just call this:

```<code>delete RISKASSESSMENTRULEOVERRIDE
from
    RISKASSESSMENTRULEOVERRIDE live
    join #applications_to_delete temp
        on (live.ApplicationNumber = temp.DeleteApplicationNumber)

delete NONPANELMORTGAGEPRODUCT
from
    NONPANELMORTGAGEPRODUCT live
    join #applications_to_delete temp
        on (live.ApplicationNumber = temp.DeleteApplicationNumber)
</code>```

Body:
temporary table data:

Delete from RISKASSESSMENTRULEOVERRIDE
where RISKASSESSMENTRULEOVERRIDE.ApplicationNumber=@ApplicationNumber;

Delete from NONPANELMORTGAGEPRODUCT
where NONPANELMORTGAGEPRODUCT.ApplicationNumber=@ApplicationNumber;

and so on...

I need to create a stored procedure which stores these delete statement inside that stored proc, so as when I get multiple values of  @ApplicationNumber, I don't need to iterate over each row, I can just have my query plan saved, as it may increase performance.

I am not sure is it possible?

Body:
Rather than trying to create a stored proc, why not just run delete statements with a join to your temp table?

Assuming you have a temp table called #applications_to_delete, with a column called DeleteApplicationNumber, you could just call this:

delete RISKASSESSMENTRULEOVERRIDE
from
    RISKASSESSMENTRULEOVERRIDE live
    join #applications_to_delete temp
        on (live.ApplicationNumber = temp.DeleteApplicationNumber)

delete NONPANELMORTGAGEPRODUCT
from
    NONPANELMORTGAGEPRODUCT live
    join #applications_to_delete temp
        on (live.ApplicationNumber = temp.DeleteApplicationNumber)


问:
No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0
I've got this issue while updating to the latest Support Library version 26.0.0 (https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0):

Error:(18, 21) No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'.

```<code>/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.
</code>```

com.android.ide.common.process.ProcessException: Failed to execute aapt

The file is from the support library:

```<code><style name="Base.V26.Widget.AppCompat.Toolbar" parent="Base.V7.Widget.AppCompat.Toolbar">
    <item name="android:touchscreenBlocksFocus">true</item>
    <item name="android:keyboardNavigationCluster">true</item>
</style>
</code>```

We're using the following versions:

```<code>ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"

ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"
</code>```

```<code>compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
</code>```

Any ideas?

答:
This issue was caused by one of the libraries for me that needed version 26 for compilation.

Making the targetSdkVersion to 26 will cause other issues and you will have to tweak your app to adapt to the Oreo platform. This is not the correct solution for all.

Just making the compileSdkVersion to 26 and buildToolsVersion to 26.0.2 worked for me.

One should also update all of their support libraries to use 26.1.0 or later.

Body:
I've got this issue while updating to the latest Support Library version 26.0.0 (https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0):

Error:(18, 21) No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'.

/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

The file is from the support library:

We're using the following versions:

ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"

ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"

compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION

Any ideas?


问:
KafkaProducer stops on application startup, saying "Closing the Kafka producer with timeoutMillis = 30000 ms"
I'm trying to run a custom Spring cloud Stream app starter, and getting the following INFO log,

```<code>2017-11-14 14:59:24.600  INFO 30300 --- [           main] o.a.kafka.common.utils.AppInfoParser     : Kafka version : 0.10.1.1
2017-11-14 14:59:24.600  INFO 30300 --- [           main] o.a.kafka.common.utils.AppInfoParser     : Kafka commitId : f10ef2720b03b247
2017-11-14 14:59:24.747  INFO 30300 --- [           main] o.a.k.clients.producer.KafkaProducer     : Closing the Kafka producer with timeoutMillis = 30000 ms.
2017-11-14 14:59:24.768  INFO 30300 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'websocket-source.output' has 1 subscriber(s).
2017-11-14 14:59:24.773  INFO 30300 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-11-14 14:59:24.906  INFO 30300 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
</code>```

My problem is my app doesn't work as intended (I can't connect to the websocket server, which this app will bring up) so I expect some clues from the kafka log. May be some missing dependency but I couldn't find one.

Is it an error? How can I debug this?

答:
When you build Spring Boot Web application, you should keep in mind that security is switched on by default - HTTP Basic Authorization

The default user is, err, user.

The generate password you can find in logs. For example:

```<code>2017-11-14 11:56:09.756  INFO 7304 --- [           main] b.a.s.AuthenticationManagerConfiguration :

Using default security password: 396c8870-f36e-44a5-aaea-735d5a8e950a
</code>```

Although you can turn it off as well. For example command line arg:

```<code>--security.basic.enabled=false
</code>```

https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#howto-switch-off-spring-boot-security-configuration

Body:
I'm trying to run a custom Spring cloud Stream app starter, and getting the following INFO log,

2017-11-14 14:59:24.600  INFO 30300 --- [           main] o.a.kafka.common.utils.AppInfoParser     : Kafka version : 0.10.1.1
2017-11-14 14:59:24.600  INFO 30300 --- [           main] o.a.kafka.common.utils.AppInfoParser     : Kafka commitId : f10ef2720b03b247
2017-11-14 14:59:24.747  INFO 30300 --- [           main] o.a.k.clients.producer.KafkaProducer     : Closing the Kafka producer with timeoutMillis = 30000 ms.
2017-11-14 14:59:24.768  INFO 30300 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'websocket-source.output' has 1 subscriber(s).
2017-11-14 14:59:24.773  INFO 30300 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-11-14 14:59:24.906  INFO 30300 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel

My problem is my app doesn't work as intended (I can't connect to the websocket server, which this app will bring up) so I expect some clues from the kafka log. May be some missing dependency but I couldn't find one.

Is it an error? How can I debug this?

Body:
When you build Spring Boot Web application, you should keep in mind that security is switched on by default - HTTP Basic Authorization

The default user is, err, user.

The generate password you can find in logs. For example:

2017-11-14 11:56:09.756  INFO 7304 --- [           main] b.a.s.AuthenticationManagerConfiguration :

Using default security password: 396c8870-f36e-44a5-aaea-735d5a8e950a

Although you can turn it off as well. For example command line arg:

--security.basic.enabled=false

https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#howto-switch-off-spring-boot-security-configuration


问:
Django & ajax like button only works in first item
good morning, I just got a problem with my like button, it's only working on the first item and it does not work on the others

This is my views.py

```<code>@login_required
@require_POST
def like(request):
    if request.method == 'POST':
        user = request.user
        slug = request.POST.get('slug', None)
        tweet = get_object_or_404(Tweet, slug=slug)
        if tweet.likes.filter(id=user.id).exists():
            tweet.likes.remove(user)
            message = 'Your disliked this'
        else:
            tweet.likes.add(user)
            message = 'You liked this'
    ctx = {'likes_count': tweet.total_likes, 'message':message}
    return HttpResponse(json.dumps(ctx), content_type='application/json')
</code>```

When I click in the like button  on the first item this works fine but, when I click like button in the other items this not works.

My models.py

```<code>class Tweet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField('Titulo', max_length=100)
    text = models.CharField(max_length=160)
    slug = models.SlugField(max_length=180)
    likes = models.ManyToManyField(User, related_name='likes')
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

    @property
    def total_likes(self):
        return self.likes.count()
</code>```

and this is my scrip ajax:

```<code><script type="text/javascript">
$("#like-button").click(function(e){
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: "/like/",
    data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
    dataType: "json",
    success: function(response){
      alert("This tweet has " + response.likes_count);
    },
    error: function(rs, r){
      alert(rs.responseText);
    }
  });
});

</script>
</code>```

My html button:

```<code>    <input
    type="button"
    id="like-button"
    name="{{tweet.slug}}"
    value="Like {{tweet.total_likes}}"
    class="btn btn-primary">
</code>```

答: You have multiple buttons, all with the same id of "like-button"? If that is the case, try deleting the ID since, from what I can see in the code, it isn't being used. ID's should always be completely unique. Having multiple elements with the same ID usually cause issues like this.</p>

Body:
good morning, I just got a problem with my like button, it's only working on the first item and it does not work on the others

This is my views.py

@login_required
@require_POST
def like(request):
    if request.method == 'POST':
        user = request.user
        slug = request.POST.get('slug', None)
        tweet = get_object_or_404(Tweet, slug=slug)
        if tweet.likes.filter(id=user.id).exists():
            tweet.likes.remove(user)
            message = 'Your disliked this'
        else:
            tweet.likes.add(user)
            message = 'You liked this'
    ctx = {'likes_count': tweet.total_likes, 'message':message}
    return HttpResponse(json.dumps(ctx), content_type='application/json')

When I click in the like button  on the first item this works fine but, when I click like button in the other items this not works.

My models.py

class Tweet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField('Titulo', max_length=100)
    text = models.CharField(max_length=160)
    slug = models.SlugField(max_length=180)
    likes = models.ManyToManyField(User, related_name='likes')
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

    @property
    def total_likes(self):
        return self.likes.count()

and this is my scrip ajax:

My html button:

    <input
    type="button"
    id="like-button"
    name="{{tweet.slug}}"
    value="Like {{tweet.total_likes}}"
    class="btn btn-primary">


答:
If you have multiple inputs you should use a class, not an id.

```<code><input
type="button"
class="like-button"
name="{{tweet.slug}}"
value="Like {{tweet.total_likes}}"
class="btn btn-primary">
</code>```

You'll also have to update your ajax:

```<code>$(".like-button").click(function(e){
</code>```

Title: Django & ajax like button only works in first item

Body:
If you have multiple inputs you should use a class, not an id.

<input
type="button"
class="like-button"
name="{{tweet.slug}}"
value="Like {{tweet.total_likes}}"
class="btn btn-primary">

You'll also have to update your ajax:

$(".like-button").click(function(e){


问:
Read content of file and put particular portion of content in separate files using bash
I would like to get specific file contains from single file and put into separate files via bash. I have tried getting test1 file contain using below code and able to get it but i'm failed when getting everything in respected files.

Tried code:

```<code>reportFile=/report.txt
test1File=/test1.txt
test2File=/test2.txt
test3File=/test3.txt

totalLineNo=`cat ${reportFile} | wc -l`
test1LineNo=`grep -n "Test1 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test2LineNo=`grep -n "Test2 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test3LineNo=`grep -n "Test3 file content :" ${reportFile} | grep -Eo '^[^:]+'`

exactTest1LineNo=`echo $(( ${test1LineNo} - 1 ))`
exactTest2LineNo=`echo $(( ${test2LineNo} -1 ))`
exactTest3LineNo=`echo $(( ${test3LineNo} -1 ))`

test1Content=`cat ${reportFile} | head -n ${exactTest1LineNo}`
test3Content=`cat ${reportFile} | tail -n ${exactTest3LineNo}`

echo -e "${test1Content}\r" >> ${test1File}
echo -e "${test3Content}\r" >> ${test3File}
</code>```

report.txt:

```<code>-------------------------------------

My Report:

Test1 file content:
1
2
3
4
5
6

Test2 file content:
7
8
9
10

Test3 file content:
11
12
13
14
15

Note: Find my report above.

-------------------------------------
</code>```

test1.txt (expected):

```<code>1
2
3
4
5
6
</code>```

test2.txt (expected):

```<code>7
8
9
10
</code>```

test3.txt (expected):

```<code>11
12
13
14
15
</code>```

答:
With single awk command:

```<code>awk '/^Test[0-9] file content:/{ f=1; fn=tolower($1)".txt"; next }
     f && NF{ print > fn }!NF{ f=0 }' report.txt
</code>```

Viewing results:

```<code>$ head test[0-9].txt
==> test1.txt <==
1
2
3
4
5
6

==> test2.txt <==
7
8
9
10

==> test3.txt <==
11
12
13
14
15
</code>```

Body:
I would like to get specific file contains from single file and put into separate files via bash. I have tried getting test1 file contain using below code and able to get it but i'm failed when getting everything in respected files.

Tried code:

reportFile=/report.txt
test1File=/test1.txt
test2File=/test2.txt
test3File=/test3.txt

totalLineNo=`cat ${reportFile} | wc -l`
test1LineNo=`grep -n "Test1 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test2LineNo=`grep -n "Test2 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test3LineNo=`grep -n "Test3 file content :" ${reportFile} | grep -Eo '^[^:]+'`

exactTest1LineNo=`echo $(( ${test1LineNo} - 1 ))`
exactTest2LineNo=`echo $(( ${test2LineNo} -1 ))`
exactTest3LineNo=`echo $(( ${test3LineNo} -1 ))`

test1Content=`cat ${reportFile} | head -n ${exactTest1LineNo}`
test3Content=`cat ${reportFile} | tail -n ${exactTest3LineNo}`

echo -e "${test1Content}\r" >> ${test1File}
echo -e "${test3Content}\r" >> ${test3File}

report.txt:

-------------------------------------

My Report:

Test1 file content:
1
2
3
4
5
6

Test2 file content:
7
8
9
10

Test3 file content:
11
12
13
14
15

Note: Find my report above.

-------------------------------------

test1.txt (expected):

1
2
3
4
5
6

test2.txt (expected):

7
8
9
10

test3.txt (expected):

11
12
13
14
15

Body:
With single awk command:

awk '/^Test[0-9] file content:/{ f=1; fn=tolower($1)".txt"; next }
     f && NF{ print > fn }!NF{ f=0 }' report.txt

Viewing results:

$ head test[0-9].txt
==> test1.txt <==
1
2
3
4
5
6

==> test2.txt <==
7
8
9
10

==> test3.txt <==
11
12
13
14
15


问:
Git LFS skipping File but git starts pushing it to repo
I have a big file in my Github repo which i normally uploaded with git lfs.
For a newer commit, i had to change the file, but now on pushing, git lfs is skipping the file and normal git tries to upload it. This, of course, fails, cause it exceeds the maximum file size of Github.
When i run

GIT_TRACE=1 git push

this is the output:

trace git-lfs: run_command: 'git' version trace git-lfs: run_command:
  'git' config -l trace git-lfs: tq: running as batched queue, batch
  size of 100 trace git-lfs: run_command: ssh -- git@github.com
  git-lfs-authenticate myRepo.git upload
  trace git-lfs: HTTP: POST
  https://lfs.github.com/myRepo/locks/verify
  trace git-lfs: HTTP: 200 trace git-lfs: HTTP:
  {"ours":[],"theirs":[],"next_cursor":""}

trace git-lfs: pre-push: refs/heads/master
  d7b0e4138403023433894f756d63bdadfabac125 refs/heads/master
  683a30586bc68758230da6686fa902d4621b358a trace git-lfs: run_command:
  git rev-list --objects d7b0e4138403023433894f756d63bdadfabac125 --not
  --remotes=origin -- trace git-lfs: run_command: git cat-file --batch trace git-lfs: tq: sending batch of size 1 trace git-lfs: ssh cache:
  git@github.com git-lfs-authenticate
  myRepo.git upload trace git-lfs: api:
  batch 1 files trace git-lfs: HTTP: POST
  https://lfs.github.com/myRepo/objects/batch
  trace git-lfs: HTTP: 200 trace git-lfs: HTTP:
  {"objects":[{"oid":"1e24fed72634c9217ce7856d11ee204d38eb154fc90572a8ef047007f2211a6c","size":246116656}]}
  trace git-lfs: tq: starting transfer adapter "basic" Git LFS: (0 of 0
  files, 1 skipped) 0 B / 0 B, 234.72 MB skipped

  17:22:37.083227 run-command.c:343       trace: run_command:
  'pack-objects' '--all-progress-implied' '--revs' '--stdout' '--thin'
  '--delta-base-offset' '--progress' 17:22:37.084316 exec_cmd.c:128

  trace: exec: 'git' 'pack-objects' '--all-progress-implied' '--revs'
  '--stdout' '--thin' '--delta-base-offset' '--progress' 17:22:37.088704
  git.c:348               trace: built-in: git 'pack-objects'
  '--all-progress-implied' '--revs' '--stdout' '--thin'
  '--delta-base-offset' '--progress' Counting objects: 109, done. Delta
  compression using up to 4 threads.

Compressing objects: 100%
  (106/106), done. Writing objects: 100% (109/109), 73.55 MiB | 1.81
  MiB/s, done. Total 109 (delta 74), reused 0 (delta 0) remote:
  Resolving deltas: 100% (74/74), completed with 53 local objects.
  remote: error: GH001: Large files detected. You may want to try Git
  Large File Storage - https://git-lfs.github.com. remote: error: Trace:
  e87aee9bcda79c0a788ae345112c9d37 remote: error: See
  http://git.io/iEPt8g for more information. remote: error: File
  src/ios/sdk/myLib.framework/Framework is 234.72 MB; this
  exceeds GitHub's file size limit of 100.00 MB To
  git@github.com:myRepo.git  ! [remote
  rejected] master -> master (pre-receive hook declined) error: failed
  to push some refs to
  'git@github.com:myRepo.git'

答:
It sounds like the lfs clean filter wasn't applied when adding the new version of the file to the index.  If the filename didn't change, then that probably means there isn't a .gitattributes file associating that path with LFS.  (Either there never was one and you somehow ran the clean filter manually when you first added the old version of the file; or there was one but it didn't get committed; or it's since been removed or modified in a way that no longer matches the file; etc...)

And to clarify - if the filename did change, it probably changed to something that doesn't match any path in the .gitattributes file.  So you'd need to update .gitattributes to match the new filename.

Once a file is staged with LFS tracking, what git sees (in the index and in the database) is the LFS pointer file.  So even if the attributes file were removed, it wouldn't immediately cause the large file to be uploaded in the repo database.  But if you re-add the file (as you'd have to after modifying it) and the attributes aren't set up at that time, then the entire file gets staged instead of a pointer file.

I think what LFS is skipping in your above trace is the old version of the file - because the server already has that.  This is normal.

But the commit you're trying to push is no good; it has the full file irrevocably embedded in it.  You need to amend (or rebase, or otherwise rewrite) each commit that has the full file in it.  Fortunately since this is preventing sharing of the commits you should be able to safely rewrite them without worrying about anyone else being put in an "upstream rebase" situation.

So to summarize:

Make sure you have a .gitattributes file that assigns the LFS attributes to a path matching the large file.  You should add this .gitattributes file to the index.

Remove and re-index the new version of the large file.

```<code>git rm --cached path/to/big/file
git add path/to/big/file
</code>```

If .gitattributes is set up correctly, the add will go through the LFS clean filter this time; a pointer file will be added to the index and a new LFS object will be created.

```<code>git commit --amend
</code>```

to replace the commit that has the large BLOB embedded in it with a new one that uses LFS.

Now try to push.  If it still fails, that means there are probably other commits you need to fix, and then things could get more involved.

Body:
It sounds like the lfs clean filter wasn't applied when adding the new version of the file to the index.  If the filename didn't change, then that probably means there isn't a .gitattributes file associating that path with LFS.  (Either there never was one and you somehow ran the clean filter manually when you first added the old version of the file; or there was one but it didn't get committed; or it's since been removed or modified in a way that no longer matches the file; etc...)

And to clarify - if the filename did change, it probably changed to something that doesn't match any path in the .gitattributes file.  So you'd need to update .gitattributes to match the new filename.

Once a file is staged with LFS tracking, what git sees (in the index and in the database) is the LFS pointer file.  So even if the attributes file were removed, it wouldn't immediately cause the large file to be uploaded in the repo database.  But if you re-add the file (as you'd have to after modifying it) and the attributes aren't set up at that time, then the entire file gets staged instead of a pointer file.

I think what LFS is skipping in your above trace is the old version of the file - because the server already has that.  This is normal.

But the commit you're trying to push is no good; it has the full file irrevocably embedded in it.  You need to amend (or rebase, or otherwise rewrite) each commit that has the full file in it.  Fortunately since this is preventing sharing of the commits you should be able to safely rewrite them without worrying about anyone else being put in an "upstream rebase" situation.

So to summarize:

Make sure you have a .gitattributes file that assigns the LFS attributes to a path matching the large file.  You should add this .gitattributes file to the index.

Remove and re-index the new version of the large file.

git rm --cached path/to/big/file
git add path/to/big/file

If .gitattributes is set up correctly, the add will go through the LFS clean filter this time; a pointer file will be added to the index and a new LFS object will be created.

git commit --amend

to replace the commit that has the large BLOB embedded in it with a new one that uses LFS.

Now try to push.  If it still fails, that means there are probably other commits you need to fix, and then things could get more involved.