问:
Possible to Set Initial Array to Returned Nested Objects
I have some fetched data that returns an array of objects, each with a nested array of objects. The nested array I have mentioned, blog_comments, can have a value dynamically inserted from a form on my page and I have a parent-child function that handles the POST and array insertion, but I can't seem to figure out a way to set the array initially to each of the blog_comments objects. Is there a way to do a nested map and set the objects with setState? Should this be handled in the constructor of my stateful component? componentDidMount?

JSON:

```<code>[
  {
    "blogId": 105,
    "blogDateSlug": "08\/15\/2017",
    "title": "Working Hard",
    "discovery": "lorem ipsum",
    "created_at": "2017-08-15T23:23:50.329Z",
    "updated_at": "2017-08-15T23:25:23.826Z",
    "blog_user": {
      "fullNameSlug": "Mike Rellis",
      "firstName": "Mike",
      "lastName": "Rellis",
      "picture": "https://s3.amazonaws.com/certain-web-assets/user-example-two.jpg"
    },
    "blog_comments": [
      {
        "createdAtDateSlug": "8\/15\/2017 11:10 AM",
        "comment": "Great work with this article",
        "created_at": "2017-08-16T10:44:52.492Z",
        "updated_at": "2017-08-16T10:44:52.492Z",
        "blog_user": {
          "fullNameSlug": "Sandra Matthews",
          "firstName": "Sandra",
          "lastName": "Matthews",
          "picture": "https://s3.amazonaws.com/certain-web-assets/user-example-one.jpg"
        }
      }
    ]
  }
]
</code>```

Here is my data fetch:

```<code>class BlogFeedContainer extends React.Component{
    constructor(props, context) {
        super(props, context);
        this.state = this.context.data || window.__INITIAL_STATE__ || {blogs: []};
    }

    fetchList() {
        fetch('http://localhost:3000/api/test')
            .then(res => {
                return res.json();
            })
            .then(data => {
                console.log(data);
                this.setState({ blogs: data.blog, user: data.user, csrf: data.csrfToken });
            })
            .catch(err => {
                console.log(err);
            });
    }

    componentDidMount() {
        this.fetchList();
    }

    render() {
        return (
            <div className="container">
                <BlogFeed {...this.state} />
            </div>
        )
    }
};
</code>```

Here is the loop skeleton that will return the correct object I'm trying to set to my comments state array:

```<code>this.props.blogs.map((blog, index) => {
    { this.props.blog_comments.map((comment, i) => {

    })
})
</code>```

Here is the component handling the array insertion and should handle the initial array state:

```<code>class BlogFeed extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            comments: []
        };
        this.updateCommentsFunc = this.updateCommentsFunc.bind(this);
    }

    componentDidMount(){
        this.props.blogs.map((blog) => {
            console.log("setCommentArr() triggered");
            console.log(blog);
        })
    }

    setCommentArr(){

    }

    updateCommentsFunc(newComments){
        console.log("Update Comments Func Triggered");
        var updatedCommentArr = this.state.comments.slice();
        updatedCommentArr.push(newComments)
        this.setState({comments: updatedCommentArr});
        console.log(this.state.comments);
    }

    render(){

        return (
            <div>
            {
                this.props.blogs.map((blog, index) => {
                    return (
                        <div className="row">
                            <div className="col-md-6 col-md-offset-3 blog-card">
                                <BlogCard {...blog} key={blog.blogIdHash} user={this.props.user} />
                                <Comments {...blog} key={index} blogId={blog.blogIdHash} csrf={this.props.csrf} updateComments={this.updateCommentsFunc}/>
                            </div>
                        </div>
                    );
                })
            }
            </div>
        );
    }
}
</code>```

答:
Use the componentWillReceiveProps(nextProps) lifecycle method. Here you can call this.setState() on your BlogFeed Component in response to changes in props after the fetch completes.

What you would pass to this.setState() would depend on how you want comments represented in the Component state and what you are going to do with that state.

Could be the flattened array of comments:

```<code>const comments = nextProps.blogs
  .reduce((arr, blog) => arr.concat(blog.blog_comments), []);
</code>```

Or it could be an object of comments keyed to the blogId:

```<code>const comments = nextProps.blogs
  .reduce((obj, blog) => Object.assign(obj, { [blog.blogId]: blog.blog_comments }), {});
</code>```

then just call with the desired state change:

```<code>this.setState({ comments })
</code>```

Body:
I have some fetched data that returns an array of objects, each with a nested array of objects. The nested array I have mentioned, blog_comments, can have a value dynamically inserted from a form on my page and I have a parent-child function that handles the POST and array insertion, but I can't seem to figure out a way to set the array initially to each of the blog_comments objects. Is there a way to do a nested map and set the objects with setState? Should this be handled in the constructor of my stateful component? componentDidMount?

JSON:

[
  {
    "blogId": 105,
    "blogDateSlug": "08\/15\/2017",
    "title": "Working Hard",
    "discovery": "lorem ipsum",
    "created_at": "2017-08-15T23:23:50.329Z",
    "updated_at": "2017-08-15T23:25:23.826Z",
    "blog_user": {
      "fullNameSlug": "Mike Rellis",
      "firstName": "Mike",
      "lastName": "Rellis",
      "picture": "https://s3.amazonaws.com/certain-web-assets/user-example-two.jpg"
    },
    "blog_comments": [
      {
        "createdAtDateSlug": "8\/15\/2017 11:10 AM",
        "comment": "Great work with this article",
        "created_at": "2017-08-16T10:44:52.492Z",
        "updated_at": "2017-08-16T10:44:52.492Z",
        "blog_user": {
          "fullNameSlug": "Sandra Matthews",
          "firstName": "Sandra",
          "lastName": "Matthews",
          "picture": "https://s3.amazonaws.com/certain-web-assets/user-example-one.jpg"
        }
      }
    ]
  }
]

Here is my data fetch:

class BlogFeedContainer extends React.Component{
    constructor(props, context) {
        super(props, context);
        this.state = this.context.data || window.__INITIAL_STATE__ || {blogs: []};
    }

    fetchList() {
        fetch('http://localhost:3000/api/test')
            .then(res => {
                return res.json();
            })
            .then(data => {
                console.log(data);
                this.setState({ blogs: data.blog, user: data.user, csrf: data.csrfToken });
            })
            .catch(err => {
                console.log(err);
            });
    }

    componentDidMount() {
        this.fetchList();
    }

    render() {
        return (

                <BlogFeed {...this.state} />

        )
    }
};

Here is the loop skeleton that will return the correct object I'm trying to set to my comments state array:

this.props.blogs.map((blog, index) => {
    { this.props.blog_comments.map((comment, i) => {

    })
})

Here is the component handling the array insertion and should handle the initial array state:

class BlogFeed extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            comments: []
        };
        this.updateCommentsFunc = this.updateCommentsFunc.bind(this);
    }

    componentDidMount(){
        this.props.blogs.map((blog) => {
            console.log("setCommentArr() triggered");
            console.log(blog);
        })
    }

    setCommentArr(){

    }

    updateCommentsFunc(newComments){
        console.log("Update Comments Func Triggered");
        var updatedCommentArr = this.state.comments.slice();
        updatedCommentArr.push(newComments)
        this.setState({comments: updatedCommentArr});
        console.log(this.state.comments);
    }

    render(){

        return (

            {
                this.props.blogs.map((blog, index) => {
                    return (

                                <BlogCard {...blog} key={blog.blogIdHash} user={this.props.user} />
                                <Comments {...blog} key={index} blogId={blog.blogIdHash} csrf={this.props.csrf} updateComments={this.updateCommentsFunc}/>

                    );
                })
            }

        );
    }
}

Body:
Use the componentWillReceiveProps(nextProps) lifecycle method. Here you can call this.setState() on your BlogFeed Component in response to changes in props after the fetch completes.

What you would pass to this.setState() would depend on how you want comments represented in the Component state and what you are going to do with that state.

Could be the flattened array of comments:

const comments = nextProps.blogs
  .reduce((arr, blog) => arr.concat(blog.blog_comments), []);

Or it could be an object of comments keyed to the blogId:

const comments = nextProps.blogs
  .reduce((obj, blog) => Object.assign(obj, { [blog.blogId]: blog.blog_comments }), {});

then just call with the desired state change:

this.setState({ comments })


来源: stackexchange

问:
Find a list of Patterns in a input stream
Suppose you have an input character stream (StreamReader) and you have a list of pattens like ABCAS, ASGKT. KHTSD etc.
You need to read the stream one by one character and you need to keep count on number of each pattern found so far and when EOF occures just print all the patterns along with count.

Example:

Input String:   011100010

Pattern 1:  011

Pattern 2: 010

Output:

   011 => 1

   010 => 1

答:
There are existing tools for solving this problem. They are called lexers, and on of the most well-known example is lex, mentioned in the comments.

However, if you need to implement it yourself, Aho-Corasick algorithm does the thing. Given a set of strings S = s_1, ..., s_k of total length L, it builds a trie on these strings and makes an automaton based on this trie. Now you feed your input string into this automaton. At any time it is capable of telling you the set of strings from S that end at current position, with time proportional to the number of such strings.

For example, if S = {"aba", "bababa", "ba", "abacaba"} and your have inputted the string rabacaba, the output of the algorithm will be {0, 2, 3} (the indices of the strings which end at the last fed position).

Having such structure, maintaining occurred strings and their count is straightforward: just make a query to the structure after each character of the stream.

ContentLicense: CC BY-SA 3.0


问:
Using $and query on array of embedded documents in mongodb
I have a collection like this

