问:
Unicode characters is shuffled in php imagettftext
I am trying to print unicode characters in image using GD library

I have following code

```<code>    $text = "கைவிடப்பட்ட";
    $font = "arial.ttf";
    $im = imagecreatetruecolor(2500, 500);
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, 2500, 500, $white);
    imagettftext($im, 16, 0, 10, 20, $black, $font, $text);
    imagepng($im);
    imagedestroy($im);
</code>```

Original text here is கைவிடப்பட்ட , but it prints as following , you can see that first letter is replaced.

Edit : I have tried 5 different fonts All results in same(online font preview is showing characters correctly) .  whereas when I echo the string via php(from database) to browser, output is exactly same(கைவிடப்பட்ட), but why imagettftext is switching characters..

答:
Limitations of Unicode

The Unicode standard policy is to encode only characters, not glyphs. கை, includes a combination character onto க.  of Tamil is treated a complex script that requires complex processing, and many software components don't properly handle it.

The best approach would be to find, or create, a php extension library which was written specifically for Tamil.

Body:
I am trying to print unicode characters in image using GD library

I have following code

    $text = "கைவிடப்பட்ட";
    $font = "arial.ttf";
    $im = imagecreatetruecolor(2500, 500);
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, 2500, 500, $white);
    imagettftext($im, 16, 0, 10, 20, $black, $font, $text);
    imagepng($im);
    imagedestroy($im);

Original text here is கைவிடப்பட்ட , but it prints as following , you can see that first letter is replaced.

Edit : I have tried 5 different fonts All results in same(online font preview is showing characters correctly) .  whereas when I echo the string via php(from database) to browser, output is exactly same(கைவிடப்பட்ட), but why imagettftext is switching characters..


来源: stackexchange

问:
highchart donut - click on slice opens page by searching from userService
I have a donut pie chart. on click of legend item it navigates to particular page which it retrieves from userSevice like given below -

pic of user service]1

legendItemClick:

```<code>function(e) { debugger;
    this.userService.search(e.target.id);
    return false;
}.bind(this)
</code>```

i am looking for same functionality when i click on the pie slices of the chart it should navigate to particular related page. i tried this below but was not successful -

```<code>point: {
    events: {
        click: function(e){
            this.userService.search(e.target.id);
            return false;
        }.bind(this)
    }
}
</code>```

any help where Iam going wrong ?

userService -

```<code>  search(id: any) {
        let headers = new Headers();

        let data = { "jql": id };
        let body = JSON.stringify(data);
        let http: Http
       var method = method || "post";
        var params;
        var path ;
        path = ' http://imptdg/IMR/Ticket/DashBoard';
                var form = document.createElement("form");
                form.setAttribute("method", method);
                form.setAttribute("action", path);
                        var hiddenField = document.createElement("input");
                        hiddenField.setAttribute("type", "hidden");
                        hiddenField.setAttribute("name", 'jql');
                        hiddenField.setAttribute("value", id);
                        form.appendChild(hiddenField);
                document.body.appendChild(form); debugger;
                form.submit();

    }

defaults() {
    this.options = {

        title: { text: ' ' },
        colors: ['rgba(79, 162, 189, 1)', 'rgba(84, 135, 201, 1)', 'rgba(143, 185, 91, 1)', 'rgba(90, 183, 130, 1)', 'rgba(71, 195, 185, 1)', 'rgba(190, 120, 203, 1)', 'rgba(228, 211, 84, 1)', 'rgba(43, 144, 143, 1)', 'rgba(145, 232, 225, 1)'],
        chart: {
            type: 'pie',
            animation: true
        },
        credits: {
            enabled: false
        },
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 300
                },
                chartOptions: {
                    legend: {
                        align: 'center',
                        verticalAlign: 'bottom',
                        layout: 'vertical',
                        labelFormatter: function () {
                            return '<div style="width:180px"><span class="pull-left" style= "font-weight: 500; padding-bottom: 5px; font-family:Helvetica ">' + this.name +
                                '</span><span class="pull-right" style= "font-weight: 500" >' + this.value +
                                '</span></div> ';
                        }
                    },
                    pie: {
                        size: 50,
                        innerSize: 20
                    }
                }
            }]
        },

        plotOptions: {
            pie: {
                innerSize: '40%',
                allowPointSelect: true,
                slicedOffset: 0,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },

                showInLegend: true,
                 point: {
                    events: {
                        click:function(e){
                            this.userService.search(e.target.id); // this part not working
                            return false;
                        }.bind(this),

                        legendItemClick: function (e) {

                            this.userService.search(e.target.id);
                            return false;
                        }.bind(this),

                    }

                    },
                states: {
                    hover: {
                        halo: {
                            size: 0
                        },
                        enabled : true
                    }
                }
            },

            series: {
                animation: false,

                }

                },

        },

        legend: {
            useHTML: true,
            enabled: true,
            align: 'right',
            verticalAlign: 'top',
            layout: 'vertical',
            symbolHeight: 12,
            itemMarginBottom: 1,
            symbolWidth: 25,
            symbolRadius: 1,
            labelFormatter: function () {
                return '<div style="width:180px;"><div class="pull-left" style= "font-weight: 500; padding-bottom: 3px;padding-top:3px;  width: 130px; font-family:Helvetica; white-space: normal; word-break:break-word ">' + this.name

            },

            },
        },

        series: [{
            data: this.donutchartData,
            allowPointSelect: true
        }]
    };

}
</code>```

}

答:
Assuming your series data is something like [{name: 'Category 1', id: 1, y: 20}, ...] you need to fetch the id from the point clicked

```<code>defaults() {
    let self = this; // store this in self so you can use component this and highcharts point event this
    this.options = {
        // other options
        plotOptions: {
            pie: {
                point: {
                    function(e){
                        let id = this.id; // get id from series data
                        self.userService.search(id);
                        return false;
                    }
                }
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a donut pie chart. on click of legend item it navigates to particular page which it retrieves from userSevice like given below -

pic of user service]1

legendItemClick:

function(e) { debugger;
    this.userService.search(e.target.id);
    return false;
}.bind(this)

i am looking for same functionality when i click on the pie slices of the chart it should navigate to particular related page. i tried this below but was not successful -

point: {
    events: {
        click: function(e){
            this.userService.search(e.target.id);
            return false;
        }.bind(this)
    }
}

any help where Iam going wrong ?

userService -

  search(id: any) {
        let headers = new Headers();

        let data = { "jql": id };
        let body = JSON.stringify(data);
        let http: Http
       var method = method || "post";
        var params;
        var path ;
        path = ' http://imptdg/IMR/Ticket/DashBoard';
                var form = document.createElement("form");
                form.setAttribute("method", method);
                form.setAttribute("action", path);
                        var hiddenField = document.createElement("input");
                        hiddenField.setAttribute("type", "hidden");
                        hiddenField.setAttribute("name", 'jql');
                        hiddenField.setAttribute("value", id);
                        form.appendChild(hiddenField);
                document.body.appendChild(form); debugger;
                form.submit();

    }

defaults() {
    this.options = {

        title: { text: ' ' },
        colors: ['rgba(79, 162, 189, 1)', 'rgba(84, 135, 201, 1)', 'rgba(143, 185, 91, 1)', 'rgba(90, 183, 130, 1)', 'rgba(71, 195, 185, 1)', 'rgba(190, 120, 203, 1)', 'rgba(228, 211, 84, 1)', 'rgba(43, 144, 143, 1)', 'rgba(145, 232, 225, 1)'],
        chart: {
            type: 'pie',
            animation: true
        },
        credits: {
            enabled: false
        },
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 300
                },
                chartOptions: {
                    legend: {
                        align: 'center',
                        verticalAlign: 'bottom',
                        layout: 'vertical',
                        labelFormatter: function () {
                            return '
' + this.name +
                                '' + this.value +
                                '
 ';
                        }
                    },
                    pie: {
                        size: 50,
                        innerSize: 20
                    }
                }
            }]
        },

        plotOptions: {
            pie: {
                innerSize: '40%',
                allowPointSelect: true,
                slicedOffset: 0,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },

                showInLegend: true,
                 point: {
                    events: {
                        click:function(e){
                            this.userService.search(e.target.id); // this part not working
                            return false;
                        }.bind(this),

                        legendItemClick: function (e) {

                            this.userService.search(e.target.id);
                            return false;
                        }.bind(this),

                    }

                    },
                states: {
                    hover: {
                        halo: {
                            size: 0
                        },
                        enabled : true
                    }
                }
            },

            series: {
                animation: false,

                }

                },

        },

        legend: {
            useHTML: true,
            enabled: true,
            align: 'right',
            verticalAlign: 'top',
            layout: 'vertical',
            symbolHeight: 12,
            itemMarginBottom: 1,
            symbolWidth: 25,
            symbolRadius: 1,
            labelFormatter: function () {
                return '

' + this.name

            },

            },
        },

        series: [{
            data: this.donutchartData,
            allowPointSelect: true
        }]
    };

}

}

Body:
Assuming your series data is something like [{name: 'Category 1', id: 1, y: 20}, ...] you need to fetch the id from the point clicked

defaults() {
    let self = this; // store this in self so you can use component this and highcharts point event this
    this.options = {
        // other options
        plotOptions: {
            pie: {
                point: {
                    function(e){
                        let id = this.id; // get id from series data
                        self.userService.search(id);
                        return false;
                    }
                }
            }
        }
    }
}


问:
How do you get the active element using Waypoint?
I'm using Waypoint (7.3.2) in React (16) to try and create a list of scrollable items where each item fades to invisible as it reaches the top of the div.  My basic question is how do I get a reference to the element that enters/leaves the waypoint in the event or callback?

I thought that by including ref={} in the element I wanted to get in the callback I would get a reference to the element and be able to change the opacity. The following is the code where Waypoint is plugged in:

```<code>class Division extends Component {
    constructor(props) {
        super(props);
    }

    _handleWayPointEnter = (event) => {
        console.log("Waypoint enter " + JSON.stringify(event, 4));
    }
    _handleWayPointLeave = (event) => {
        console.log("Waypoint leave " + JSON.stringify(event, 4));
    }

    render() {
        let inlineStyle= {opacity : this.state.opacity};
        return (
            <Waypoint debug={false} onEnter={this._handleWayPointEnter} onLeave={this._handleWayPointLeave} >
                <div style={inlineStyle} ref={this.props.innerRef} className="sch-division">
                    {this.props.name}<br/>
                    <SomeOtherComponent />
                </div>
            </Waypoint>
        );
    }

}

export default Division;
</code>```

Any/all replies appreciated!

-- griff

答:
From react-waypoint docs :

If you do pass a child, it can be a single DOM component (e.g.
)
  or a composite component (e.g. <MyComponent />).

Waypoint needs a DOM node to compute its boundaries. When you pass a
  DOM component to Waypoint, it handles getting a reference to the DOM
  node through the ref prop automatically. If you pass a composite
  component, you need to make use of the innerRef prop passed by
  Waypoint to your component. Simply pass it through as the ref of a DOM
  component and you're all set. Like in this example:

```<code>class Block extends React.Component {
  render() {
    return <div ref={this.props.innerRef}>Hello</div>
  }
}
Block.propTypes = {
  innerRef: PropTypes.func.isRequired,
}

const App = () => (
  <Waypoint>
    <Block />
  </Waypoint>
)
</code>```

Here you're using a single DOM component (
), i suggest you store your div ref like this :

```<code><div style={inlineStyle} ref={(div) => { this.divinwaypoint = div; }} className="sch-division">
</code>```

Then use it in your functions :

```<code>_handleWayPointEnter = (event) => {
   console.log("Waypoint enter " + JSON.stringify(event, 4));
   this.divinwaypoint.style.opacity = 0;
}
</code>```

Edit: i'm not using waypoint but i think it should display your component ref in the event prop.

Body:
I'm using Waypoint (7.3.2) in React (16) to try and create a list of scrollable items where each item fades to invisible as it reaches the top of the div.  My basic question is how do I get a reference to the element that enters/leaves the waypoint in the event or callback?

I thought that by including ref={} in the element I wanted to get in the callback I would get a reference to the element and be able to change the opacity. The following is the code where Waypoint is plugged in:

class Division extends Component {
    constructor(props) {
        super(props);
    }

    _handleWayPointEnter = (event) => {
        console.log("Waypoint enter " + JSON.stringify(event, 4));
    }
    _handleWayPointLeave = (event) => {
        console.log("Waypoint leave " + JSON.stringify(event, 4));
    }

    render() {
        let inlineStyle= {opacity : this.state.opacity};
        return (
            <Waypoint debug={false} onEnter={this._handleWayPointEnter} onLeave={this._handleWayPointLeave} >

                    {this.props.name}

                    <SomeOtherComponent />

            </Waypoint>
        );
    }

}

export default Division;

Any/all replies appreciated!

-- griff

Body:
From react-waypoint docs :

If you do pass a child, it can be a single DOM component (e.g. <div>)
  or a composite component (e.g. <MyComponent />).

Waypoint needs a DOM node to compute its boundaries. When you pass a
  DOM component to Waypoint, it handles getting a reference to the DOM
  node through the ref prop automatically. If you pass a composite
  component, you need to make use of the innerRef prop passed by
  Waypoint to your component. Simply pass it through as the ref of a DOM
  component and you're all set. Like in this example:

class Block extends React.Component {
  render() {
    return <div ref={this.props.innerRef}>Hello</div>
  }
}
Block.propTypes = {
  innerRef: PropTypes.func.isRequired,
}

const App = () => (
  <Waypoint>
    <Block />
  </Waypoint>
)

Here you're using a single DOM component (<div>), i suggest you store your div ref like this :

<div style={inlineStyle} ref={(div) => { this.divinwaypoint = div; }} className="sch-division">

Then use it in your functions :

_handleWayPointEnter = (event) => {
   console.log("Waypoint enter " + JSON.stringify(event, 4));
   this.divinwaypoint.style.opacity = 0;
}

Edit: i'm not using waypoint but i think it should display your component ref in the event prop.


问:
How to add the confidence interval in scatter plot (ggplot in R)
I want to show the 90%RI intervals of the dependent variable at each level of the categorical variable and also the whole population on this plot. The 90%RI for disp variable at vs=0 is 200-250, the RI for disp variable at vs=1 is 220-250, and the CI for disp for whole data set is 300-400. How can I add these intervals into this scatter plot?</p>

```<code>ggplot(mtcars, aes(mpg, disp)) +
      geom_point(aes(colour=factor(vs),
      fill = factor(vs)), shape=21, size = 4) +
  scale_fill_manual(values=c("blue", "pink")) +
  scale_colour_manual(values=c("black", "black"))
</code>```

答:
Perhaps something like:

```<code>ggplot(mtcars, aes(mpg, disp, colour = factor(vs), fill = factor(vs))) +
  geom_point(shape = 21, size = 4, col = "black") +
  stat_summary(aes(vs+8, disp, col = factor(vs)),
               fun.data = function(x) mean_cl_normal(x, conf.int = 0.9)) +
  stat_summary(aes(7, disp, group = 1),
               fun.data = function(x) mean_cl_normal(x, conf.int = 0.9))
</code>```

If you have intervals, you could use:

```<code>cis <- data.frame(vs = c(0, 1, 'all'), lwr = c(200, 220, 300), upr = c(250, 250, 400))
ggplot(mtcars, aes(colour = factor(vs), fill = factor(vs))) +
  geom_point(aes(mpg, disp), shape = 21, size = 4, col = "black") +
  geom_linerange(aes(x = c(8:10), ymin = lwr, ymax = upr), cis)
</code>```

Body:
I want to show the 90%RI intervals of the dependent variable at each level of the categorical variable and also the whole population on this plot. The 90%RI for disp variable at vs=0 is 200-250, the RI for disp variable at vs=1 is 220-250, and the CI for disp for whole data set is 300-400. How can I add these intervals into this scatter plot?

ggplot(mtcars, aes(mpg, disp)) +
      geom_point(aes(colour=factor(vs),
      fill = factor(vs)), shape=21, size = 4) +
  scale_fill_manual(values=c("blue", "pink")) +
  scale_colour_manual(values=c("black", "black"))

Body:
Perhaps something like:

ggplot(mtcars, aes(mpg, disp, colour = factor(vs), fill = factor(vs))) +
  geom_point(shape = 21, size = 4, col = "black") +
  stat_summary(aes(vs+8, disp, col = factor(vs)),
               fun.data = function(x) mean_cl_normal(x, conf.int = 0.9)) +
  stat_summary(aes(7, disp, group = 1),
               fun.data = function(x) mean_cl_normal(x, conf.int = 0.9))

If you have intervals, you could use:

cis <- data.frame(vs = c(0, 1, 'all'), lwr = c(200, 220, 300), upr = c(250, 250, 400))
ggplot(mtcars, aes(colour = factor(vs), fill = factor(vs))) +
  geom_point(aes(mpg, disp), shape = 21, size = 4, col = "black") +
  geom_linerange(aes(x = c(8:10), ymin = lwr, ymax = upr), cis)


问:
Padded text padding overflow not affecting word break
Word "under" should go to next line, but it doesn't cause of inline padding i think.

Is there anyway i can get text to break to next line when white padding touches edge of container.

Text needs to stay as inline cause i need that blank space between text lines. Tho if you have solution which requires to change that and result looks same as mine only the problem is fixed, than that will work too.

P.S. My container in real situation is 100% 100% so width,height is not fixed for the block.

It seems like it's not possible cause inline padding doesnt affect wrapping in any way and is completely ignored.

body {
  background: #111111;
}
.container {
  width: 338px;
  height: 600px;
  background-color: #000;
  font-family: Arial;
  text-align: center;
}
h1 {
  font-weight: bold;
  font-size: 48px;
  background-color: #fff;
  display: inline;
  line-height: 95px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
  padding: 10px 20px 10px 20px;
}
.sub {
  display: inline;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>Heading title</h1>
  <br/>
  <span class="sub">Some random text under heading title</span>
</div></code>```

答:
If you use inline-block rather than inline you get the desired behaviour but this will cause both lines to be wrapped in one box element.

Here's a Fiddle with the changed style, all I changed was:

```<code>.sub {
  display: inline-block; // was "inline"
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}
</code>```

More details on the problem you are facing:

In your given example, the width of your h1 is determined by the widest element on your page which is the container. So as soon as the width of the heading exceeds the width of the wrapping element, it wraps to the next line. Your rule box-decoration-break: clone; is not used to somehow cut the heading into two same-width elements, it simply makes sure that the padding on both wrapped elements is the same, if you had omitted it, you would not get a padding on the right of the first and no padding on the left of the second line.

Another idea

You could use a trick to get your desired result that does not involve any JS:

As the wrapping position of the title is defined by the next element defining the width, you can add your title in a DIV with a defined width. This will then make sure that the title wraps at the right position as you can see in this Fiddle. Basically that's the code you need:

HTML:

```<code><div class="defined-width-for-heading">
  <span class="sub">Some random text under heading title</span>
</div>
</code>```

CSS:

```<code>.defined-width-for-heading {
  width: 300px;
}

.sub {
  display: inline;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}
</code>```

Body:
Word "under" should go to next line, but it doesn't cause of inline padding i think.

Is there anyway i can get text to break to next line when white padding touches edge of container.