```<code>/* 9 */
{
    "_id" : ObjectId("5a0da2f9a0d00b28dcc69b29"),
    "list_id" : ObjectId("59ec6c97a0d00bc96b5680d4"),
    "rowdatas" : [
        {
            "_id" : ObjectId("5a0da2f9a0d00b28dcc69b2a"),
            "field_id" : "59ec6d33a0d00bc96b5680d8",
            "field_name" : "Title2",
            "field_value" : "Arvind",
            "field_type" : "sltext"
        },
        {
            "_id" : ObjectId("5a0da2faa0d00b28dcc69b2b"),
            "field_id" : "59ec8a2ea0d00bc96b568111",
            "field_name" : "Department",
            "field_value" : "AS",
            "field_type" : "dropdown"
        }
    ]
}

/* 10 */
{
    "_id" : ObjectId("5a0da306a0d00b28dcc69b2c"),
    "list_id" : ObjectId("59ec6c97a0d00bc96b5680d4"),
    "rowdatas" : [
        {
            "_id" : ObjectId("5a0da306a0d00b28dcc69b2d"),
            "field_id" : "59ec6d33a0d00bc96b5680d8",
            "field_name" : "Title2",
            "field_value" : "Arnab",
            "field_type" : "sltext"
        },
        {
            "_id" : ObjectId("5a0da306a0d00b28dcc69b2e"),
            "field_id" : "59ec8a2ea0d00bc96b568111",
            "field_name" : "Department",
            "field_value" : "SD",
            "field_type" : "dropdown"
        }
    ]
}

/* 11 */
{
    "_id" : ObjectId("5a0da30fa0d00b28dcc69b2f"),
    "list_id" : ObjectId("59ec6c97a0d00bc96b5680d4"),
    "rowdatas" : [
        {
            "_id" : ObjectId("5a0da30fa0d00b28dcc69b30"),
            "field_id" : "59ec6d33a0d00bc96b5680d8",
            "field_name" : "Title2",
            "field_value" : "Ankush",
            "field_type" : "sltext"
        },
        {
            "_id" : ObjectId("5a0da30fa0d00b28dcc69b31"),
            "field_id" : "59ec8a2ea0d00bc96b568111",
            "field_name" : "Department",
            "field_value" : "SD",
            "field_type" : "dropdown"

        }
    ]
}
</code>```

I'm trying to query this collection in a way that it returns only record no 9 and 10 that has the

"field_name" : "Department" and
"field_value" : "SD"

The query I have tried is

```<code> db.getCollection('ldata').find(
  { $and: [
                {"list_id": ObjectId("59ec6c97a0d00bc96b5680d4")} ,
                { 'rowdatas.field_name': 'Department', 'rowdatas.field_value': 'AS' },
           ]
   }
 )
</code>```

This returns the me 2 records correctly thats is 9 and 10. However, if I pass 'rowdatas.field_value': 'Arnab' it still returns me record no 10. This should return me zero result since I'm trying to find records with whose Department name is  "SD" . In this case its matching the field_value without combining the field_name for the AND query.

答:
You need to add $elemMatch to your query. So your query would look like this:

```<code>db.getCollection('ldata').find(
  { $and: [
                {"list_id": ObjectId("59ec6c97a0d00bc96b5680d4")} ,
                { rowdatas: {$elemMatch: {'field_name': 'Department', 'field_value': 'Arnab' }}},
           ]
   }
 )
</code>```

This would return no results.

To explain it a little bit better. What your query does:

```<code>$and: [
                {"list_id": ObjectId("59ec6c97a0d00bc96b5680d4")} ,
                { 'rowdatas.field_name': 'Department', 'rowdatas.field_value': 'Arnab' },
           ]
   }
</code>```

It simply says, find any document where the array rowdatas has a field_name: 'Department', and a field_value: 'Arnab'. This is true for document 10, because it looks inside the complete array rowdata.

If you now add the $elemMatch query operator like that:

```<code>{ rowdatas: {$elemMatch: {'field_name': 'Department', 'field_value': 'Arnab' }}}
</code>```

Then you are simply saying you want both these fields (field_name and field_value) to match in a single array entry.

Hope you understand the difference between querying an array field through a dot (rowdatas.field_name) and $elemMatch (rowdatas: {$elemMatch: {'field_name': ...) a little better now.

Body:
I have a collection like this

/* 9 */
{
    "_id" : ObjectId("5a0da2f9a0d00b28dcc69b29"),
    "list_id" : ObjectId("59ec6c97a0d00bc96b5680d4"),
    "rowdatas" : [
        {
            "_id" : ObjectId("5a0da2f9a0d00b28dcc69b2a"),
            "field_id" : "59ec6d33a0d00bc96b5680d8",
            "field_name" : "Title2",
            "field_value" : "Arvind",
            "field_type" : "sltext"
        },
        {
            "_id" : ObjectId("5a0da2faa0d00b28dcc69b2b"),
            "field_id" : "59ec8a2ea0d00bc96b568111",
            "field_name" : "Department",
            "field_value" : "AS",
            "field_type" : "dropdown"
        }
    ]
}

/* 10 */
{
    "_id" : ObjectId("5a0da306a0d00b28dcc69b2c"),
    "list_id" : ObjectId("59ec6c97a0d00bc96b5680d4"),
    "rowdatas" : [
        {
            "_id" : ObjectId("5a0da306a0d00b28dcc69b2d"),
            "field_id" : "59ec6d33a0d00bc96b5680d8",
            "field_name" : "Title2",
            "field_value" : "Arnab",
            "field_type" : "sltext"
        },
        {
            "_id" : ObjectId("5a0da306a0d00b28dcc69b2e"),
            "field_id" : "59ec8a2ea0d00bc96b568111",
            "field_name" : "Department",
            "field_value" : "SD",
            "field_type" : "dropdown"
        }
    ]
}

/* 11 */
{
    "_id" : ObjectId("5a0da30fa0d00b28dcc69b2f"),
    "list_id" : ObjectId("59ec6c97a0d00bc96b5680d4"),
    "rowdatas" : [
        {
            "_id" : ObjectId("5a0da30fa0d00b28dcc69b30"),
            "field_id" : "59ec6d33a0d00bc96b5680d8",
            "field_name" : "Title2",
            "field_value" : "Ankush",
            "field_type" : "sltext"
        },
        {
            "_id" : ObjectId("5a0da30fa0d00b28dcc69b31"),
            "field_id" : "59ec8a2ea0d00bc96b568111",
            "field_name" : "Department",
            "field_value" : "SD",
            "field_type" : "dropdown"

        }
    ]
}

I'm trying to query this collection in a way that it returns only record no 9 and 10 that has the

"field_name" : "Department" and
"field_value" : "SD"

The query I have tried is

 db.getCollection('ldata').find(
  { $and: [
                {"list_id": ObjectId("59ec6c97a0d00bc96b5680d4")} ,
                { 'rowdatas.field_name': 'Department', 'rowdatas.field_value': 'AS' },
           ]
   }
 )

This returns the me 2 records correctly thats is 9 and 10. However, if I pass 'rowdatas.field_value': 'Arnab' it still returns me record no 10. This should return me zero result since I'm trying to find records with whose Department name is  "SD" . In this case its matching the field_value without combining the field_name for the AND query.

Body:
You need to add $elemMatch to your query. So your query would look like this:

db.getCollection('ldata').find(
  { $and: [
                {"list_id": ObjectId("59ec6c97a0d00bc96b5680d4")} ,
                { rowdatas: {$elemMatch: {'field_name': 'Department', 'field_value': 'Arnab' }}},
           ]
   }
 )

This would return no results.

To explain it a little bit better. What your query does:

$and: [
                {"list_id": ObjectId("59ec6c97a0d00bc96b5680d4")} ,
                { 'rowdatas.field_name': 'Department', 'rowdatas.field_value': 'Arnab' },
           ]
   }

It simply says, find any document where the array rowdatas has a field_name: 'Department', and a field_value: 'Arnab'. This is true for document 10, because it looks inside the complete array rowdata.

If you now add the $elemMatch query operator like that:

{ rowdatas: {$elemMatch: {'field_name': 'Department', 'field_value': 'Arnab' }}}

Then you are simply saying you want both these fields (field_name and field_value) to match in a single array entry.

Hope you understand the difference between querying an array field through a dot (rowdatas.field_name) and $elemMatch (rowdatas: {$elemMatch: {'field_name': ...) a little better now.


问:
UI best practice question: Cancel button or Cancel link
I have a discussion with a colleague about what the "web standard" is for canceling in an form. In our discussion we have a "change password" page as example. We have a designed "send" button and "cancel" button. Both the same design.

He claims that in web standard a cancel button is no longer a button but a link transferring the user to another page. In my opinion, for those pages including a cancel button it actually is a cancel button which either resets the form and/or send the user to the prevision page.

Who is correct? Link or button... or both? And why? Any links to where this kind of standard is decided?

Br,

Paul Peelen

EDIT
I guess the answer with most votes will be the "correct answer"?

答:
Don't put it on there at all. Users are used to the convention that if they are somewhere where they don't want to be, they will use the back button. Your job designing the UI is to guide a user through a process and allow them to make logical choices. You have already commented yourself by saying a cancel button could have one of two outcomes but how does a user know which one it is? Some users may expect it to reset a form and it takes them away from the page and vice versa.

In my opinion, your form does not need a cancel button and it would aid the user if it was just omitted completely.

ContentLicense: CC BY-SA 2.5


问:
Updating state on first render only?
Using react-native, I'm creating sub-Components within the parent App and providing their position to the array this.state.objLocation within the parent App.

I can get the initial location data into the array straight after the render, but because my subcomponents are draggable, each time they re-render on drag, it adds a new position object to the array.

I'd like to avoid this, and I thought that creating this.state = { firstRender: true } in the constructor and then using componentDidMount = () => { this.setState({ firstRender: false }) } after the first render would allow me to create a 'gate' to stop the addition of the extra position objects.

I can see that if I comment out //componentDidMount = () => { this.setState({ firstRender: false }) } then I will get multiple entries to my array but if it's included in the class I get absolutely none.

So possibly my interpretation of the render lifecycle and componentDidMount is incorrect?

Here is my code.

// App

```<code>import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

const dataArray = [{num: 1,id: 'A',},{num: 2,id: 'B',},{num: 3,id: 'Z',}]

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
            objLocation: [],
            firstRender: true,
        };
    }
    render(){
        return (
            <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                    <Text>Draggable Container</Text> {dataArray.map( d => { return(
                    <Draggable
                        id={d.id}
                        onLayout={ e=> this.onLayout(e)}
                        onPanResponderGrant={(dID) =>this.setState({ dID })}
                        onPanResponderRelease={() => this.setState({dID: null})} /> ) })}
                        <View style={[styles.findPoint ]} />
                </View>
                <View style={styles.infoBar}>
                    <Text>{this.state.dID ? this.state.dID : ''}</Text>{this.compFrame()}
                </View>
            </View>
        );
    }
    onLayout = (e) => {
      if ( e && this.state.firstRender) {
        const n = e.nativeEvent.layout;
            const position = {
              width: n.width,
              height: n.height,
              x: n.x,
              y: n.y
            }
        console.log(position);
        this.setState({
          objLocation: this.state.objLocation.concat([position])
        });
      }
    }
    componentWillMount = () => {
      console.log("START");
    }
    compFrame = () => {
      return(
        this.state.objLocation.map( d => {<View style={[styles.findPoint2,{left: d.x, top: d.y, width: d.width, height: d.height} ]} ></View>})
        )
    }
    componentDidMount = () => {
      this.setState({firstRender: true })
      console.log(this.state.objLocation.length);
    }
}
</code>```

// Draggable

```<code>import React, { Component } from 'react';
import { Text, PanResponder, Animated } from 'react-native';
import styles from './styles';

class Draggable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
    };
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        this.props.onPanResponderGrant(this.props.id);
      },
      onPanResponderMove: Animated.event([ null, {
          dx: this.state.pan.x,
          dy: this.state.pan.y,
        },
      ]),
      onPanResponderRelease: () => {
        Animated.spring(this.state.pan, { toValue: { x: 0, y: 0 } }).start();
        this.props.onPanResponderRelease();
      },
    });
  }
  render() {
    return (
      <Animated.View
        onLayout={ (e) => this.props.onLayout(e) }
        {...this.panResponder.panHandlers}
        style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
        <Text style={styles.textAlt}>Drag me!</Text>
        <Text style={styles.textNum}>{this.props.id}</Text>
      </Animated.View>
    );
  }
  componentDidMount = () => {
    this.props.onLayout(this.props.dragEvent)
  }
}
export default Draggable;
</code>```

// Output of console.log

```<code>START xxx
0
{width:108,height:108,x:133.5,y:376.5}
{width:108,height:108,x:133.5,y:78.5}
{width:108,height:108,x:133.5,y:227.5}
</code>```

答:
I feel like I've hacked this, to get it to work, so please correct me as to correct procedure.

This is the onLayout method from the App. I've included an if statement that checks if the new positions array length is equal too the dataArray length that the draggable items are based on.

It looks like this.

```<code>onLayout = (e) => {
  if ( this.state.objLocation.length != dataArray.length ) {
    if ( e ) {
      const n = e.nativeEvent.layout;
          const position = {
            width: n.width,
            height: n.height,
            x: n.x,
            y: n.y
          }
      console.log(position);
      this.setState({
        objLocation: this.state.objLocation.concat([position])
      });
    }
  }
}
</code>```

Title: Updating state on first render only?

Body:
Using react-native, I'm creating sub-Components within the parent App and providing their position to the array this.state.objLocation within the parent App.

I can get the initial location data into the array straight after the render, but because my subcomponents are draggable, each time they re-render on drag, it adds a new position object to the array.

I'd like to avoid this, and I thought that creating this.state = { firstRender: true } in the constructor and then using componentDidMount = () => { this.setState({ firstRender: false }) } after the first render would allow me to create a 'gate' to stop the addition of the extra position objects.

I can see that if I comment out //componentDidMount = () => { this.setState({ firstRender: false }) } then I will get multiple entries to my array but if it's included in the class I get absolutely none.

So possibly my interpretation of the render lifecycle and componentDidMount is incorrect?

Here is my code.

// App

import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

const dataArray = [{num: 1,id: 'A',},{num: 2,id: 'B',},{num: 3,id: 'Z',}]

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
            objLocation: [],
            firstRender: true,
        };
    }
    render(){
        return (
            <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                    <Text>Draggable Container</Text> {dataArray.map( d => { return(
                    <Draggable
                        id={d.id}
                        onLayout={ e=> this.onLayout(e)}
                        onPanResponderGrant={(dID) =>this.setState({ dID })}
                        onPanResponderRelease={() => this.setState({dID: null})} /> ) })}
                        <View style={[styles.findPoint ]} />
                </View>
                <View style={styles.infoBar}>
                    <Text>{this.state.dID ? this.state.dID : ''}</Text>{this.compFrame()}
                </View>
            </View>
        );
    }
    onLayout = (e) => {
      if ( e && this.state.firstRender) {
        const n = e.nativeEvent.layout;
            const position = {
              width: n.width,
              height: n.height,
              x: n.x,
              y: n.y
            }
        console.log(position);
        this.setState({
          objLocation: this.state.objLocation.concat([position])
        });
      }
    }
    componentWillMount = () => {
      console.log("START");
    }
    compFrame = () => {
      return(
        this.state.objLocation.map( d => {<View style={[styles.findPoint2,{left: d.x, top: d.y, width: d.width, height: d.height} ]} ></View>})
        )
    }
    componentDidMount = () => {
      this.setState({firstRender: true })
      console.log(this.state.objLocation.length);
    }
}

// Draggable

import React, { Component } from 'react';
import { Text, PanResponder, Animated } from 'react-native';
import styles from './styles';

class Draggable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
    };
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        this.props.onPanResponderGrant(this.props.id);
      },
      onPanResponderMove: Animated.event([ null, {
          dx: this.state.pan.x,
          dy: this.state.pan.y,
        },
      ]),
      onPanResponderRelease: () => {
        Animated.spring(this.state.pan, { toValue: { x: 0, y: 0 } }).start();
        this.props.onPanResponderRelease();
      },
    });
  }
  render() {
    return (
      <Animated.View
        onLayout={ (e) => this.props.onLayout(e) }
        {...this.panResponder.panHandlers}
        style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
        <Text style={styles.textAlt}>Drag me!</Text>
        <Text style={styles.textNum}>{this.props.id}</Text>
      </Animated.View>
    );
  }
  componentDidMount = () => {
    this.props.onLayout(this.props.dragEvent)
  }
}
export default Draggable;

// Output of console.log

START xxx
0
{width:108,height:108,x:133.5,y:376.5}
{width:108,height:108,x:133.5,y:78.5}
{width:108,height:108,x:133.5,y:227.5}

Body:
I feel like I've hacked this, to get it to work, so please correct me as to correct procedure.

This is the onLayout method from the App. I've included an if statement that checks if the new positions array length is equal too the dataArray length that the draggable items are based on.

It looks like this.

onLayout = (e) => {
  if ( this.state.objLocation.length != dataArray.length ) {
    if ( e ) {
      const n = e.nativeEvent.layout;
          const position = {
            width: n.width,
            height: n.height,
            x: n.x,
            y: n.y
          }
      console.log(position);
      this.setState({
        objLocation: this.state.objLocation.concat([position])
      });
    }
  }
}


问:
Angular 5 and :host pseudo class
I have been using the :host pseudo class in Angular 4 with no problems. We are converting to Angular 5, and now the style does not seem to be getting added to the host component. Is there a different way to add this now in the new version of Angular?

```<code>:host {
  border: 10px solid black;
  &.isLeft {
    display: flex;
  }
}

@media (max-width: 599px) {
  :host {
    display: flex;
  }
}
</code>```

The isLeft class is set up based on a parameter that is passed into the component from the parent component because this particular control can be displayed in 2 different formats, one of which is responsive. Inside the component, I have the following code:

```<code>  @HostBinding('class.isLeft') isLeft: boolean;

  @Input()
  placement: string = 'responsive';

  ngOnInit() {
    this.isLeft = (this.placement.toLowerCase() === 'left');
  }
</code>```

I know there is a suggestion to use @HostBinding to do all of this. First of all, I'm not sure how that would work when I have to use media queries. Secondly, the only way to use @HostBinding with this would be to include styling inside the component, which goes against our company standards.

Thanks in advance!

答:
Code had included

```<code>encapsulation: ViewEncapsulation.None
</code>```

Is working now that that is removed.

Title: Angular 5 and :host pseudo class

Body:
I have been using the :host pseudo class in Angular 4 with no problems. We are converting to Angular 5, and now the style does not seem to be getting added to the host component. Is there a different way to add this now in the new version of Angular?

:host {
  border: 10px solid black;
  &.isLeft {
    display: flex;
  }
}

@media (max-width: 599px) {
  :host {
    display: flex;
  }
}

The isLeft class is set up based on a parameter that is passed into the component from the parent component because this particular control can be displayed in 2 different formats, one of which is responsive. Inside the component, I have the following code:

  @HostBinding('class.isLeft') isLeft: boolean;

  @Input()
  placement: string = 'responsive';

  ngOnInit() {
    this.isLeft = (this.placement.toLowerCase() === 'left');
  }

I know there is a suggestion to use @HostBinding to do all of this. First of all, I'm not sure how that would work when I have to use media queries. Secondly, the only way to use @HostBinding with this would be to include styling inside the component, which goes against our company standards.

Thanks in advance!

Body:
Code had included

encapsulation: ViewEncapsulation.None

Is working now that that is removed.


问:
How to show grid lines for rows in TreeTableView
I have the following FXML:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="1000.0" stylesheets="@../css/fxmlDemo.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fxmldemo.controller.MainController">
    <children>
        <TreeTableView fx:id="treeTableView" prefHeight="600.0" prefWidth="1000.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" xmlns:fx="http://javafx.com/fxml">
            <columns>
                <TreeTableColumn fx:id="nameColumn" prefWidth="600.0" text="Name" />
                <TreeTableColumn fx:id="sizeColumn" prefWidth="100.0" text="Size" />
                <TreeTableColumn fx:id="lastModifiedColumn" prefWidth="300.0" text="Modified" />
            </columns>
        </TreeTableView>
    </children>