Text needs to stay as inline cause i need that blank space between text lines. Tho if you have solution which requires to change that and result looks same as mine only the problem is fixed, than that will work too.

P.S. My container in real situation is 100% 100% so width,height is not fixed for the block.

It seems like it's not possible cause inline padding doesnt affect wrapping in any way and is completely ignored.

body {
  background: #111111;
}
.container {
  width: 338px;
  height: 600px;
  background-color: #000;
  font-family: Arial;
  text-align: center;
}
h1 {
  font-weight: bold;
  font-size: 48px;
  background-color: #fff;
  display: inline;
  line-height: 95px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
  padding: 10px 20px 10px 20px;
}
.sub {
  display: inline;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}

Heading title

  Some random text under heading title

Body:
If you use inline-block rather than inline you get the desired behaviour but this will cause both lines to be wrapped in one box element.

Here's a Fiddle with the changed style, all I changed was:

.sub {
  display: inline-block; // was "inline"
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}

More details on the problem you are facing:

In your given example, the width of your h1 is determined by the widest element on your page which is the container. So as soon as the width of the heading exceeds the width of the wrapping element, it wraps to the next line. Your rule box-decoration-break: clone; is not used to somehow cut the heading into two same-width elements, it simply makes sure that the padding on both wrapped elements is the same, if you had omitted it, you would not get a padding on the right of the first and no padding on the left of the second line.

Another idea

You could use a trick to get your desired result that does not involve any JS:

As the wrapping position of the title is defined by the next element defining the width, you can add your title in a DIV with a defined width. This will then make sure that the title wraps at the right position as you can see in this Fiddle. Basically that's the code you need:

HTML:

<div class="defined-width-for-heading">
  <span class="sub">Some random text under heading title</span>
</div>

CSS:

.defined-width-for-heading {
  width: 300px;
}

.sub {
  display: inline;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}


问:
Swift: How to refresh UICollectionView layout after rotation of the device
I used UICollectionView (flowlayout) to build a simple layout.
the width for each cell is set to the width of screen using self.view.frame.width

but when I rotate the device, the cells don't get updated.

I have found a function, which is called upon orientation change :

```<code>override func willRotateToInterfaceOrientation(toInterfaceOrientation:
  UIInterfaceOrientation, duration: NSTimeInterval) {
    //code
}
</code>```

but I am unable to find a way to update the UICollectionView layout

The main code is here:

```<code>class ViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{

    @IBOutlet weak var myCollection: UICollectionView!

    var numOfItemsInSecOne: Int!
    override func viewDidLoad() {
        super.viewDidLoad()

        numOfItemsInSecOne = 8
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {

        //print("orientation Changed")
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numOfItemsInSecOne
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellO", forIndexPath: indexPath)

        return cell
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
    let itemSize = CGSize(width: self.view.frame.width, height: 100)
    return itemSize
    }}
</code>```

答:
To update UICollectionViewLayout, traitCollectionDidChange method might be used as well:

```<code>override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    guard previousTraitCollection != nil else { return }
    collectionView?.collectionViewLayout.invalidateLayout()
}
</code>```

Body:
I used UICollectionView (flowlayout) to build a simple layout.
the width for each cell is set to the width of screen using self.view.frame.width

but when I rotate the device, the cells don't get updated.

I have found a function, which is called upon orientation change :

override func willRotateToInterfaceOrientation(toInterfaceOrientation:
  UIInterfaceOrientation, duration: NSTimeInterval) {
    //code
}

but I am unable to find a way to update the UICollectionView layout

The main code is here:

class ViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{

    @IBOutlet weak var myCollection: UICollectionView!

    var numOfItemsInSecOne: Int!
    override func viewDidLoad() {
        super.viewDidLoad()

        numOfItemsInSecOne = 8
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {

        //print("orientation Changed")
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numOfItemsInSecOne
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellO", forIndexPath: indexPath)

        return cell
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
    let itemSize = CGSize(width: self.view.frame.width, height: 100)
    return itemSize
    }}

Body:
To update UICollectionViewLayout, traitCollectionDidChange method might be used as well:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    guard previousTraitCollection != nil else { return }
    collectionView?.collectionViewLayout.invalidateLayout()
}

ContentLicense: CC BY-SA 4.0


问:
Make scrollbars only visible when a Div is hovered over?
I am trying to figure out how to have a scrollable div that only shows its scrollbars when Hovered.

Example is Google Image search, in the image below you can see how the left sidebar does not appear to be scroll-able until you hover the mouse over it.

Is this possible with CSS or is Javascript required?  If possible maybe a quick example how to do such a task?

答:
One trick for this, for webkit browsers, is to create an invisible scrollbar, and then make it appear on hover. This method does not affect the scrolling area width as the space needed for the scrollbar is already there.

Something like this:

body {
  height: 500px;
  &::-webkit-scrollbar {
    background-color: transparent;
    width: 10px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: transparent;
  }
}

body:hover {
  &::-webkit-scrollbar-thumb {
    background-color: black;
  }
}