</AnchorPane>
</code>```

And in my fxmlDemo.css file I have tried things like:

```<code>* {
  -fx-border-style: solid;
}
</code>```

And

```<code>tree-table-view {
  -fx-border-style: solid;
}
</code>```

And

```<code>tree-item {
  -fx-border-style: solid;
}
</code>```

The first one puts a border around everything in the FXML, the other two do nothing.

What I want is to show grid lines like an Excel spread sheet.  The code I'm using is very similar to what is seen in this example, but mine has been modified to actually work :)

Here is a link to the Java FX CSS Reference Guide, but it does not contain information on TreeTableView or its sub-components.

答:
If you use modena.css and just want to modify your TreeTableView to look like a TableView try to use following code.
The resulting TreeTableView has/contains:

Horizontal borders

Odd rows with different colour

Same selection behaviour like TableView

CSS file:

```<code>/* Let TreeTableView rows look like TableView rows  */
 .tree-table-row-cell {
    -fx-background-color: -fx-table-cell-border-color, -fx-background;
    -fx-background-insets: 0, 0 0 1 0;
}
/* Let odd rows look different */
.tree-table-row-cell:odd {
    -fx-background: -fx-control-inner-background-alt;
}
/* Selected when control is focused */
.tree-table-view:focused > .virtual-flow > .clipped-container > .sheet > .tree-table-row-cell:selected {
    -fx-background: -fx-selection-bar;
    -fx-table-cell-border-color: derive(-fx-selection-bar, 20%);
}
/* Selected when control is not focused */
.tree-table-row-cell:filled:selected {
    -fx-background: -fx-selection-bar-non-focused;
    -fx-table-cell-border-color: derive(-fx-selection-bar-non-focused, 20%);
}
</code>```

Body:
I have the following FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="1000.0" stylesheets="@../css/fxmlDemo.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fxmldemo.controller.MainController">
    <children>
        <TreeTableView fx:id="treeTableView" prefHeight="600.0" prefWidth="1000.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" xmlns:fx="http://javafx.com/fxml">
            <columns>
                <TreeTableColumn fx:id="nameColumn" prefWidth="600.0" text="Name" />
                <TreeTableColumn fx:id="sizeColumn" prefWidth="100.0" text="Size" />
                <TreeTableColumn fx:id="lastModifiedColumn" prefWidth="300.0" text="Modified" />
            </columns>
        </TreeTableView>
    </children>
</AnchorPane>

And in my fxmlDemo.css file I have tried things like:

* {
  -fx-border-style: solid;
}

And

tree-table-view {
  -fx-border-style: solid;
}

And

tree-item {
  -fx-border-style: solid;
}

The first one puts a border around everything in the FXML, the other two do nothing.

What I want is to show grid lines like an Excel spread sheet.  The code I'm using is very similar to what is seen in this example, but mine has been modified to actually work :)

Here is a link to the Java FX CSS Reference Guide, but it does not contain information on TreeTableView or its sub-components.

Body:
If you use modena.css and just want to modify your TreeTableView to look like a TableView try to use following code.
The resulting TreeTableView has/contains:

Horizontal borders

Odd rows with different colour

Same selection behaviour like TableView

CSS file:

/* Let TreeTableView rows look like TableView rows  */
 .tree-table-row-cell {
    -fx-background-color: -fx-table-cell-border-color, -fx-background;
    -fx-background-insets: 0, 0 0 1 0;
}
/* Let odd rows look different */
.tree-table-row-cell:odd {
    -fx-background: -fx-control-inner-background-alt;
}
/* Selected when control is focused */
.tree-table-view:focused > .virtual-flow > .clipped-container > .sheet > .tree-table-row-cell:selected {
    -fx-background: -fx-selection-bar;
    -fx-table-cell-border-color: derive(-fx-selection-bar, 20%);
}
/* Selected when control is not focused */
.tree-table-row-cell:filled:selected {
    -fx-background: -fx-selection-bar-non-focused;
    -fx-table-cell-border-color: derive(-fx-selection-bar-non-focused, 20%);
}


问:
HTML ASCII Case Insensitive ICU Collator
I need to create a Collator which corresponds to https://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive/ i.e. it ignores the case sensitivity of ASCII A-Z and a-z characters when making comparisons.

I have attempted this with the following ICU4j RuleBasedCollator:

```<code>final RuleBasedCollator collator =
        new RuleBasedCollator("&a=A, b=B, c=C, d=D, e=E, f=F, g=G, h=H, "
                + "i=I, j=J, k=K, l=L, m=M, n=N, o=O, p=P, q=Q, r=R, s=S, t=T, "
                + "u=U, v=V, u=U, v=V, w=W, x=X, y=Y, z=Z").freeze();
</code>```

However, the following comparison seems to fail, where I would expect it to succeed (i.e. return true):

```<code>final SearchIterator searchIterator = new StringSearch(
        "pu", new StringCharacterIterator("iNPut"), collator);
return searchIterator.first() >= 0;
</code>```

What am I missing in my rules?

答:
This W3C "collation" does not look like a Collator in the usual sense. It's an ASCII-case-insensitive matcher without ordering. I suspect that it is usually implemented with low-level code that matches ASCII letters case-insensitively and everything else precisely. See https://www.w3.org/TR/xpath-functions-31/#html-ascii-case-insensitive-collation

The Collator rules probably don't do what you think they do. The comma is old syntax for a tertiary difference, so &a=A, b=B, c=C is the same as &a=A<<<b=B<<<c=C. I think you were intending something like &a=A &b=B &c=C etc.

http://userguide.icu-project.org/collation/customization

http://demo.icu-project.org/icu-bin/collation.html

http://www.unicode.org/reports/tr35/tr35-collation.html#Rules

Body:
I need to create a Collator which corresponds to https://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive/ i.e. it ignores the case sensitivity of ASCII A-Z and a-z characters when making comparisons.

I have attempted this with the following ICU4j RuleBasedCollator:

final RuleBasedCollator collator =
        new RuleBasedCollator("&a=A, b=B, c=C, d=D, e=E, f=F, g=G, h=H, "
                + "i=I, j=J, k=K, l=L, m=M, n=N, o=O, p=P, q=Q, r=R, s=S, t=T, "
                + "u=U, v=V, u=U, v=V, w=W, x=X, y=Y, z=Z").freeze();

However, the following comparison seems to fail, where I would expect it to succeed (i.e. return true):

final SearchIterator searchIterator = new StringSearch(
        "pu", new StringCharacterIterator("iNPut"), collator);
return searchIterator.first() >= 0;

What am I missing in my rules?


问:
Speed up gsutil rsync between s3 and gs
I want to rsync a bucket with 100M files between s3 and gs. I've got a c3.8xlarge instance and did a quick dry run:

```<code>$ time gsutil -m rsync -r -n s3://s3-bucket/ gs://gs-bucket/
Building synchronization state...
At source listing 10000...
^C

real    4m11.946s
user    0m0.560s
sys     0m0.268s
</code>```

About 4 minutes for 10k files. At this rate, it's going to take 27 days just to compute the sync state. Anything I can do to speed this up?

I also noticed [and fixed] the following warning:
   WARNING: gsutil rsync uses hashes when modification time is not
   available at
   both the source and destination. Your crcmod installation isn't using the
   module's C extension, so checksumming will run very slowly. If this is your
   first rsync since updating gsutil, this rsync can take significantly longer than
   usual. For help installing the extension, please see "gsutil help crcmod".

Are the file hashes computed or am I just waiting for listing 100M files?

答:
When setting up a sync process between two buckets, the first iteration is going to be the slowest because it needs to copy all of the data in source-bucket to dest-bucket. For cross-provider syncs, this is further slowed down by the need for two separate connections per object -- one to pull the data from the source to the host machine, and another to funnel it through from the host to the destination (gsutil refers to this as "daisy-chain" mode).

For the initial sync (and possibly subsequent syncs as well) between buckets, you might be better off using GCS's transfer service, which allows GCS to copy the objects on your behalf. This tends to be much faster than doing all the work with one machine running gsutil.

As for the warning, it's a general warning that's printed at the beginning of the command execution if you don't have the crcmod C extension installed, regardless of what's present at the destination.

Title: Speed up gsutil rsync between s3 and gs

Body:
I want to rsync a bucket with 100M files between s3 and gs. I've got a c3.8xlarge instance and did a quick dry run:

$ time gsutil -m rsync -r -n s3://s3-bucket/ gs://gs-bucket/
Building synchronization state...
At source listing 10000...
^C

real    4m11.946s
user    0m0.560s
sys     0m0.268s

About 4 minutes for 10k files. At this rate, it's going to take 27 days just to compute the sync state. Anything I can do to speed this up?

I also noticed [and fixed] the following warning:
   WARNING: gsutil rsync uses hashes when modification time is not
   available at
   both the source and destination. Your crcmod installation isn't using the
   module's C extension, so checksumming will run very slowly. If this is your
   first rsync since updating gsutil, this rsync can take significantly longer than
   usual. For help installing the extension, please see "gsutil help crcmod".

Are the file hashes computed or am I just waiting for listing 100M files?


问:
Excluding in Live HTTP Headers plugin for Firefox
I am trying to exclude gmail's requests from Live Http headers, but I cant
seem to get the exclude reg ex to work.

My exclude regex is this: .gif$|.jpg$|.ico$|.css$|.js$|.*mail.google.com.*

Any ideas/suggestions?

答:
I think. You sould use "\." to catch a dot. Dot without slash is any symbol.
Like this:

\.gif$|\.jpg$|\.ico$|.css$|\.js$|.*mail\.google\.com.*


问:
how to sum two fields
I'm trying to perform Arithmetic Operators and this is my query ,

```<code>SELECT

    GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY,
    GLB.PERIOD_NET_DR + GLB.PERIOD_NET_CR AS BEG_BALANCE ,
    ACTIVITY + BEG_BALANCE AS END_BALANCE,
    SUM(ACTIVITY) AS TOTAL_ACT,
    SUM(BEG_BALANCE) AS TOTAL_BEG_BALANCE,
    SUM(END_BALANCE) AS TOTAL_END_BALANCE,
</code>```

But it didn't work , Can anyone guide me how can I fix it ?!

答:
It's not valid for aliases assigned in the SELECT list of the query to be referenced elsewhere in the SELECT list or in the WHERE clause of the same query. (MySQL does have extensions which allows a column alias to be referenced in ORDER BY and HAVING.)

If we want to reference an alias in the SELECT list, one option is to make the query into an inline view. And an outer query can reference an alias as a columname. As a simple example...

```<code> SELECT c.myalias
      , c.fee
      , c.myalias + c.fee AS grand_tot
   FROM ( SELECT t.somecol + t.othercol  AS `myalias`
               , t.fi + t.fo + t.fum     AS `fee`
            FROM t
        ) c
</code>```

For performance reasons, we would typically avoid doing this, due to the cost of materializing the inline view as a derived table. It would be much more efficient to avoid the inline view, and reference columns that are available, even if we have to repeat expressions.

```<code> SELECT t.somecol + t.othercol                       AS `myalias`
      , t.fi + t.fo + t.fum                          AS `fee`
      , t.somecol + t.othercol + t.fi + t.fo + t.fum AS `grand_tot`
   FROM t