.full-width {
  width: 100%;
  background: blue;
  padding: 30px;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>some content here

<div class="full-width">does not change</div></code>```

Body:
One trick for this, for webkit browsers, is to create an invisible scrollbar, and then make it appear on hover. This method does not affect the scrolling area width as the space needed for the scrollbar is already there.

Something like this:

body {
  height: 500px;
  &::-webkit-scrollbar {
    background-color: transparent;
    width: 10px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: transparent;
  }
}

body:hover {
  &::-webkit-scrollbar-thumb {
    background-color: black;
  }
}

.full-width {
  width: 100%;
  background: blue;
  padding: 30px;
  color: white;
}

some content here

<div class="full-width">does not change</div>


问:
C++ - enum vs. const vs. #define
At the end of the article here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/, it mentions the following:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

How is the bold sentence above achieved?

Thanks.

答:
Consider this code,

```<code>#define WIDTH 300

enum econst
{
   eWidth=300
};

const int Width=300;

struct sample{};

int main()
{
        sample s;
        int x = eWidth * s; //error 1
        int y = WIDTH * s;  //error 2
        int z = Width * s;  //error 3
        return 0;
}
</code>```

Obviously each multiplication results in compilation-error, but see how the GCC generates the messages for each multiplication error:

prog.cpp:19: error: no match for
  ‘operator*’ in ‘eWidth * s’

  prog.cpp:20: error: no match for
  ‘operator*’ in ‘300 * s’

  prog.cpp:21: error: no match for
  ‘operator*’ in ‘Width * s’

In the error message, you don't see the macro WIDTH which you've #defined, right? That is because by the time GCC makes any attempt to compile the line corresponds to second error, it doesn't see WIDTH, all it sees only 300, as before GCC compiles the line, preprocessor has already replaced WIDTH with 300. On the other hand, there is no any such thing happens with enum eWidth  and const Width.

See the error yourself here : http://www.ideone.com/naZ3P

Also, read Item 2 : Prefer consts, enums, and inlines to #defines from Effective C++ by Scott Meyers.

ContentLicense: CC BY-SA 2.5

Title: C++ - enum vs. const vs. #define

Body:
Consider this code,

#define WIDTH 300

enum econst
{
   eWidth=300
};

const int Width=300;

struct sample{};

int main()
{
        sample s;
        int x = eWidth * s; //error 1
        int y = WIDTH * s;  //error 2
        int z = Width * s;  //error 3
        return 0;
}

Obviously each multiplication results in compilation-error, but see how the GCC generates the messages for each multiplication error:

prog.cpp:19: error: no match for
  ‘operator*’ in ‘eWidth * s’

  prog.cpp:20: error: no match for
  ‘operator*’ in ‘300 * s’

  prog.cpp:21: error: no match for
  ‘operator*’ in ‘Width * s’

In the error message, you don't see the macro WIDTH which you've #defined, right? That is because by the time GCC makes any attempt to compile the line corresponds to second error, it doesn't see WIDTH, all it sees only 300, as before GCC compiles the line, preprocessor has already replaced WIDTH with 300. On the other hand, there is no any such thing happens with enum eWidth  and const Width.

See the error yourself here : http://www.ideone.com/naZ3P

Also, read Item 2 : Prefer consts, enums, and inlines to #defines from Effective C++ by Scott Meyers.


问:
React-native TouchableOpacity button doesn't respect border/border-radius
I have created a generic button which I'd like to have round edges instead of being a square. My button component is as such:

const Button = ({ onPress, children }) => {
  const { buttonStyle, textStyle } = styles;

  return (
    <TouchableOpacity onPress={onPress} style={buttonStyle}>
      <Text style={textStyle}>
          {children}
      </Text>
    </TouchableOpacity>
  );
};

const styles = {
    textStyle: {
        alignSelf: 'center',
        color: colors.primaryTeal,
        fontSize: 16,
        fontWeight: '600',
        paddingTop: 10,
        paddingBottom: 10,
    },
    buttonStyle: {
        flex: 1,
        backgroundColor: colors.whiteText,
        marginLeft: 5,
        marginRight: 5,
        borderRadius: 50
    }
};
```

<p>However, it remains to be square and doesn't respond to <code>borderRadius</code> at all.</p>

<p>It's invoked as such:</p>

<pre class="lang-js prettyprint-override"><code><Button onPress={this.onButtonPress.bind(this)}>
    Log in
</Button>
</code>```

How do I make it respect borderRadius and get round edges?

The login form in which it appears(Render)

  render() {
    return (
        <Card>
            <CardSection>
                <Input
                    placeholder="user@gmail.com"
                    label="Email"
                    value={this.state.email}
                    onChangeText={email => this.setState({ email })}
                />
            </CardSection>
            <CardSection>
                <Input
                    secureTextEntry
                    placeholder="password"
                    label="Password"
                    value={this.state.password}
                    onChangeText={password => this.setState({ password })}
                />
            </CardSection>
            <View style={styles.btnWrapper}>
            <CardSection>
                {this.state.loading ?
                    <Spinner size="small" /> :
                    <Button onPress={this.onButtonPress.bind(this)}>
                        Log in
                    </Button>}
            </CardSection>
            </View>
            <Text style={styles.errorTextStyle} disabled={this.state.error !== null}>
                {this.state.error}
            </Text>
        </Card>
```

<p>CardSection component:</p>

<pre class="lang-js prettyprint-override"><code>const CardSection = (props) => {
  return (
    <View style={styles.containerStyle}>
      {props.children}
    </View>
  );
};

const styles = {
  containerStyle: {
    borderBottomWidth: 1,
    padding: 5,
    backgroundColor: '#fff',
    justifyContent: 'flex-start',
    flexDirection: 'row',
    borderColor: '#ddd',
    position: 'relative'
  }
};
</code>```

答:
Works perfectly fine. Just make sure to use react native's StyleSheet.create to get cached styles.
Maybe your button container view background is white and you're not seeing the rounded corners.

Heres my working snack

Code snippet i used, but refer to the snack as you'll see it live in action.

import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';

const Button = ({ onPress, children }) => {

  return (
    <TouchableOpacity onPress={onPress} style={styles.buttonStyle}>
      <Text style={styles.textStyle}>
          {children}
      </Text>
    </TouchableOpacity>
  );
};

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Button>
          Log in
        </Button>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    backgroundColor: 'black',
  },
  textStyle: {
        alignSelf: 'center',
        color: 'teal',
        fontSize: 16,
        fontWeight: '600',
        paddingTop: 10,
        paddingBottom: 10,
    },
    buttonStyle: {
        flex: 1,
        backgroundColor: 'white',
        marginLeft: 5,
        marginRight: 5,
        borderRadius: 50
    },
});
```

Body:
I have created a generic button which I'd like to have round edges instead of being a square. My button component is as such:

const Button = ({ onPress, children }) => {
  const { buttonStyle, textStyle } = styles;

  return (
    <TouchableOpacity onPress={onPress} style={buttonStyle}>
      <Text style={textStyle}>
          {children}
      </Text>
    </TouchableOpacity>
  );
};

const styles = {
    textStyle: {
        alignSelf: 'center',
        color: colors.primaryTeal,
        fontSize: 16,
        fontWeight: '600',
        paddingTop: 10,
        paddingBottom: 10,
    },
    buttonStyle: {
        flex: 1,
        backgroundColor: colors.whiteText,
        marginLeft: 5,
        marginRight: 5,
        borderRadius: 50
    }
};

However, it remains to be square and doesn't respond to borderRadius at all.

It's invoked as such:

<Button onPress={this.onButtonPress.bind(this)}>
    Log in
</Button>

How do I make it respect borderRadius and get round edges?

The login form in which it appears(Render)

  render() {
    return (
        <Card>
            <CardSection>
                <Input
                    placeholder="user@gmail.com"
                    label="Email"
                    value={this.state.email}
                    onChangeText={email => this.setState({ email })}
                />
            </CardSection>
            <CardSection>
                <Input
                    secureTextEntry
                    placeholder="password"
                    label="Password"
                    value={this.state.password}
                    onChangeText={password => this.setState({ password })}
                />
            </CardSection>
            <View style={styles.btnWrapper}>
            <CardSection>
                {this.state.loading ?
                    <Spinner size="small" /> :
                    <Button onPress={this.onButtonPress.bind(this)}>
                        Log in
                    </Button>}
            </CardSection>
            </View>
            <Text style={styles.errorTextStyle} disabled={this.state.error !== null}>
                {this.state.error}
            </Text>
        </Card>

CardSection component:

const CardSection = (props) => {
  return (
    <View style={styles.containerStyle}>
      {props.children}
    </View>
  );
};

const styles = {
  containerStyle: {
    borderBottomWidth: 1,
    padding: 5,
    backgroundColor: '#fff',
    justifyContent: 'flex-start',
    flexDirection: 'row',
    borderColor: '#ddd',
    position: 'relative'
  }
};


问:
LibGDX: Implement touch screen, without touching the screen
I'm using LibGDX.

Let's say that I wan't to jump - but not really touching the screen, I don't want to use a keyboard forsay, And implement the touch, like i was touching the screen.
Can i do that?

Can one let's say "test" the button without pressing it (from the touch screen of application / android / ios / etc..)?

Example of a button from InputListener:

```<code>final Image imageJumpButton = new Image(new Texture("jbjump.png"));
imageJumpButton.addListener(new InputListener() {

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP= true;
        return true;
    }

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP = false;
    }
});
</code>```

I thank you.

答:
I would suggest to use Button class for a button instead of Image. There is a convenient way to do what you ask with Button:

```<code>final Button imageJumpButton = new Button(new TextureRegionDrawable(new TextureRegion(new Texture("jbjump.png"))));
//use ChangeListener instead of InputListener
imageJumpButton.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            Gdx.app.log("", "Button is pressed");
        }
    });
</code>```

Then you could programmatically press the button:

```<code>//this will trigger changed() method of the ChangeListener
imageJumpButton.toggle();
</code>```

Update

If you want to do something, while the button is pressed, call this in your render() method:

```<code>if (button.isPressed())
    //do something each frame, while button is pressed
</code>```

For example, if you want a player to run, while the button is pressed, it would be something like this:

```<code>public void update(float deltaTime) {
    if (button.isPressed())
        player.x += deltaTime * velocityX;
}
</code>```

And by the way, you don't need to add ChangeListener to the button in this case.

Body:
I'm using LibGDX.

Let's say that I wan't to jump - but not really touching the screen, I don't want to use a keyboard forsay, And implement the touch, like i was touching the screen.
Can i do that?

Can one let's say "test" the button without pressing it (from the touch screen of application / android / ios / etc..)?

Example of a button from InputListener:

final Image imageJumpButton = new Image(new Texture("jbjump.png"));
imageJumpButton.addListener(new InputListener() {

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP= true;
        return true;
    }

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        JOYSTICK_UP = false;
    }
});

I thank you.

Body:
I would suggest to use Button class for a button instead of Image. There is a convenient way to do what you ask with Button:

final Button imageJumpButton = new Button(new TextureRegionDrawable(new TextureRegion(new Texture("jbjump.png"))));
//use ChangeListener instead of InputListener
imageJumpButton.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            Gdx.app.log("", "Button is pressed");
        }
    });

Then you could programmatically press the button:

//this will trigger changed() method of the ChangeListener
imageJumpButton.toggle();

Update

If you want to do something, while the button is pressed, call this in your render() method:

if (button.isPressed())
    //do something each frame, while button is pressed

For example, if you want a player to run, while the button is pressed, it would be something like this:

public void update(float deltaTime) {
    if (button.isPressed())
        player.x += deltaTime * velocityX;
}

And by the way, you don't need to add ChangeListener to the button in this case.


问:
Cannot save Spark dataframe to Google Cloud Storage from PySpark
I have a Spark dataframe that I'm trying to save to a Google Storage bucket with the line

```<code>df.write.format("com.databricks.spark.csv").save('gs://some-test-bucket-delete-me')
</code>```

But Pyspark raises the following exception

```<code>Py4JJavaError: An error occurred while calling o55.save.
: java.lang.RuntimeException: java.lang.ClassNotFoundException: Class com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem not found
</code>```

What I've tried:

The typical solutions to this exception is to make sure that the environmental variable HADOOP_CLASSPATH to point at the gcs-connector-latest-hadoop2.jar file, which it does. I've tried using the Hadoop version 1 as well as version 2 jars incase that was the problem. I've  tried explicitly pointing at it within Jupyter notebook with

```<code>sc._jsc.hadoopConfiguration().set("spark.driver.extraClassPath", "/home/****/hadoop-2.8.2/share/hadoop/common/lib/gcs-connector-latest-hadoop1.jar")
</code>```

to no avail.

If I try hadoop fs -ls gs://gs://some-test-bucket-delete-me from bash the command returns perfectly, which is supposed to indicate that that the Google Cloud Storage connect works but for some reason I can't seem to get this functionality to work in PySpark.

Things that may be important:

Spark Version 2.2.0

Python 3.6.1 :: Anaconda custom (64-bit)

I'm running PySpark locally

答:
You should run gcloud init first

Then try df.write.csv('gs://some-test-bucket-delete-me/file_name')

Body:
I have a Spark dataframe that I'm trying to save to a Google Storage bucket with the line

df.write.format("com.databricks.spark.csv").save('gs://some-test-bucket-delete-me')

But Pyspark raises the following exception

Py4JJavaError: An error occurred while calling o55.save.
: java.lang.RuntimeException: java.lang.ClassNotFoundException: Class com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem not found

What I've tried:

The typical solutions to this exception is to make sure that the environmental variable HADOOP_CLASSPATH to point at the gcs-connector-latest-hadoop2.jar file, which it does. I've tried using the Hadoop version 1 as well as version 2 jars incase that was the problem. I've  tried explicitly pointing at it within Jupyter notebook with

sc._jsc.hadoopConfiguration().set("spark.driver.extraClassPath", "/home/****/hadoop-2.8.2/share/hadoop/common/lib/gcs-connector-latest-hadoop1.jar")

to no avail.

If I try hadoop fs -ls gs://gs://some-test-bucket-delete-me from bash the command returns perfectly, which is supposed to indicate that that the Google Cloud Storage connect works but for some reason I can't seem to get this functionality to work in PySpark.

Things that may be important:

Spark Version 2.2.0

Python 3.6.1 :: Anaconda custom (64-bit)

I'm running PySpark locally


问:
Cannot get dataTable responsive extension to work
I have a table that is being created with the responsive property of true

It is adding the dtr-inline class to my table but the table is not breaking on the breakpoints and no matter the screensize, the rows are not becoming children of the parent rows and the collapse class is notbeing added.  I am ending up with this HTML for my table...

```<code><table id="member-details" class="table table-striped table-bordered dataTable no-footer dtr-inline" role="grid" cellspacing="0" aria-describedby="member-details_info">
    <thead>
        <tr role="row">
            <th class="sorting" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-label="Pay No: activate to sort column ascending">Pay No</th>
            <th class="sorting" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-label="Name: activate to sort column ascending">Name</th>
            <th class="sorting_asc" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Ni.No: activate to sort column descending">Ni.No</th>
            <th class="sorting" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-label="DOB: activate to sort column ascending">DOB</th>
            <th class="sorting" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-label="Dept: activate to sort column ascending">Dept</th>
            <th class="sorting" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-label="Location: activate to sort column ascending">Location</th>
            <th class="sorting" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-label="Pay point: activate to sort column ascending">Pay point</th>
            <th class="sorting" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-label="Scheme: activate to sort column ascending">Scheme</th>
            <th class="sorting" tabindex="0" aria-controls="member-details" rowspan="1" colspan="1" aria-label="Category: activate to sort column ascending">Category</th>
            <th class="details-control sorting_disabled" rowspan="1" colspan="1" style="width: 10%;" aria-label="Options">Options</th>
        </tr>
    </thead>
    <tbody>
        ...
    </tbody>
</table>
</code>```

My table also uses bootstrap and I am loading the JS and CSS in this order

"Scripts/vendor/jquery-1.12.4.js",

  "Scripts/vendor/datatables-1.10.15.js",

  "Scripts/vendor/dataTables.responsive.js",

  "Scripts/vendor/datatables-select-1.2.2.js",

  "Scripts/vendor/less-1.5.1.min.js",

  "Scripts/vendor/bootstrap.min.js",

  "Scripts/vendor/dataTables.bootstrap.min.js",

"Content/bootstrap.min.css",
  "Content/font-awesome.min.css",
  "Content/jquery.dataTables.min.css",
  "Content/responsive.dataTables.css",
  "Content/responsive.bootstrap.css",

and initiating the table as follows

```<code>!$.fn.DataTable.isDataTable("#" + domElement) ? $("#" + domElement).DataTable({
    responsive: true,
    language: {
        "emptyTable": "No records found",
        "processing": eq.api.spinner()
    },
    processing: true,
    serverSide: true,
    info: true,
    stateSave: true,
    bFilter: false,
    bAutoWidth: false,
    lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
    columns: columns,
    ajax: ajaxPart,
</code>```

Am I doing something wrong? Can responsive not be used with bootstrap?

I am loading the responsive resources first

Mike

答:
You can use bootstrap with datatable responsive. See this example.

As datatable documentation you need to load responsive plugin files, and add nowarp class to your HTML code:

So your code should be like this:

```<code><table id="member-details" class="nowrap table table-striped table-bordered dataTable no-footer dtr-inline" role="grid" cellspacing="0" aria-describedby="member-details_info">
</code>```

Also see responsive example

Body:
I have a table that is being created with the responsive property of true

It is adding the dtr-inline class to my table but the table is not breaking on the breakpoints and no matter the screensize, the rows are not becoming children of the parent rows and the collapse class is notbeing added.  I am ending up with this HTML for my table...

            Pay No
            Name
            Ni.No
            DOB
            Dept
            Location
            Pay point
            Scheme
            Category
            Options

        ...

My table also uses bootstrap and I am loading the JS and CSS in this order

"Scripts/vendor/jquery-1.12.4.js",

  "Scripts/vendor/datatables-1.10.15.js",

  "Scripts/vendor/dataTables.responsive.js",

  "Scripts/vendor/datatables-select-1.2.2.js",

  "Scripts/vendor/less-1.5.1.min.js",

  "Scripts/vendor/bootstrap.min.js",

  "Scripts/vendor/dataTables.bootstrap.min.js",

"Content/bootstrap.min.css",
  "Content/font-awesome.min.css",
  "Content/jquery.dataTables.min.css",
  "Content/responsive.dataTables.css",
  "Content/responsive.bootstrap.css",

and initiating the table as follows

!$.fn.DataTable.isDataTable("#" + domElement) ? $("#" + domElement).DataTable({
    responsive: true,
    language: {
        "emptyTable": "No records found",
        "processing": eq.api.spinner()
    },
    processing: true,
    serverSide: true,
    info: true,
    stateSave: true,
    bFilter: false,
    bAutoWidth: false,
    lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
    columns: columns,
    ajax: ajaxPart,

Am I doing something wrong? Can responsive not be used with bootstrap?

I am loading the responsive resources first

Mike

Body:
You can use bootstrap with datatable responsive. See this example.

As datatable documentation you need to load responsive plugin files, and add nowarp class to your HTML code:

So your code should be like this:

<table id="member-details" class="nowrap table table-striped table-bordered dataTable no-footer dtr-inline" role="grid" cellspacing="0" aria-describedby="member-details_info">

Also see responsive example


问:
Errors when compiling library in command line
I am trying to compile this library: http://www.mega-nerd.com/SRC/win32.html . but I am having some trouble. Here's what happens:

```<code>C:\libsamplerate-0.1.8>make
    1 file(s) copied.
    1 file(s) copied.

Microsoft (R) Program Maintenance Utility Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.

    link.exe /nologo /dll /incremental:no /libpath:""C:\Program Files (x86)\
Microsoft Visual Studio 10.0\Common7\IDE"\Lib" /pdb:"libsamplerate-0.pdb" /impli
b:".\libsamplerate-0.lib" /machine:I386 /out:"libsamplerate-0.dll" /def:".\Win32
\libsamplerate-0.def" ".\src\samplerate.obj"  ".\src\src_linear.obj"  ".\src\src
_zoh.obj"  ".\src\src_sinc.obj"
LINK : fatal error LNK1181: cannot open input file 'Files.obj'
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 10.0
\VC\BIN\link.exe"' : return code '0x49d'
Stop.
</code>```

I run vcvars32.bat prior to attempting to compile, I think I have all the right folders in my path variable, but I'm new to this so I'm not entirely sure. What am I doing wrong?

答:
You get error: "LINK : fatal error LNK1181: cannot open input file 'Files.obj'"
Because the linker thinks you are adding file "Files" as one of input libraries.
This comes from "C:\Program Files (x86)" (see the "Files"?) ;-)</p>

Body:
I am trying to compile this library: http://www.mega-nerd.com/SRC/win32.html . but I am having some trouble. Here's what happens:

C:\libsamplerate-0.1.8>make
    1 file(s) copied.
    1 file(s) copied.

Microsoft (R) Program Maintenance Utility Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.

    link.exe /nologo /dll /incremental:no /libpath:""C:\Program Files (x86)\
Microsoft Visual Studio 10.0\Common7\IDE"\Lib" /pdb:"libsamplerate-0.pdb" /impli
b:".\libsamplerate-0.lib" /machine:I386 /out:"libsamplerate-0.dll" /def:".\Win32
\libsamplerate-0.def" ".\src\samplerate.obj"  ".\src\src_linear.obj"  ".\src\src
_zoh.obj"  ".\src\src_sinc.obj"
LINK : fatal error LNK1181: cannot open input file 'Files.obj'
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 10.0
\VC\BIN\link.exe"' : return code '0x49d'
Stop.

I run vcvars32.bat prior to attempting to compile, I think I have all the right folders in my path variable, but I'm new to this so I'm not entirely sure. What am I doing wrong?


问:
Where is the Cygwin config.log file located
I have installed cygwin recently and have installed all the required packages. I was trying to install libevent-2.1.8-stable. When I did ./configure it shows C compiler cannot create executables. See config.log for more details. But where can I find the config.log file? I have searched the cygwin installation directory but found nothing.</p>

答:
the config.log is produced by configure and it is in the directory where you run ./configure

C compiler cannot create executables could mean:
you have missed to install something or likely an antivirus is interfering with the compiler.


问:
How do I set the focus to the first input element in an HTML form independent from the id?
Is there a simple way to set the focus (input cursor) of a web page on the first input element (textbox, dropdownlist, ...) on loading the page without having to know the id of the element?

I would like to implement it as a common script for all my pages/forms of my web application.

答:
You should be able to use clientHeight instead of checking for the display attribute, since a parent could be hiding this element:</p>

```<code>function setFocus() {
    var forms = document.forms || [];
        for (var i = 0; i < forms.length; i++) {
            for (var j = 0; j < forms[i].length; j++) {
            var widget = forms[i][j];
                if ((widget && widget.domNode && widget.domNode.clientHeight > 0) && typeof widget.focus === "function")
                 && (typeof widget.disabled === "undefined" || widget.disabled === false)
                 && (typeof widget.readOnly === "undefined" || widget.readOnly === false)) {
                        widget.focus();
                        break;
                }
            }
        }
    }
}
</code>```

OwnerDisplayName: splattne

LastEditorDisplayName: John Topley

Body:
You should be able to use clientHeight instead of checking for the display attribute, since a parent could be hiding this element:

function setFocus() {
    var forms = document.forms || [];
        for (var i = 0; i < forms.length; i++) {
            for (var j = 0; j < forms[i].length; j++) {
            var widget = forms[i][j];
                if ((widget && widget.domNode && widget.domNode.clientHeight > 0) && typeof widget.focus === "function")
                 && (typeof widget.disabled === "undefined" || widget.disabled === false)
                 && (typeof widget.readOnly === "undefined" || widget.readOnly === false)) {
                        widget.focus();
                        break;
                }
            }
        }
    }
}