</code>```

It's not clear what resultset twe are needing to return.

If we want just the totals, I'd avoid an inline view, and just bite the bullet and use expressions that reference columns that are available in the SELECT list. It seems like an odd resultset to return:

```<code>SELECT SUM( GLB.BEGIN_BALANCE_DR_BEQ
          + GLB.BEGIN_BALANCE_CR_BEQ
       ) AS TOTAL_ACT
     , SUM( GLB.PERIOD_NET_DR
          + GLB.PERIOD_NET_CR
       ) AS TOTAL_BEG_BALANCE
     , SUM( GLB_GLB.BEGIN_BALANCE_DR_BEQ
          + GLB.BEGIN_BALANCE_CR_BEQ
          + GLB.PERIOD_NET_DR
          + GLB.PERIOD_NET_CR
       ) AS TOTAL_END_BALANCE
  FROM ...
</code>```

Title: how to sum two fields

Body:
I'm trying to perform Arithmetic Operators and this is my query ,

SELECT

    GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY,
    GLB.PERIOD_NET_DR + GLB.PERIOD_NET_CR AS BEG_BALANCE ,
    ACTIVITY + BEG_BALANCE AS END_BALANCE,
    SUM(ACTIVITY) AS TOTAL_ACT,
    SUM(BEG_BALANCE) AS TOTAL_BEG_BALANCE,
    SUM(END_BALANCE) AS TOTAL_END_BALANCE,

But it didn't work , Can anyone guide me how can I fix it ?!

Body:
It's not valid for aliases assigned in the SELECT list of the query to be referenced elsewhere in the SELECT list or in the WHERE clause of the same query. (MySQL does have extensions which allows a column alias to be referenced in ORDER BY and HAVING.)

If we want to reference an alias in the SELECT list, one option is to make the query into an inline view. And an outer query can reference an alias as a columname. As a simple example...

 SELECT c.myalias
      , c.fee
      , c.myalias + c.fee AS grand_tot
   FROM ( SELECT t.somecol + t.othercol  AS `myalias`
               , t.fi + t.fo + t.fum     AS `fee`
            FROM t
        ) c

For performance reasons, we would typically avoid doing this, due to the cost of materializing the inline view as a derived table. It would be much more efficient to avoid the inline view, and reference columns that are available, even if we have to repeat expressions.

 SELECT t.somecol + t.othercol                       AS `myalias`
      , t.fi + t.fo + t.fum                          AS `fee`
      , t.somecol + t.othercol + t.fi + t.fo + t.fum AS `grand_tot`
   FROM t

It's not clear what resultset twe are needing to return.

If we want just the totals, I'd avoid an inline view, and just bite the bullet and use expressions that reference columns that are available in the SELECT list. It seems like an odd resultset to return:

SELECT SUM( GLB.BEGIN_BALANCE_DR_BEQ
          + GLB.BEGIN_BALANCE_CR_BEQ
       ) AS TOTAL_ACT
     , SUM( GLB.PERIOD_NET_DR
          + GLB.PERIOD_NET_CR
       ) AS TOTAL_BEG_BALANCE
     , SUM( GLB_GLB.BEGIN_BALANCE_DR_BEQ
          + GLB.BEGIN_BALANCE_CR_BEQ
          + GLB.PERIOD_NET_DR
          + GLB.PERIOD_NET_CR
       ) AS TOTAL_END_BALANCE
  FROM ...


问:
mysqldump from remote host
Is it possible to dump a database from a remote host through an ssh connection and have the backup file on my local computer.

If so how can this be achieved?

I am assuming it will be some combination of piping output from the ssh to the dump or vice versa but cant figure it out.

答:
I have created a script to make it easier to automate mysqldump commands on remote hosts using the answer provided by Michel Feldheim as a starting point:

mysqldump-remote

The script allows you to fetch a database dump from a remote host with or without SSH and optionally using a .env file containing environment variables.

I plan to use the script for automated database backups. Feel free to create issues / contribute - hope this helps others as well!

Title: mysqldump from remote host


问:
Explicit instanciation of template linker error
I'm asking your help because I'm using templates and it seems like I misunderstood something.

Here's my code :

arbre.h

```<code>template<typename T>
class Arbre;

template<typename T>
class Noeud
{
    friend class Arbre<T>;

    public :

    Noeud();
    ~Noeud();
    T get_info()const;

    private :
    T info;
    Noeud<T> *fg, *fd;
};

template<typename T>
class Arbre
{
    public :
    //Constructors-------------------------------------------------------------
    Arbre();
    /*
      other function definitions
    */
}
</code>```

arbre.tpp

```<code>#include "arbre.h"

template <typename T>
Noeud<T>::Noeud(){
    fg = fd = 0;
}

template <typename T>
Noeud<T>::~Noeud(){
}
template <typename T>
T Noeud<T>::get_info()const{
    return info;
}

template <typename T>
Arbre<T>::Arbre(){
    racine = 0;
}
/*
  other function implementations...
*/
</code>```

The main.cpp includes "arbre.h" and creates an object like so :

```<code>Arbre<int> a;
</code>```

So following this article on explicit instantiation : http://www.cplusplus.com/forum/articles/14272/

I added those 2 lines at the end of arbre.tpp :

```<code>template class Noeud<int>;
template class Arbre<int>;
</code>```

So that the linker can compile the code for the int version of my object in arbre.o and so I could keep the implementation (arbre.tpp) apart from the header (arbre.h). My code worked with implicit instantiation (arbre.tpp included at the end of header.h) but I wanted to keep them apart.

I wonder why does the linking fail :

```<code>g++ -o main.o -c main.cpp -Wall -g -std=c++11
g++ -o arbre.o -c arbre.tpp -Wall -g -std=c++11
g++: warning: arbre.tpp: linker input file unused because linking not done
g++ -o arbre.out main.o arbre.o
g++: error: arbre.o: No such file or directory
Makefile:9: recipe for target 'arbre.out' failed
make: *** [arbre.out] Error 1
</code>```

Do you have any idea ? I'm doing the same thing as in the article I linked aren't I ?

Thanks in advance.

答:
The explicit instantiation definition is not enough. Generally speaking, the compiler is supposed to assume the primary template definition is all that it sees. So to it, those specializations rely on undefined members.

However, there is the concept of an explicit instantiation declaration. It tells the compiler to look for the template definition elsewhere. Just add those two at the bottom of your header:

```<code>extern template class Noeud<int>;
extern template class Arbre<int>;
</code>```

Body:
I'm asking your help because I'm using templates and it seems like I misunderstood something.

Here's my code :

arbre.h

template<typename T>
class Arbre;

template<typename T>
class Noeud
{
    friend class Arbre<T>;

    public :

    Noeud();
    ~Noeud();
    T get_info()const;

    private :
    T info;
    Noeud<T> *fg, *fd;
};

template<typename T>
class Arbre
{
    public :
    //Constructors-------------------------------------------------------------
    Arbre();
    /*
      other function definitions
    */
}

arbre.tpp

#include "arbre.h"

template <typename T>
Noeud<T>::Noeud(){
    fg = fd = 0;
}

template <typename T>
Noeud<T>::~Noeud(){
}
template <typename T>
T Noeud<T>::get_info()const{
    return info;
}

template <typename T>
Arbre<T>::Arbre(){
    racine = 0;
}
/*
  other function implementations...
*/

The main.cpp includes "arbre.h" and creates an object like so :

Arbre<int> a;

So following this article on explicit instantiation : http://www.cplusplus.com/forum/articles/14272/

I added those 2 lines at the end of arbre.tpp :

template class Noeud<int>;
template class Arbre<int>;

So that the linker can compile the code for the int version of my object in arbre.o and so I could keep the implementation (arbre.tpp) apart from the header (arbre.h). My code worked with implicit instantiation (arbre.tpp included at the end of header.h) but I wanted to keep them apart.

I wonder why does the linking fail :

g++ -o main.o -c main.cpp -Wall -g -std=c++11
g++ -o arbre.o -c arbre.tpp -Wall -g -std=c++11
g++: warning: arbre.tpp: linker input file unused because linking not done
g++ -o arbre.out main.o arbre.o
g++: error: arbre.o: No such file or directory
Makefile:9: recipe for target 'arbre.out' failed
make: *** [arbre.out] Error 1

Do you have any idea ? I'm doing the same thing as in the article I linked aren't I ?

Thanks in advance.

Body:
The explicit instantiation definition is not enough. Generally speaking, the compiler is supposed to assume the primary template definition is all that it sees. So to it, those specializations rely on undefined members.

However, there is the concept of an explicit instantiation declaration. It tells the compiler to look for the template definition elsewhere. Just add those two at the bottom of your header:

extern template class Noeud<int>;
extern template class Arbre<int>;


答: Since you are using a nonstandard extension, .tpp, you may want to tell the compiler that you are working with C++ code, g++ -x c++.

Title: Explicit instanciation of template linker error


问:
How to get the last dir from a path in a string
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

```<code>result = test
</code>```

答:
You can use pathinfo - pathinfo

```<code>$pathinfo = pathinfo('dir/path', PATHINFO_DIRNAME);
$pathinfo = array_filter( explode('/', $pathinfo) );

$result = array_pop($pathinfo);
</code>```

This will also make sure that a trailing slash doesn't mean a blank string is returned.

Body:
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

result = test

Body:
You can use pathinfo - pathinfo

$pathinfo = pathinfo('dir/path', PATHINFO_DIRNAME);
$pathinfo = array_filter( explode('/', $pathinfo) );

$result = array_pop($pathinfo);

This will also make sure that a trailing slash doesn't mean a blank string is returned.


问:
check if the n-th variadic template argument is of a certain type
I'd like to implement something like same_type() function in C++11 like below (this is what I have tried so far but it can not cope with the use cases mentioned below). The function is to check if T is of the same type of the n-th argument of Args, currently n=0 should be enough for my requirement, although n=other meaningful value would be something better to have (not very important if not straightforward).

```<code>template<typename T, typename... Args>
struct MyClass
{
    // check if T is of the same type of the n-th argument of Args
    bool same_type() {
        // currently, I only check the first argument
        // but if possible, it would be more useful to extend
        // this function to check the n-th argument
        return std::is_same<T,typename std::tuple_element<0, std::tuple<Args...> >::type>;
    }
};
</code>```

I have already had a look at this answer, but it does not consider the following use cases.

Use cases:

1.use with references and const qualifier:

```<code>MyClass<int,const int&> c;
// expect to see 1, type of int should match const int&, i.e. reference or const should NOT affect the result
std::cout<<c.same_type();
</code>```

2.use with no argument supplied:

```<code>MyClass<int> c;
// expect to see 0 as there is no variadic argument provided to compare with int
std::cout<<c.same_type();
</code>```

答:
I propose to develop a type traits isSameNth as follows

```<code>template <std::size_t, typename...>
struct isSameNth;

template <std::size_t N, typename T, typename A0, typename ... As>
struct isSameNth<N, T, A0, As...> : public isSameNth<N-1U, T, As...>
 { };

template <std::size_t N, typename T>
struct isSameNth<N, T> : public std::false_type
 { };

template <typename T, typename A0, typename ... As>
struct isSameNth<0U, T, A0, As...> : public std::is_same<
   typename std::remove_reference<T>::type const,
   typename std::remove_reference<A0>::type const>
 { };
</code>```

to transform same_type() in a template static method (where the template value is N)

```<code>template <typename T, typename... Args>
struct MyClass
 {
   template <std::size_t N>
   static constexpr bool same_type()
    { return isSameNth<N, T, Args...>::value; }
 };
</code>```

The following is a full example (C++11 compliant)

```<code>#include <type_traits>

template <std::size_t, typename...>
struct isSameNth;

template <std::size_t N, typename T, typename A0, typename ... As>
struct isSameNth<N, T, A0, As...> : public isSameNth<N-1U, T, As...>
 { };

template <std::size_t N, typename T>
struct isSameNth<N, T> : public std::false_type
 { };

template <typename T, typename A0, typename ... As>
struct isSameNth<0U, T, A0, As...> : public std::is_same<
   typename std::remove_reference<T>::type const,
   typename std::remove_reference<A0>::type const>
 { };

template <typename T, typename... Args>
struct MyClass
 {
   template <std::size_t N>
   static constexpr bool same_type()
    { return isSameNth<N, T, Args...>::value; }
 };

int main ()
 {
   static_assert(
      false == MyClass<int, long, int, short>::template same_type<0U>(), "!");
   static_assert(
      true == MyClass<int, long, int, short>::template same_type<1U>(), "!");
   static_assert(
      false == MyClass<int, long, int, short>::template same_type<2U>(), "!");

   static_assert(
      true == MyClass<int const, int &>::template same_type<0U>(), "!");

   static_assert(
      false == MyClass<int const &>::template same_type<0U>(), "!");
 }
</code>```

Body:
I'd like to implement something like same_type() function in C++11 like below (this is what I have tried so far but it can not cope with the use cases mentioned below). The function is to check if T is of the same type of the n-th argument of Args, currently n=0 should be enough for my requirement, although n=other meaningful value would be something better to have (not very important if not straightforward).

template<typename T, typename... Args>
struct MyClass
{
    // check if T is of the same type of the n-th argument of Args
    bool same_type() {
        // currently, I only check the first argument
        // but if possible, it would be more useful to extend
        // this function to check the n-th argument
        return std::is_same<T,typename std::tuple_element<0, std::tuple<Args...> >::type>;
    }
};

I have already had a look at this answer, but it does not consider the following use cases.

Use cases:

1.use with references and const qualifier:

MyClass<int,const int&> c;
// expect to see 1, type of int should match const int&, i.e. reference or const should NOT affect the result
std::cout<<c.same_type();

2.use with no argument supplied:

MyClass<int> c;
// expect to see 0 as there is no variadic argument provided to compare with int
std::cout<<c.same_type();

Body:
I propose to develop a type traits isSameNth as follows

template <std::size_t, typename...>
struct isSameNth;

template <std::size_t N, typename T, typename A0, typename ... As>
struct isSameNth<N, T, A0, As...> : public isSameNth<N-1U, T, As...>
 { };

template <std::size_t N, typename T>
struct isSameNth<N, T> : public std::false_type
 { };

template <typename T, typename A0, typename ... As>
struct isSameNth<0U, T, A0, As...> : public std::is_same<
   typename std::remove_reference<T>::type const,
   typename std::remove_reference<A0>::type const>
 { };

to transform same_type() in a template static method (where the template value is N)

template <typename T, typename... Args>
struct MyClass
 {
   template <std::size_t N>
   static constexpr bool same_type()
    { return isSameNth<N, T, Args...>::value; }
 };

The following is a full example (C++11 compliant)

#include <type_traits>

template <std::size_t, typename...>
struct isSameNth;

template <std::size_t N, typename T, typename A0, typename ... As>
struct isSameNth<N, T, A0, As...> : public isSameNth<N-1U, T, As...>
 { };

template <std::size_t N, typename T>
struct isSameNth<N, T> : public std::false_type
 { };

template <typename T, typename A0, typename ... As>
struct isSameNth<0U, T, A0, As...> : public std::is_same<
   typename std::remove_reference<T>::type const,
   typename std::remove_reference<A0>::type const>
 { };

template <typename T, typename... Args>
struct MyClass
 {
   template <std::size_t N>
   static constexpr bool same_type()
    { return isSameNth<N, T, Args...>::value; }
 };

int main ()
 {
   static_assert(
      false == MyClass<int, long, int, short>::template same_type<0U>(), "!");
   static_assert(
      true == MyClass<int, long, int, short>::template same_type<1U>(), "!");
   static_assert(
      false == MyClass<int, long, int, short>::template same_type<2U>(), "!");

   static_assert(
      true == MyClass<int const, int &>::template same_type<0U>(), "!");

   static_assert(
      false == MyClass<int const &>::template same_type<0U>(), "!");
 }


问:
Can I create a WordPress plugin with JavaScript only?
I am scared to ask this question, because StackOverflow is already warning me about my question being likely to be downvoted. But I am very curious about this.

I have read that you must have at least one php file in your WordPress Plugin. Which sounds to me like you only need something like an index/entry php file.

However, I wasn't able to find much about JavaScript in WordPress Plugins by using google. Which seemed weird to me, because we're talking here about the web of 2017.

An answer would be very appreciated!

答:
The answer is no, you cannot, as you have referenced in your question. By definition, a plugin is at the very least a "PHP file with a WordPress plugin header comment" (Wordpress Docs).

However, there is no reason a Wordpress plugin can't be primarily Javascript. You can follow this guide for some different approaches to include it in your plugin.


问:
How do I update the volumes in a running Kubernetes Pod?
I have a Kubernetes pod that is already running on a Minikube (v0.23.0) node.

Some context: it's the coredns pod that is created from enabling the plugin. I'm working through this blog post, in an attempt to set up custom DNS entries for my Kubernetes cluster: https://coredns.io/2017/05/08/custom-dns-entries-for-kubernetes/

I'm able to replace the config map without a problem; I altered the template spec from the blog post to suit my needs and ran:

```<code>kubectl create -f configmap.yml -o yaml --dry-run | kubectl replace -f -
</code>```

That seemed to work; I inspected the configmap using kubectl and everything looked fine.

However I'm not sure how to update the volumes. I tried putting something like this in a file:

```<code>apiVersion: v1
kind: Pod
metadata:
  labels:
    k8s-app: coredns
  namespace: kube-system
spec:
  containers:
  - name: coredns
  volumes:
  - configMap:
      items:
      - key: Corefile
        path: Corefile
      - key: cluster.db
        path: cluster.db
      name: coredns
    name: config-volume
</code>```

Then I tried applying it with:

```<code>kubectl create -f k8s_config/coredns/volumes.yml -o yaml --dry-run | kubectl apply -f -
</code>```

But that gave this error message:

```<code>error: error when retrieving current configuration of:
&{0xc4218be840 0xc420213500 kube-system  STDIN 0xc421a9e5e0 0xc421a9e5e0  false}
from server for: "STDIN": resource name may not be empty
</code>```

I also tried dumping the contents of the coredns pod into a file, altering the volume section accordingly, then replacing the pod, but got this message:

```<code>The Pod "coredns-6b4fd7784-xhb5s" is invalid: spec: Forbidden: pod updates may not change fields other than `spec.containers[*].image`, `spec.initContainers[*].image`, `spec.activeDeadlineSeconds` or `spec.tolerations` (only additions to existing tolerations)
</code>```

Short of deleting the pod and bringing it back up, how should I go about updating the volumes in a Pod? Is it even possible?

I suppose another overarching question would be: what's the correct way to update/configure the coredns pod/plugin? I can't seem to find a guide anywhere. In the blog post it says the following:

To create the new zone, we need to modify the coredns.yaml we have
  been using to create an additional file in the pod.

However this must have come from when coredns was manually set up in Kubernetes, and now that it "just works" as a plugin I'm not sure how to go about configuring it.

答:
Looking at the Pod name coredns-6b4fd7784-xhb5s, it looks like your CoreDNS Pod is actually being managed by a Deployment controller.

Do not modify Pods managed by a deployment controller directly. To edit Pods managed by a deployment, edit the deployment object itself (kubectl -n kube-system edit deployment coredns) and modify the spec.template property. After editing the deployment, the controller will delete the old pod and create a new one with the updated specification.

If you simply updated a ConfigMap object and want the CoreDNS Pod to receive the new contents, its also sufficient to simply delete the old Pod; the deployment controller will create a new one with the most recent version of the ConfigMap.

If you're worried about a potential service interruption by deleting your CoreDNS Pod, consider increasing the deployment's spec.replica value to a value higher than 1.

Body:
I have a Kubernetes pod that is already running on a Minikube (v0.23.0) node.

Some context: it's the coredns pod that is created from enabling the plugin. I'm working through this blog post, in an attempt to set up custom DNS entries for my Kubernetes cluster: https://coredns.io/2017/05/08/custom-dns-entries-for-kubernetes/

I'm able to replace the config map without a problem; I altered the template spec from the blog post to suit my needs and ran:

kubectl create -f configmap.yml -o yaml --dry-run | kubectl replace -f -

That seemed to work; I inspected the configmap using kubectl and everything looked fine.

However I'm not sure how to update the volumes. I tried putting something like this in a file:

apiVersion: v1
kind: Pod
metadata:
  labels:
    k8s-app: coredns
  namespace: kube-system
spec:
  containers:
  - name: coredns
  volumes:
  - configMap:
      items:
      - key: Corefile
        path: Corefile
      - key: cluster.db
        path: cluster.db
      name: coredns
    name: config-volume

Then I tried applying it with:

kubectl create -f k8s_config/coredns/volumes.yml -o yaml --dry-run | kubectl apply -f -

But that gave this error message:

error: error when retrieving current configuration of:
&{0xc4218be840 0xc420213500 kube-system  STDIN 0xc421a9e5e0 0xc421a9e5e0  false}
from server for: "STDIN": resource name may not be empty

I also tried dumping the contents of the coredns pod into a file, altering the volume section accordingly, then replacing the pod, but got this message:

The Pod "coredns-6b4fd7784-xhb5s" is invalid: spec: Forbidden: pod updates may not change fields other than `spec.containers[*].image`, `spec.initContainers[*].image`, `spec.activeDeadlineSeconds` or `spec.tolerations` (only additions to existing tolerations)

Short of deleting the pod and bringing it back up, how should I go about updating the volumes in a Pod? Is it even possible?

I suppose another overarching question would be: what's the correct way to update/configure the coredns pod/plugin? I can't seem to find a guide anywhere. In the blog post it says the following:

To create the new zone, we need to modify the coredns.yaml we have
  been using to create an additional file in the pod.

However this must have come from when coredns was manually set up in Kubernetes, and now that it "just works" as a plugin I'm not sure how to go about configuring it.


问:
How to bind event for dynamically created elements in JQuery
i have created some dynamic elements using jquery and add a dropdownlist using ajax inside dynamic elements ,The problem is when i select a option from a dropdownlist,then upcoming ajax data are override the all other dynamic elements data.

now i want to bind data every dynamic elements data separately in jquery.

  $(document).ready(function() {
  var html = $("#dsp > .row:first").first().html();
  var maxrows = 5;
  var x = 1;
  $("#addrow").click(function() {
    if (x <= maxrows) {
      $('#dsp').append(html);
      x++;
    }
  });

  $("#rmvrow").click(function() {
    $('#dsp').children().last().remove();
  });

    $('#dsp').on('change','.p_name',function(){
      var pid=$(this).val();
      var parent=$('#dsp');

      //alert(pid);
      $.ajax({
        url:"{{route('getinfo')}}",
        method:'post',
        data:{id:pid,'_token':"{{csrf_token()}}"},
        success:function(response) {
            console.log(parent.find('.p_code').val(response.code));

        }
      });

    });
});

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>           <div id="dsp">
  <div class="row">
    <div class="col-md-2">
      <select name="p_name[]" class="form-control p_name">
      <option value="">-Select Product-</option>
      @foreach($products as $product)
      <option value="{{$product->product_id}}">{{$product->name}}</option>
      @endforeach
    </select>
    </div>
    <div class="col-md-2">
      <input type="text" name="p_code[]" class="form-control p_code">
    </div>
    <div class="col-md-2">
      <input type="text" name="unit_pctn[]" class="form-control unit_pctn" readonly="">
    </div>
    <div class="col-md-2">
      <input type="text" name="u_price[]" class="form-control u_price" readonly="">
    </div>
    <div class="col-md-1">
      <input type="text" name="ctn[]" class="form-control ctn">
    </div>
    <div class="col-md-1">
      <input type="text" name="pcs[]" class="form-control pcs">
    </div>
    <div class="col-md-2">
      <input type="text" name="t_amt[]" class="form-control t_amt">
    </div>

  </div><br>
</div></code>```