问:
How to deal with StompServerHandlers in vert-x
I'm using vert-x 3.5.0 and I want to use StompServer as a WebSocket server

My java code is following:

```<code>import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.stomp.StompServer;
import io.vertx.ext.stomp.StompServerHandler;
import io.vertx.ext.stomp.StompServerOptions;

StompServer server = StompServer.create(vertx, new StompServerOptions()
                .setPort(-1)
                .setWebsocketBridge(true)
                .setWebsocketPath("/stomp"))
                .handler(StompServerHandler.create(vertx)
                .receivedFrameHandler(event -> {
                    LOG.info(String.format("frame is %s", event.frame().getBodyAsString()));
                })
                .beginHandler(event -> {
                    LOG.info("Begin event");
                })
                .connectHandler(event -> {
                    LOG.info("Connect event");
                })
                .subscribeHandler(event -> {
                    LOG.info("Subscribe event");
                }));

        vertx.createHttpServer(
                new HttpServerOptions().setWebsocketSubProtocols("v10.stomp, v11.stomp, v13.stomp")
        )
                .websocketHandler(server.webSocketHandler())
                .listen(8080);
</code>```

Server is running and can receive a handshake request and a message. I see it from websocket client and from extended server log

```<code>Server received request: /stomp
[id: 0x1f899ae3, L:/127.0.0.1:8080 - R:/127.0.0.1:42550] WebSocket version V13 server handshake
WebSocket version 13 server handshake key: Qe8G85Aw1PwuQbWKPyJSrg==, response: VQVnKr2Jp8RuK/vltKb7XqBiMTU=
Decoding WebSocket Frame opCode=1
Decoding WebSocket Frame length=7
</code>```

But declared handlers (receivedFrameHandler, beginHandler, connectHandler, subscribeHandler) are not working. How to deal with them?

答:
You are configuring the WebSocket Stomp bridge that allows a client using  web socket to interact with the Stomp server. However, this client must send STOMP frames (and expect STOMP frames).

Typically:

The connectEvent is called when a STOMP client connects to the server
The beginEvent is called when you start a STOMP transaction.

If your web socket client is not sending the frames (CONNECT, BEGIN...), the callbacks won't be called.

You can see an example of the CONNECT frame here.

Body:
I'm using vert-x 3.5.0 and I want to use StompServer as a WebSocket server

My java code is following:

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.stomp.StompServer;
import io.vertx.ext.stomp.StompServerHandler;
import io.vertx.ext.stomp.StompServerOptions;

StompServer server = StompServer.create(vertx, new StompServerOptions()
                .setPort(-1)
                .setWebsocketBridge(true)
                .setWebsocketPath("/stomp"))
                .handler(StompServerHandler.create(vertx)
                .receivedFrameHandler(event -> {
                    LOG.info(String.format("frame is %s", event.frame().getBodyAsString()));
                })
                .beginHandler(event -> {
                    LOG.info("Begin event");
                })
                .connectHandler(event -> {
                    LOG.info("Connect event");
                })
                .subscribeHandler(event -> {
                    LOG.info("Subscribe event");
                }));

        vertx.createHttpServer(
                new HttpServerOptions().setWebsocketSubProtocols("v10.stomp, v11.stomp, v13.stomp")
        )
                .websocketHandler(server.webSocketHandler())
                .listen(8080);

Server is running and can receive a handshake request and a message. I see it from websocket client and from extended server log

Server received request: /stomp
[id: 0x1f899ae3, L:/127.0.0.1:8080 - R:/127.0.0.1:42550] WebSocket version V13 server handshake
WebSocket version 13 server handshake key: Qe8G85Aw1PwuQbWKPyJSrg==, response: VQVnKr2Jp8RuK/vltKb7XqBiMTU=
Decoding WebSocket Frame opCode=1
Decoding WebSocket Frame length=7

But declared handlers (receivedFrameHandler, beginHandler, connectHandler, subscribeHandler) are not working. How to deal with them?


问:
How can the Dropbox API alert when a token is received?

I am able to log in and do export/import from my Android app using the v2 Dropbox API. The only problem is on first run when a token is requested and the Dropbox app/website is launched - I have to run Auth.startOAuth2Authentication at least twice with a pause in between to be able to read the token with Auth.getOAuth2Token.

Is there anyway to wait() and get notified when startOAuth2Authentication returns after acquiring a token?

```<code>   Auth.startOAuth2Authentication(this, getString(R.string.app_key));
   //wait for response, retry, or time out and finish
   String accessToken = Auth.getOAuth2Token();
   prefs.edit().putString(ACCESS_TOKEN, accessToken).commit();
</code>```

答:
You shouldn't call startOAuth2Authentication twice, and you shouldn't call getOAuth2Token immediately after calling startOAuth2Authentication.

You should start the flow by calling startOAuth2Authentication as shown in the example here:

https://github.com/dropbox/dropbox-sdk-java/blob/master/examples/android/src/main/java/com/dropbox/core/examples/android/UserActivity.java#L36

And then you should complete the flow by calling getOAuth2Token later in onResume as shown in the example here:

https://github.com/dropbox/dropbox-sdk-java/blob/master/examples/android/src/main/java/com/dropbox/core/examples/android/DropboxActivity.java#L22

Body:
I am able to log in and do export/import from my Android app using the v2 Dropbox API. The only problem is on first run when a token is requested and the Dropbox app/website is launched - I have to run Auth.startOAuth2Authentication at least twice with a pause in between to be able to read the token with Auth.getOAuth2Token.

Is there anyway to wait() and get notified when startOAuth2Authentication returns after acquiring a token?

   Auth.startOAuth2Authentication(this, getString(R.string.app_key));
   //wait for response, retry, or time out and finish
   String accessToken = Auth.getOAuth2Token();
   prefs.edit().putString(ACCESS_TOKEN, accessToken).commit();


问:
Convert First character of each word to upper case
I have a String and I need to convert the first letter of each word to upper case and rest to lower case using xsl, For example,

Input String= dInEsh sAchdeV kApil Muk

Desired Output String= Dinesh Sachdev Kapil Muk

Although, I know I have to use translate function for the purpose but how can I translate the first charter of each word to Upper-case and rest all in lower- case using XSLT 1.0

Thanks

答:
You can also try this:

http://www.xsltfunctions.com/xsl/functx_camel-case-to-words.html

```<code> <xsl:function name="functx:camel-case-to-words" as="xs:string"
                  xmlns:functx="http://www.functx.com">
      <xsl:param name="arg" as="xs:string?"/>
      <xsl:param name="delim" as="xs:string"/>

      <xsl:sequence select="
       concat(substring($arg,1,1),
                 replace(substring($arg,2),'(\p{Lu})',
                            concat($delim, '$1')))
     "/>

</xsl:function>
</code>```

and backwards:
http://www.xsltfunctions.com/xsl/functx_words-to-camel-case.html

```<code><xsl:function name="functx:words-to-camel-case" as="xs:string"
              xmlns:functx="http://www.functx.com">
  <xsl:param name="arg" as="xs:string?"/>

  <xsl:sequence select="
     string-join((tokenize($arg,'\s+')[1],
       for $word in tokenize($arg,'\s+')[position() > 1]
       return functx:capitalize-first($word))
      ,'')
 "/>

</xsl:function>
</code>```

Body:
You can also try this:

http://www.xsltfunctions.com/xsl/functx_camel-case-to-words.html

 <xsl:function name="functx:camel-case-to-words" as="xs:string"
                  xmlns:functx="http://www.functx.com">
      <xsl:param name="arg" as="xs:string?"/>
      <xsl:param name="delim" as="xs:string"/>

      <xsl:sequence select="
       concat(substring($arg,1,1),
                 replace(substring($arg,2),'(\p{Lu})',
                            concat($delim, '$1')))
     "/>

</xsl:function>

and backwards:
http://www.xsltfunctions.com/xsl/functx_words-to-camel-case.html

<xsl:function name="functx:words-to-camel-case" as="xs:string"
              xmlns:functx="http://www.functx.com">
  <xsl:param name="arg" as="xs:string?"/>

  <xsl:sequence select="
     string-join((tokenize($arg,'\s+')[1],
       for $word in tokenize($arg,'\s+')[position() > 1]
       return functx:capitalize-first($word))
      ,'')
 "/>

</xsl:function>


问:
Get logged windows user in NodeJS
My NodeJS app is running on a Linux server.

I have several machines connecting to the app (via browser) running on Windows.

How can I get, in my app, the current windows logged in user?

答:
Browser trying to access that kind of information is considered a security risk and not wildly supported.

But you can access the logged in windows user name in Internet Explorer alone using  ActiveX. For more information of how to get follow this SO post
JavaScript - How to get the name of the current user

Title: Get logged windows user in NodeJS


问:
ShellCheck warning: "Remove surrounding $() to avoid executing output. [SC2091]"
I have the following set of commands in my script:

```<code>message="Secure copying file $remoteHost"
backupLogOutput "Info $message"
$(scp  "$file" "$remoteUser"@"$remoteHost":"$remotePath")  >> "$BACKUPLOG"
backupErrorHandler "$?" "$message"
</code>```

ShellCheck is giving me the warning on the scp line (3):

Remove surrounding $() to avoid executing output. [SC2091]

The script works. I do want to execute the output. Shall I ignore this warning or should the scp line be written in a different way?

答:
I don't think you actually do want to execute what scp outputs - it looks more like you simply want to copy a file:

```<code>scp  "$file" "$remoteUser"@"$remoteHost":"$remotePath"  >> "$BACKUPLOG"
</code>```

Body:
I have the following set of commands in my script:

message="Secure copying file $remoteHost"
backupLogOutput "Info $message"
$(scp  "$file" "$remoteUser"@"$remoteHost":"$remotePath")  >> "$BACKUPLOG"
backupErrorHandler "$?" "$message"

ShellCheck is giving me the warning on the scp line (3):

Remove surrounding $() to avoid executing output. [SC2091]

The script works. I do want to execute the output. Shall I ignore this warning or should the scp line be written in a different way?

Body:
I don't think you actually do want to execute what scp outputs - it looks more like you simply want to copy a file:

scp  "$file" "$remoteUser"@"$remoteHost":"$remotePath"  >> "$BACKUPLOG"


问:
How to properly overload the << operator for an ostream?
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2
) however I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

```<code>namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}
</code>```

And the "implementation":

```<code>using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}
</code>```

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream&
  Math::Matrix::operator<<(std::ostream&,
  const Math::Matrix&)' must take
  exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)

答:
Just telling you about one other possibility: I like using friend definitions for that:

```<code>namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
            [...]
        }
    };
}
</code>```

The function will be automatically targeted into the surrounding namespace Math (even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>.

OwnerDisplayName: Matthias van der Vlies

Body:
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2
) however I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}

And the "implementation":

using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream&
  Math::Matrix::operator<<(std::ostream&,
  const Math::Matrix&)' must take
  exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)

LastEditorDisplayName: Mehrdad Afshari

Body:
Just telling you about one other possibility: I like using friend definitions for that:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
            [...]
        }
    };
}

The function will be automatically targeted into the surrounding namespace Math (even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>.

OwnerDisplayName: litb


问:
operator.setitem problem in python 3
I have a problem when using operator.setitem in python 3.

When I use the code below and run it in python 3.1.

```<code>people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print (p_dict)

>>> {}
</code>```

That just prints out a empty dictionary {}.

But I use the same code to run in python 2.6.
It prints out {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1} .
This is the result I want.

So, can anyone tell me what's the problem when I run this code in python 3?
Thanks in advance.

答:
The problem is that the map() is never 'executed'. In Python 3, map just returns an iterator - the individual elements are only computed when they are needed. To work around that, you might write

```<code>list(map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1]))
</code>```

However, I agree with everybody else that you shouldn't be using map in the first place - as you don't really need to result of the map application.

Title: operator.setitem problem in python 3

Body:
I have a problem when using operator.setitem in python 3.

When I use the code below and run it in python 3.1.

people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print (p_dict)

>>> {}

That just prints out a empty dictionary {}.

But I use the same code to run in python 2.6.
It prints out {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1} .
This is the result I want.

So, can anyone tell me what's the problem when I run this code in python 3?
Thanks in advance.

Body:
The problem is that the map() is never 'executed'. In Python 3, map just returns an iterator - the individual elements are only computed when they are needed. To work around that, you might write

list(map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1]))

However, I agree with everybody else that you shouldn't be using map in the first place - as you don't really need to result of the map application.


问:
Find elements in group by result use SQL
I have a table contain event log, schema:

```<code>userid, event, timestamp
</code>```

I want group by userid and find that user have specific event

ex.

```<code>userid, events
A, "open, click, remove, restart"
</code>```

so I want make group by result as a string / array

is there any way can do this?

thanks!

答:
Below is for BigQuery Standard SQL

as an example - assuming you want to get list of all ordered events of users who have remove event:

```<code>#standardSQL
SELECT userid,
  STRING_AGG(event ORDER BY ts) AS events
FROM `project.dataset.yourtable`
GROUP BY userid
HAVING REGEXP_CONTAINS(LOWER(events), r'\bremove\b')
</code>```

You can test / play with above using dummy data as below

```<code>#standardSQL
WITH `project.dataset.yourtable` AS (
  SELECT 'A' userid, 'open' event, 1 ts UNION ALL
  SELECT 'A', 'click', 2 UNION ALL
  SELECT 'A', 'remove', 3 UNION ALL
  SELECT 'A', 'restart', 4 UNION ALL
  SELECT 'B', 'open', 1 UNION ALL
  SELECT 'B', 'click', 2
)
SELECT userid,
  STRING_AGG(event ORDER BY ts) AS events
FROM `project.dataset.yourtable`
GROUP BY userid
HAVING REGEXP_CONTAINS(LOWER(events), r'\bremove\b')
</code>```

with result as below (user B is not presented because no remove even present for this user)

```<code>userid  events
A       open,click,remove,restart
</code>```

Body:
I have a table contain event log, schema:

userid, event, timestamp

I want group by userid and find that user have specific event

ex.

userid, events
A, "open, click, remove, restart"

so I want make group by result as a string / array

is there any way can do this?

thanks!

Body:
Below is for BigQuery Standard SQL

as an example - assuming you want to get list of all ordered events of users who have remove event:

#standardSQL
SELECT userid,
  STRING_AGG(event ORDER BY ts) AS events
FROM `project.dataset.yourtable`
GROUP BY userid
HAVING REGEXP_CONTAINS(LOWER(events), r'\bremove\b')

You can test / play with above using dummy data as below

#standardSQL
WITH `project.dataset.yourtable` AS (
  SELECT 'A' userid, 'open' event, 1 ts UNION ALL
  SELECT 'A', 'click', 2 UNION ALL
  SELECT 'A', 'remove', 3 UNION ALL
  SELECT 'A', 'restart', 4 UNION ALL
  SELECT 'B', 'open', 1 UNION ALL
  SELECT 'B', 'click', 2
)
SELECT userid,
  STRING_AGG(event ORDER BY ts) AS events
FROM `project.dataset.yourtable`
GROUP BY userid
HAVING REGEXP_CONTAINS(LOWER(events), r'\bremove\b')

with result as below (user B is not presented because no remove even present for this user)

userid  events
A       open,click,remove,restart


问:
When defining a prototype of an overloaded C++ function template, is it legal to use its name to refer to previous definitions?
Let's say we want to overload a function template f, but only if a similar overload is not declared yet:

```<code>template<typename T>
void f(T); // main prototype

struct A {};
struct B {};

//we want to declare B f(A), but only if something like A f(A) hasn't been declared
//we can try to check the type of expression f(A) before defining it
//and disable overload via enable_if
template<typename T = void>   //it has to be a template to use enable_if
std::enable_if_t<std::is_same_v<void, decltype(T(), (f)(A{}))>, B> f(A);
// decltype expression depends on T, but always evaluates to the type of (f)(A{})
// parenthesis are used to disable ADL, so only preceding definitions are visible
</code>```