答:
Keep giving dynamic id for each of your rows and use that to add listeners.

On every add row call a funtion that does

```<code>function addrow(rownumber) {
    document.getElementById('dsp' + rownumber).addEventListener('click', function(event) {
        // do some action
    });
}
</code>```

Body:
i have created some dynamic elements using jquery and add a dropdownlist using ajax inside dynamic elements ,The problem is when i select a option from a dropdownlist,then upcoming ajax data are override the all other dynamic elements data.

now i want to bind data every dynamic elements data separately in jquery.

  $(document).ready(function() {
  var html = $("#dsp > .row:first").first().html();
  var maxrows = 5;
  var x = 1;
  $("#addrow").click(function() {
    if (x <= maxrows) {
      $('#dsp').append(html);
      x++;
    }
  });

  $("#rmvrow").click(function() {
    $('#dsp').children().last().remove();
  });

    $('#dsp').on('change','.p_name',function(){
      var pid=$(this).val();
      var parent=$('#dsp');

      //alert(pid);
      $.ajax({
        url:"{{route('getinfo')}}",
        method:'post',
        data:{id:pid,'_token':"{{csrf_token()}}"},
        success:function(response) {
            console.log(parent.find('.p_code').val(response.code));

        }
      });

    });
});

      <select name="p_name[]" class="form-control p_name">
      <option value="">-Select Product-</option>
      @foreach($products as $product)
      <option value="{{$product->product_id}}">{{$product->name}}</option>
      @endforeach
    </select>

      <input type="text" name="p_code[]" class="form-control p_code">

      <input type="text" name="unit_pctn[]" class="form-control unit_pctn" readonly="">

      <input type="text" name="u_price[]" class="form-control u_price" readonly="">

      <input type="text" name="ctn[]" class="form-control ctn">

      <input type="text" name="pcs[]" class="form-control pcs">

      <input type="text" name="t_amt[]" class="form-control t_amt">

Body:
Keep giving dynamic id for each of your rows and use that to add listeners.

On every add row call a funtion that does

function addrow(rownumber) {
    document.getElementById('dsp' + rownumber).addEventListener('click', function(event) {
        // do some action
    });
}


问:
PHP - How can I Create Dynamic Bootstrap Rows & Columns in WordPress based on how many sub arrays an array has?
I am using the Advanced Custom Fields plugin in WordPress to display rows of different employees. Basically, a User can input data in the Admin section, and it creates an array that can be used to display the data.

Currently, The array is storing 5 values(subarrays):

```<code>array (
    0 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/jaime.jpg',
            'profile_name' => 'Jaime Daignault',
            'profile_job' => 'Executive Director',
            'profile_email' => 'Jaimie.Daignault@ocdd.org',
        ),
    1 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/beth.jpg',
            'profile_name' => 'Beth Kessler',
            'profile_job' => 'Family Engagement Coordinator',
            'profile_email' => 'Beth.Kessler@ocdd.org',
        ),
    2 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/carrie.jpg',
            'profile_name' => 'Carrie Salehiamin',
            'profile_job' => 'Operations Manager',
            'profile_email' => 'CarrieS@ocdd.org',
        ),
    3 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/leslie.jpg',
            'profile_name' => 'Leslie Sutton',
            'profile_job' => 'Policy Director',
            'profile_email' => 'Leslie.Sutton@ocdd.org',
        ),
    4 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/ryley.jpg',
            'profile_name' => 'Ryley Newport',
            'profile_job' => 'Communications Director',
            'profile_email' => 'Ryley.newport@ocdd.org',
        ),
)
</code>```

I want to be able to create one Bootstrap row with 3 columns, if it has 3 subarrays. Otherwise, I want to create 2 rows, with 3 columns each, if there is more than 3 subarrays. So far this is what I created:

```<code>// Store Name of custom field(array) from Admin Section
<?php $repeater = get_field('staff'); ?>

<?php if(count($repeater) <= 3): ?>
    <?php while(have_rows('staff')) : the_row(); ?>
        <div class="row">
            <div class="col-md-4 col-sm-6 col-xs-12 staffBlock">
                <img src="<?php the_sub_field('profile_pic'); ?>" alt="Profile Pic">
                <h4 class="staffTitle"><?php the_sub_field('profile_name'); ?></h4>
                <p class="staffSubTitle"><?php the_sub_field('profile_job'); ?></p>
                <a class="staffEmail" href="mailto:<?php the_sub_field('profile_email'); ?>"><?php the_sub_field('profile_email'); ?></a>
            </div>
        </div>
    <?php endwhile; ?>

<?php elseif(count($repeater) > 3 && count(repeater) <= 6): ?>
    <?php while(have_rows('staff')) : the_row(); ?>
        // Display first row and 3 columns
        // Display second row and remaining columns
    <?php endwhile; ?>
<?php endif; ?>
</code>```

It works great if the Array has 3 subarrays, but I can't seem to wrap my head around how to create two different rows if it has more subarrays.

答:
You just need to assign variables that increase in every instance of the loop and reset or check them see this I wrote some comments in the code to help you understand.

BTW its not limited to 6 items its could be for unlimited items. every 3 items its wrap with row

```<code><?php
$x = 1;
$z = 1;
// Total items in the repeater field
$total_items = count($repeater);
?>
<?php
foreach($repeater as $item):
    // Check if $x is bigger than 3 then we set it back to 1
    $x = ($x > 3) ? 1 : $x;
    // if $x = 1 then we start a new row
    echo ($x == 1) ? '<div class="row">' : '';
        ?>
        <div class="col-md-4 col-sm-6 col-xs-12 staffBlock">
            <img src="<?php echo $item['profile_pic']; ?>" alt="Profile Pic">
            <h4 class="staffTitle"><?php echo $item['profile_name']; ?></h4>
            <p class="staffSubTitle"><?php echo $item['profile_job']; ?></p>
            <a class="staffEmail" href="mailto:<?php echo $item['profile_email']; ?>"><?php echo $item['profile_email']; ?></a>
        </div>
    <?php
    // Check if $x is equal to 3 or if $z equal to the total of the items in the repeater
    // then its true we close the row
    echo ($x == 3) || ($z == $total_items) ? '</div>' : '';
    $x++;
    $z++;
endforeach;
?>
</code>```

Body:
I am using the Advanced Custom Fields plugin in WordPress to display rows of different employees. Basically, a User can input data in the Admin section, and it creates an array that can be used to display the data.

Currently, The array is storing 5 values(subarrays):

array (
    0 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/jaime.jpg',
            'profile_name' => 'Jaime Daignault',
            'profile_job' => 'Executive Director',
            'profile_email' => 'Jaimie.Daignault@ocdd.org',
        ),
    1 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/beth.jpg',
            'profile_name' => 'Beth Kessler',
            'profile_job' => 'Family Engagement Coordinator',
            'profile_email' => 'Beth.Kessler@ocdd.org',
        ),
    2 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/carrie.jpg',
            'profile_name' => 'Carrie Salehiamin',
            'profile_job' => 'Operations Manager',
            'profile_email' => 'CarrieS@ocdd.org',
        ),
    3 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/leslie.jpg',
            'profile_name' => 'Leslie Sutton',
            'profile_job' => 'Policy Director',
            'profile_email' => 'Leslie.Sutton@ocdd.org',
        ),
    4 =>
        array (
            'profile_pic' => 'http://ocdd.vztechsolutions.com/wp-content/uploads/2017/11/ryley.jpg',
            'profile_name' => 'Ryley Newport',
            'profile_job' => 'Communications Director',
            'profile_email' => 'Ryley.newport@ocdd.org',
        ),
)