The code is accepted by Clang, kind of works on GCC (See
 https://godbolt.org/g/ZGfbDW), and causes compiler error 'recursive type or function dependency context too complex' on Visual C++ 15.5.

My question is: is this a legal declaration according to the C++ standard or does it involve undefined behavior?

答:
I believe this is a legal declaration based simply on there not really being any reason for it to not be.

Couple things worth pointing out. First, we have two uses of f here, and they are different:

```<code>template<typename T = void>
std::enable_if_t<std::is_same_v<void, decltype(T(), (f)(A{}))>, B> f(A);
//                                                  ^^^           ^^^
//                                                   #1            #2
</code>```

We are declaring the name f in #2, but it is not in scope for its usage in #1† - its point of declaration is after the complete declarator, which includes that enable_if_t block. So there's no recursion here. If VS has a problem with it, I suspect it might be related to their general issues around name lookup in templates.

Second, these aren't functionally equivalent templates - the main prototype takes an argument whose type is the template parameter, and this one takes an A. The point of functional equivalency is to match up declarations to definitions in a way that doesn't require token-by-token copies - but our two f function templates in this example are totally different.

I don't see a reason for this to be ill-formed. Eyebrow-raising, yes. Ill-formed, no.

†This leads to a fairly common error when trying to declare a recursive function template whose return type depends on itself. e.g.:

```<code>template <size_t V>
using size_ = std::integral_constant<size_t, V>;

constexpr size_<0> count() { return {}; }

template <typename T, typename... Ts>
constexpr auto count(T, Ts... ts)
    -> size_<decltype(count(ts...))::value + 1> { return {}; }

int main() {
    static_assert(count() == 0);      // ok
    static_assert(count(1) == 1);     // ok
    static_assert(count(1, 2) == 2);  // error: no matching function to call
}
</code>```

Body:
Let's say we want to overload a function template f, but only if a similar overload is not declared yet:

template<typename T>
void f(T); // main prototype

struct A {};
struct B {};

//we want to declare B f(A), but only if something like A f(A) hasn't been declared
//we can try to check the type of expression f(A) before defining it
//and disable overload via enable_if
template<typename T = void>   //it has to be a template to use enable_if
std::enable_if_t<std::is_same_v<void, decltype(T(), (f)(A{}))>, B> f(A);
// decltype expression depends on T, but always evaluates to the type of (f)(A{})
// parenthesis are used to disable ADL, so only preceding definitions are visible

The code is accepted by Clang, kind of works on GCC (See
 https://godbolt.org/g/ZGfbDW), and causes compiler error 'recursive type or function dependency context too complex' on Visual C++ 15.5.

My question is: is this a legal declaration according to the C++ standard or does it involve undefined behavior?

Body:
I believe this is a legal declaration based simply on there not really being any reason for it to not be.

Couple things worth pointing out. First, we have two uses of f here, and they are different:

template<typename T = void>
std::enable_if_t<std::is_same_v<void, decltype(T(), (f)(A{}))>, B> f(A);
//                                                  ^^^           ^^^
//                                                   #1            #2

We are declaring the name f in #2, but it is not in scope for its usage in #1† - its point of declaration is after the complete declarator, which includes that enable_if_t block. So there's no recursion here. If VS has a problem with it, I suspect it might be related to their general issues around name lookup in templates.

Second, these aren't functionally equivalent templates - the main prototype takes an argument whose type is the template parameter, and this one takes an A. The point of functional equivalency is to match up declarations to definitions in a way that doesn't require token-by-token copies - but our two f function templates in this example are totally different.

I don't see a reason for this to be ill-formed. Eyebrow-raising, yes. Ill-formed, no.

†This leads to a fairly common error when trying to declare a recursive function template whose return type depends on itself. e.g.:

template <size_t V>
using size_ = std::integral_constant<size_t, V>;

constexpr size_<0> count() { return {}; }

template <typename T, typename... Ts>
constexpr auto count(T, Ts... ts)
    -> size_<decltype(count(ts...))::value + 1> { return {}; }

int main() {
    static_assert(count() == 0);      // ok
    static_assert(count(1) == 1);     // ok
    static_assert(count(1, 2) == 2);  // error: no matching function to call
}


问:
Convert JS Post Ajax to AngularJS Post Factory

I am trying to convert an Ajax call with WSSE authentication to an AngularJS factory.
The method is Post.

The intended use of this is to access the Adobe Analytics Rest API and return data to be converted to JSON and then visualised with d3.js.

I am not familiar with the properties that can be used in an AngularJS $http post call and so not sure what is the correct way to do the WSSE auth, dataType, callback etc.

This is the original ajax code which came from a public github repo:

```<code>(function($) {
  window.MarketingCloud = {
    env:   {},
    wsse:  new Wsse(),

    /** Make the api request */
    /* callback should follow standard jQuery request format:
     *    function callback(data)
     */
    makeRequest: function (username, secret, method, params, endpoint, callback)
    {
        var headers = MarketingCloud.wsse.generateAuth(username, secret);
        var url = 'https://'+endpoint+'/admin/1.4/rest/?method='+method;
        $.ajax(url, {
            type:'POST',
            data: params,
            complete: callback,
            dataType: "text",
            headers: {
                'X-WSSE': headers['X-WSSE']
            }
        });
    }
  };
})(jQuery);
</code>```

This is the current way the code is being used with pure JS:

```<code>MarketingCloud.makeRequest(username, secret, method, params, endpoint, function(response) {
        data = JSON.parse(response.responseText);
});
</code>```

I want to convert this to a factory and a controller respectively.

This is what I have done for the factory so far:

```<code>app.factory('mainFactory', ['$http', function($http) {
  var wsse = new Wsse ();
  return function(username, secret, method, params, endpoint) {
    return $http({
      method: 'POST',
      url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
      data: params,
      headers: {
        'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
      },
      dataType: 'text',
    });
  };
}]);
</code>```

And this is what I have for the controller:

```<code>app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
  mainFactory.success(function(data) {
    $scope.data = data;
  });
}]);
</code>```

Currently I get an error saying mainFactory.success is not a function which I assume is because the factory isn't working yet.

答:
I have resolved this question myself. The parameters I was passing to the first function in the factory were globally defined already and therefore getting over-written.
The first function is not required anyway.

Here is the factory code:

```<code>app.factory('mainFactory', ['$http', function($http) {
  var wsse = new Wsse ();
  return {
    getAnalytics : function (){
      $http({
          method: 'POST',
          url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
          data: params,
          headers: {
            'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
          }
        })
        .success(function(data) {
          return data;
        })
        .error(function(err) {
          return err;
        });
    }
  };
}]);
</code>```

And here is the controller code:

```<code>app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
  $scope.title = "Inn Site";
  $scope.data = mainFactory.getAnalytics();
}]);
</code>```

Body:
I am trying to convert an Ajax call with WSSE authentication to an AngularJS factory.
The method is Post.

The intended use of this is to access the Adobe Analytics Rest API and return data to be converted to JSON and then visualised with d3.js.

I am not familiar with the properties that can be used in an AngularJS $http post call and so not sure what is the correct way to do the WSSE auth, dataType, callback etc.

This is the original ajax code which came from a public github repo:

(function($) {
  window.MarketingCloud = {
    env:   {},
    wsse:  new Wsse(),

    /** Make the api request */
    /* callback should follow standard jQuery request format:
     *    function callback(data)
     */
    makeRequest: function (username, secret, method, params, endpoint, callback)
    {
        var headers = MarketingCloud.wsse.generateAuth(username, secret);
        var url = 'https://'+endpoint+'/admin/1.4/rest/?method='+method;
        $.ajax(url, {
            type:'POST',
            data: params,
            complete: callback,
            dataType: "text",
            headers: {
                'X-WSSE': headers['X-WSSE']
            }
        });
    }
  };
})(jQuery);

This is the current way the code is being used with pure JS:

MarketingCloud.makeRequest(username, secret, method, params, endpoint, function(response) {
        data = JSON.parse(response.responseText);
});

I want to convert this to a factory and a controller respectively.

This is what I have done for the factory so far:

app.factory('mainFactory', ['$http', function($http) {
  var wsse = new Wsse ();
  return function(username, secret, method, params, endpoint) {
    return $http({
      method: 'POST',
      url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
      data: params,
      headers: {
        'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
      },
      dataType: 'text',
    });
  };
}]);

And this is what I have for the controller:

app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
  mainFactory.success(function(data) {
    $scope.data = data;
  });
}]);

Currently I get an error saying mainFactory.success is not a function which I assume is because the factory isn't working yet.

Body:
I have resolved this question myself. The parameters I was passing to the first function in the factory were globally defined already and therefore getting over-written.
The first function is not required anyway.

Here is the factory code:

app.factory('mainFactory', ['$http', function($http) {
  var wsse = new Wsse ();
  return {
    getAnalytics : function (){
      $http({
          method: 'POST',
          url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
          data: params,
          headers: {
            'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
          }
        })
        .success(function(data) {
          return data;
        })
        .error(function(err) {
          return err;
        });
    }
  };
}]);

And here is the controller code:

app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
  $scope.title = "Inn Site";
  $scope.data = mainFactory.getAnalytics();
}]);


问:
Selenium: click on

I have the following html code and I want to click on the second option "Plan b".

```<code><ul class="clearfix all">
<li data-content="a" data-tab-target="tab1" class="active"><span>Plan a</span</li>
<li data-content="b" data-tab-target="tab2" class=""><span>Plan b</span></li>
<li data-content="c" data-tab-target="tab3" class=""><span>Plan c</span></li>/ul>
</code>```

I tried to do somthing like this:

1.

```<code>@FindBy(css = "li:nth-child(2)")
WebElement sparpreis;
sparpreis.click();
</code>```

2.

```<code>@FindBy(xpath = "//*[@class='clearfix all']/ul/li[2]")
WebElement sparpreis;
sparpreis.click();
</code>```

My error messages:

org.openqa.selenium.ElementNotVisibleException: element not visible

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class='clearfix all']/ul/li[2]"}

Perhaphs I should activate the second "class"?

答:
As per the HTML you have shared, to click on the second option Plan b you can use either of the following code block :

css

```<code>@FindBy(css = "ul.clearfix.all li[data-content=b] > span")
WebElement sparpreis;
sparpreis.click();
</code>```

xpath

```<code>@FindBy(xpath = "//ul[@class='clearfix all']//li[@data-content='b']/span")
WebElement sparpreis;
sparpreis.click();
</code>```

Title: Selenium: click on <li>

Body:
I have the following html code and I want to click on the second option "Plan b".

Plan a</span

Plan b

Plan c
/ul>

I tried to do somthing like this:

1.

@FindBy(css = "li:nth-child(2)")
WebElement sparpreis;
sparpreis.click();

2.

@FindBy(xpath = "//*[@class='clearfix all']/ul/li[2]")
WebElement sparpreis;
sparpreis.click();

My error messages:

org.openqa.selenium.ElementNotVisibleException: element not visible

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class='clearfix all']/ul/li[2]"}

Perhaphs I should activate the second "class"?

Body:
As per the HTML you have shared, to click on the second option Plan b you can use either of the following code block :

css

@FindBy(css = "ul.clearfix.all li[data-content=b] > span")
WebElement sparpreis;
sparpreis.click();

xpath

@FindBy(xpath = "//ul[@class='clearfix all']//li[@data-content='b']/span")
WebElement sparpreis;
sparpreis.click();


问:
Looper or while in a thread?
I'm trying to understand the Looper...

This time i'm getting a little bit confused, because I've only used (until now) the while(true) condition to maintain the thread in an infinite loop.

I just want to know if it is better to use the Looper or the while(true) condition.

I've searched a possible answer to my question in internet and I was quite disappointed in finding codes that use Looper and while(true) together.

Probably I didn't get the point of using the Looper but, you know, we are here to learn... isn't it?

答:
Looper is a mechanism that keeps thread open to process Messages that are sent to it via Handler. In that sense, they are similar to while(true) in that the Thread stays open forever (or in this case until you explicitly tell it to close).  However, unlike while(true), you can send the Messages to it from another thread.  Every time you create a Handler, it binds itself to the Looper thread that it was created in. Then, every time you post a message to that Handler, it processes that message on the thread in which it was created.

The most common, well-known Looper thread in Android is the main UI thread. This thread is always running. It runs code that are posted to it. Most commonly drawing operations, but if you take a view and call View#post, it will run the code in the next draw cycle. This is because all View objects have a Handler that was built on the main UI Looper thread.

The UI Looper can actually be referenced to Looper.getMainLooper() method, and you can create a Handler that posts messages to this thread like so: new Handler(Looper.getMainLooper());.

Though if you need, you could create your own Looper thread that acts as a parallel thread to the UI thread. You can't do drawing operations on it, but you could use it as a worker thread for other operations. That way you don't have the overhead of creating a new thread every time you need to do something intensive.

Title: Looper or while in a thread?