I want to be able to create one Bootstrap row with 3 columns, if it has 3 subarrays. Otherwise, I want to create 2 rows, with 3 columns each, if there is more than 3 subarrays. So far this is what I created:

// Store Name of custom field(array) from Admin Section
<?php $repeater = get_field('staff'); ?>

<?php if(count($repeater) <= 3): ?>
    <?php while(have_rows('staff')) : the_row(); ?>

                <img src="<?php the_sub_field('profile_pic'); ?>" alt="Profile Pic">

<?php the_sub_field('profile_name'); ?>

<?php the_sub_field('profile_job'); ?>

                <a class="staffEmail" href="mailto:<?php the_sub_field('profile_email'); ?>"><?php the_sub_field('profile_email'); ?>

    <?php endwhile; ?>

<?php elseif(count($repeater) > 3 && count(repeater) <= 6): ?>
    <?php while(have_rows('staff')) : the_row(); ?>
        // Display first row and 3 columns
        // Display second row and remaining columns
    <?php endwhile; ?>
<?php endif; ?>

It works great if the Array has 3 subarrays, but I can't seem to wrap my head around how to create two different rows if it has more subarrays.

Body:
You just need to assign variables that increase in every instance of the loop and reset or check them see this I wrote some comments in the code to help you understand.

BTW its not limited to 6 items its could be for unlimited items. every 3 items its wrap with row

<?php
$x = 1;
$z = 1;
// Total items in the repeater field
$total_items = count($repeater);
?>
<?php
foreach($repeater as $item):
    // Check if $x is bigger than 3 then we set it back to 1
    $x = ($x > 3) ? 1 : $x;
    // if $x = 1 then we start a new row
    echo ($x == 1) ? '<div class="row">' : '';
        ?>
        <div class="col-md-4 col-sm-6 col-xs-12 staffBlock">
            <img src="<?php echo $item['profile_pic']; ?>" alt="Profile Pic">
            <h4 class="staffTitle"><?php echo $item['profile_name']; ?></h4>
            <p class="staffSubTitle"><?php echo $item['profile_job']; ?></p>
            <a class="staffEmail" href="mailto:<?php echo $item['profile_email']; ?>"><?php echo $item['profile_email']; ?></a>
        </div>
    <?php
    // Check if $x is equal to 3 or if $z equal to the total of the items in the repeater
    // then its true we close the row
    echo ($x == 3) || ($z == $total_items) ? '</div>' : '';
    $x++;
    $z++;
endforeach;
?>


问:
Set a cookie to a webView in Android
I'm getting a HttpResponse from a server when checking if a username or password is correct.
When I load the url in a webview I want the webView to have the cookie (the answer I get with postData() stored in the webView.
I want the webView to pickup the cookie and load the url with that cookie stored in the webview.

I'm getting the response through.

```<code>public HttpResponse postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://example.com/login.aspx");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("txtUsername", "user"));
        nameValuePairs.add(new BasicNameValuePair("txtPassword", "123"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        String responseAsText = EntityUtils.toString(response.getEntity());
        Log.v(TAG , "Response from req: " + responseAsText);
        return responseAsText;

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
    return null;
}
</code>```

And I loadUrl with:

```<code>webView.loadUrl("http://a_page.com/getpage.aspx?p=home");
</code>```

I guess I'm not really managing a cookie and I have no idea how to do so.
Any suggestions or solutions?

答:
Just wanna throw another way how this can be done. Not saying it is the best, but it is a way. You can use JavaScript to set cookies as well. Just override onPageFinished in WebViewClient

```<code>new WebViewClient() {

        override fun onPageFinished(view: WebView, url: String) {

                val javascript = """document.cookie = "key=$value""""

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    view.evaluateJavascript(javascript) { s -> Timber.d("Inject: %s", s) }
                } else {
                    view.loadUrl("javascript:" + javascript, null)
                }
        }
}
</code>```

One thing with this approach: you will have to reload the webView. If anyone knows how to fix that, please comment.

Title: Set a cookie to a webView in Android

Body:
I'm getting a HttpResponse from a server when checking if a username or password is correct.
When I load the url in a webview I want the webView to have the cookie (the answer I get with postData() stored in the webView.
I want the webView to pickup the cookie and load the url with that cookie stored in the webview.

I'm getting the response through.

public HttpResponse postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://example.com/login.aspx");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("txtUsername", "user"));
        nameValuePairs.add(new BasicNameValuePair("txtPassword", "123"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        String responseAsText = EntityUtils.toString(response.getEntity());
        Log.v(TAG , "Response from req: " + responseAsText);
        return responseAsText;

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
    return null;
}

And I loadUrl with:

webView.loadUrl("http://a_page.com/getpage.aspx?p=home");

I guess I'm not really managing a cookie and I have no idea how to do so.
Any suggestions or solutions?

Body:
Just wanna throw another way how this can be done. Not saying it is the best, but it is a way. You can use JavaScript to set cookies as well. Just override onPageFinished in WebViewClient

new WebViewClient() {

        override fun onPageFinished(view: WebView, url: String) {

                val javascript = """document.cookie = "key=$value""""

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    view.evaluateJavascript(javascript) { s -> Timber.d("Inject: %s", s) }
                } else {
                    view.loadUrl("javascript:" + javascript, null)
                }
        }
}

One thing with this approach: you will have to reload the webView. If anyone knows how to fix that, please comment.


答:
The following article should give you insight about this.

Your WordPress Plugin must have at least one PHP file; it could also contain JavaScript files, CSS files, image files and language files. If there are multiple files, pick a unique name for a directory and a name of your choice for the main PHP file. (This file name is often, but not essentially, the same as the directory name.) Example directory and file names could be mycompanyname-fabulous-functionality and mycompanyname-fabulous-functionality.php respectively. Put all your Plugin's files into the directory you've created and tell your Plugin users to upload the whole directory to wp-content/plugins/.

Hope this helps. But no, you can't create a Wordpress plugin with only Javascript.

Title: Can I create a WordPress plugin with JavaScript only?

Body:
I am scared to ask this question, because StackOverflow is already warning me about my question being likely to be downvoted. But I am very curious about this.

I have read that you must have at least one php file in your WordPress Plugin. Which sounds to me like you only need something like an index/entry php file.

However, I wasn't able to find much about JavaScript in WordPress Plugins by using google. Which seemed weird to me, because we're talking here about the web of 2017.

An answer would be very appreciated!


问:
Show customer details on WooCommerce Thankyou page even if not registered
In WooCommerce, for logged in users the Thankyou (order-received) page does show the customer details like the name, address and e-mail, but nothing when customers are not registered.

How can I ensure that non registered users can see their details on the Thankyou (order-received) page when the payment is successfully finished, just like registered users?

Why the customer details doesn't show up on the Thankyou (order-received) page for non registered users?

答:
You can change this behavior for non logged users with the following code:

```<code>add_action( 'woocommerce_thankyou', 'adding_customers_details_to_thankyou', 10, 1 );
function adding_customers_details_to_thankyou( $order_id ) {
    // Only for non logged in users
    if ( ! $order_id || is_user_logged_in() ) return;

    $order = wc_get_order($order_id); // Get an instance of the WC_Order object

    wc_get_template( 'order/order-details-customer.php', array('order' => $order ));
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.

May be the fact that customer info doesn't show up is for security reasons, as this info is not really protected the same way than for logged in users (registered users).

Body:
You can change this behavior for non logged users with the following code:

add_action( 'woocommerce_thankyou', 'adding_customers_details_to_thankyou', 10, 1 );
function adding_customers_details_to_thankyou( $order_id ) {
    // Only for non logged in users
    if ( ! $order_id || is_user_logged_in() ) return;

    $order = wc_get_order($order_id); // Get an instance of the WC_Order object

    wc_get_template( 'order/order-details-customer.php', array('order' => $order ));
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.

May be the fact that customer info doesn't show up is for security reasons, as this info is not really protected the same way than for logged in users (registered users).


问:
Create Border around image when clicked in JavaScript?
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

```

答:
One issue is that your mark() function is passing hard-coded numbers, but there are no elements that have the id property set with a number. Note that your  id properties are strings.

What you could do for those instead, is to set each mark call to pass the element id, like so:

```<code>onclick="mark(this.id)"
</code>```

With that minor change, you will see that your borders turn orange. However, there will still be the matter of clearing the other borders...

To clear the borders, you can loop the children of the parent element to remove all borders before setting the one that was clicked. You could do this inside the mark function, or some other function/handling, but I'll change the mark function for this example:

```<code>function mark(ID) { //creates border
    var childImages = document.getElementById("thumbnails").children;
    var i;

    // clear any other borders that might be set
    for ( i = 0; i < childImages.length; i++ ) {
       childImages[i].style.border = '';
    }

    // Then set the one that got clicked.
    document.getElementById(ID).style.border="2px solid orange";
}
</code>```

Body:
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}

@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

Body:
One issue is that your mark() function is passing hard-coded numbers, but there are no elements that have the id property set with a number. Note that your <img> id properties are strings.

What you could do for those instead, is to set each mark call to pass the element id, like so:

onclick="mark(this.id)"

With that minor change, you will see that your borders turn orange. However, there will still be the matter of clearing the other borders...

To clear the borders, you can loop the children of the parent element to remove all borders before setting the one that was clicked. You could do this inside the mark function, or some other function/handling, but I'll change the mark function for this example:

function mark(ID) { //creates border
    var childImages = document.getElementById("thumbnails").children;
    var i;

    // clear any other borders that might be set
    for ( i = 0; i < childImages.length; i++ ) {
       childImages[i].style.border = '';
    }

    // Then set the one that got clicked.
    document.getElementById(ID).style.border="2px solid orange";
}


问:
How to use breakpoints in Eclipse
I am using the Eclipse IDE. I don't know how effectively put breakpoints in Eclipse and go forward and backward into it. Can anyone help me?

Can anyone suggest a site suitable for me?

答: Googling gives many sites... Debugging with the Eclipse platform for one.</p>

ContentLicense: CC BY-SA 4.0

Title: How to use breakpoints in Eclipse