问:
ReactJS - Griddle v1.0 get current filtered data
Im trying to figure out how to get the current filtered items from the Griddle component.

I found the following function in the source-code:

```<code>var filteredDataSelector = exports.filteredDataSelector = (0, _reselect.createSelector)(dataSelector, filterSelector, function (data, filter){
        return data.filter(function (row) {
        return Object.keys(row.toJSON()).some(function (key) {
        return row.get(key) &&
        row.get(key).toString().toLowerCase().indexOf(filter.toLowerCase()) > -1;
      });
   });
});
</code>```

But how would I use the filteredDataSelector in my react-component? I would like to get the filtered items when clicking a button export to excel.

I found this example on how to interact with each item (to render hyperlink instead of just plain text) in the list which I think should work in a similair way to what I want to achieve:
https://github.com/GriddleGriddle/Griddle/issues/586

I dont really understand how this works with redux and the connect function, but example above worked just fine.

Not sure if I have to use redux/connect in a similair way to get the filtered list of items?

Griddle-documentation:
https://griddlegriddle.github.io/Griddle/docs/

答:
Found a way to solve this, even though Im pretty sure there is a better solution, then please let me know.

First I overrided the TableBody griddle-component and also made a small fix to get it work properly in internet explorer 11, ie11 (list._tail.array). I store the currently filtered datarow indexes in this.rowIds.

```<code>                TableBody: (_ref) => {
                    var rowIds = _ref.rowIds,
                        Row = _ref.Row,
                        style = _ref.style,
                        className = _ref.className;

                    this.rowIds = rowIds._tail.array;

                    var list = rowIds && rowIds.map(function (r) {
                        return React.createElement(Row, { key: r, griddleKey: r });
                    });

                    //ie11 felsökningsfix:
                    //console.log(list);
                    //console.log(list._tail.array);

                    return React.createElement(
                        'tbody',
                        { style: style, className: className }, list._tail.array //fix för ie11! orginalkoden skickade bara in list, men krachade då i ie11.
                    );
                }
</code>```

Using the rowDataSelector as explained in this article: https://griddlegriddle.github.io/Griddle/examples/getDataFromRowIntoCell/ and then using the rowIds field to get the selected data, only at the first row-index.

```<code>    this.rowDataSelector = (state, { griddleKey }) => {
        if (griddleKey === this.rowIds[0]) {
            this.selectedData = this.rowIds.map(function (id) {
                return state.get('data')
                    .find(rowMap => rowMap.get('griddleKey') === id)
                    .toJSON();
            });
        }
        return state
            .get('data')
            .find(rowMap => rowMap.get('griddleKey') === griddleKey)
            .toJSON();
    }
</code>```

Using it:

```<code>exportToExcel() {
if (this.selectedData.length != 0) {
    var results = this.selectedData;
    Api.exportToExcelPre('/product/exporttoexcelpre/', results).then(result => {
        window.location = Constants.API_URL + '/product/exporttoexcel/';
    });
}
}
</code>```

Final code:

```<code>import { connect } from 'react-redux';

export default class ProductList extends Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        loading: true
    };
}

updateProductList() {
    Api.getProducts().then(products => {
        this.setState({ data: products, loading: false });
    });
}

componentDidMount() {
    this.updateProductList();
}

componentWillReceiveProps(props) {
    if (props.refreshProductList) {
        this.updateProductList();
    }
}

render() {
    if (this.state.loading) {
        return (
            <div>Läser in produkter...</div>
        );
    }
    return (
        <div>
            <ProductResultList products={this.state.data} />
        </div>
    );
}
}
class Filter extends Component {
constructor(props) {
    super(props);
}

onChange(e) {
    this.props.setFilter(e.target.value);
}

render() {
    var imgExcelLogo = <img src={PathHelper.getCurrentPathAppend("img/excel_logo.png")} className="export-symbol" onClick={this.props.export} style={{ float: "right" }} />;
    return (
        <div>
            <div className="row">
                <div className="form-group col-md-6 label-floating is-empty">
                    <label class="control-label" htmlFor="search-product">Sök på valfritt fält, exempelvis produktnamn/produktkategori osv.</label>
                    <input className="form-control" type="text" name="search-product" id="search-product" onChange={this.onChange.bind(this)} />
                </div>
                <div className="col-md-6 form-group" style={{ minHeight: "35px" }}>
                    {imgExcelLogo}
                </div>
            </div>
        </div>
    );
}
}

export class ProductResultList extends Component {
constructor(props) {
    super(props);
    this.rowIds = [];
    this.selectedData = [];
    this.styleConfig = {
        classNames: {
            Row: 'row-class',
            Cell: "col-md-2",
            TableHeadingCell: "col-md-2 cursor",
            Table: "table table-striped table-hover",
            Filter: "form-control"
        },
    }
    this.sortMethod = {
        data: this.props.products,
        column: "generatedId"
    }
    this.settings = {
        // The height of the table
        tableHeight: 100,
        // The width of the table
        tableWidth: null,
        // The minimum row height
        rowHeight: 10,
        // The minimum column width
        defaultColumnWidth: null,
        // Whether or not the header should be fixed
        fixedHeader: false,
        // Disable pointer events while scrolling to improve performance
        disablePointerEvents: false
    };
    this.pageProps = {
        currentPage: 1,
        pageSize: 1000
    }

    this.rowDataSelector = (state, { griddleKey }) => {
        if (griddleKey === 0) {
            this.selectedData = this.rowIds.map(function (id) {
                return state.get('data')
                    .find(rowMap => rowMap.get('griddleKey') === id)
                    .toJSON();
            });
        }
        return state
            .get('data')
            .find(rowMap => rowMap.get('griddleKey') === griddleKey)
            .toJSON();
    }
    this.exportToExcel = this.exportToExcel.bind(this);
    this.enhancedWithRowData = connect((state, props) => {
        return {
            // rowData will be available into MyCustomComponent
            rowData: this.rowDataSelector(state, props)
        };
    });
}

exportToExcel() {
    if (this.selectedData.length != 0) {
        var results = this.selectedData;
        Api.exportToExcelPre('/product/exporttoexcelpre/', results).then(result => {
            window.location = Constants.API_URL + '/product/exporttoexcel/';
        });
    }
}

LinkComponent({ value, griddleKey, rowData }) {
    return (
        <Link to={PathHelper.getCurrentPath() + "product/edit/" + rowData.id}>{rowData.name}</Link>
    );
}

render() {
    return (
        <Griddle
            ref='Griddle'
            styleConfig={this.styleConfig}
            data={this.props.products}
            pageProperties={this.pageProps}
            sortProperties={this.sortProperties}
            components={{
                Layout: ({ Table, Filter }) => <div><Filter /><div className="table-responsive"><Table /></div></div>,
                Settings: () => <span />,
                SettingsContainer: () => <span />,
                SettingsToggle: () => <span />,
                PageDropdown: () => <span />,
                NextButton: () => <span />,
                Filter: (filter) => {
                    return <Filter products={this.props.products} export={this.exportToExcel} setFilter={filter.setFilter} />
                },
                TableBody: (_ref) => {
                    var rowIds = _ref.rowIds,
                        Row = _ref.Row,
                        style = _ref.style,
                        className = _ref.className;

                    this.rowIds = rowIds._tail.array;

                    var list = rowIds && rowIds.map(function (r) {
                        return React.createElement(Row, { key: r, griddleKey: r });
                    });

                    //ie11 felsökningsfix:
                    //console.log(list);
                    //console.log(list._tail.array);

                    return React.createElement(
                        'tbody',
                        { style: style, className: className }, list._tail.array //fix för ie11! orginalkoden skickade bara in list, men krachade då i ie11.
                    );
                }
            }}
            plugins={[plugins.LocalPlugin]}>
            <RowDefinition>
                <ColumnDefinition id="generatedId" title="Produkt-Id" />
                <ColumnDefinition id="name" title="Namn" customComponent={this.enhancedWithRowData(this.LinkComponent)} />
                <ColumnDefinition id="productCategoryName" title="Produktkategori" />
                <ColumnDefinition id="productTypeName" title="Produkttyp" />
                <ColumnDefinition id="supplierName" title="Leverantör" />
                <ColumnDefinition id="toBeInspectedString" title="Besiktigas" />
            </RowDefinition>
        </Griddle>
    );
};
}
</code>```

Body:
Im trying to figure out how to get the current filtered items from the Griddle component.

I found the following function in the source-code:

var filteredDataSelector = exports.filteredDataSelector = (0, _reselect.createSelector)(dataSelector, filterSelector, function (data, filter){
        return data.filter(function (row) {
        return Object.keys(row.toJSON()).some(function (key) {
        return row.get(key) &&
        row.get(key).toString().toLowerCase().indexOf(filter.toLowerCase()) > -1;
      });
   });
});

But how would I use the filteredDataSelector in my react-component? I would like to get the filtered items when clicking a button export to excel.

I found this example on how to interact with each item (to render hyperlink instead of just plain text) in the list which I think should work in a similair way to what I want to achieve:
https://github.com/GriddleGriddle/Griddle/issues/586

I dont really understand how this works with redux and the connect function, but example above worked just fine.

Not sure if I have to use redux/connect in a similair way to get the filtered list of items?

Griddle-documentation:
https://griddlegriddle.github.io/Griddle/docs/

Body:
Found a way to solve this, even though Im pretty sure there is a better solution, then please let me know.

First I overrided the TableBody griddle-component and also made a small fix to get it work properly in internet explorer 11, ie11 (list._tail.array). I store the currently filtered datarow indexes in this.rowIds.

                TableBody: (_ref) => {
                    var rowIds = _ref.rowIds,
                        Row = _ref.Row,
                        style = _ref.style,
                        className = _ref.className;

                    this.rowIds = rowIds._tail.array;

                    var list = rowIds && rowIds.map(function (r) {
                        return React.createElement(Row, { key: r, griddleKey: r });
                    });

                    //ie11 felsökningsfix:
                    //console.log(list);
                    //console.log(list._tail.array);

                    return React.createElement(
                        'tbody',
                        { style: style, className: className }, list._tail.array //fix för ie11! orginalkoden skickade bara in list, men krachade då i ie11.
                    );
                }

Using the rowDataSelector as explained in this article: https://griddlegriddle.github.io/Griddle/examples/getDataFromRowIntoCell/ and then using the rowIds field to get the selected data, only at the first row-index.

    this.rowDataSelector = (state, { griddleKey }) => {
        if (griddleKey === this.rowIds[0]) {
            this.selectedData = this.rowIds.map(function (id) {
                return state.get('data')
                    .find(rowMap => rowMap.get('griddleKey') === id)
                    .toJSON();
            });
        }
        return state
            .get('data')
            .find(rowMap => rowMap.get('griddleKey') === griddleKey)
            .toJSON();
    }

Using it:

exportToExcel() {
if (this.selectedData.length != 0) {
    var results = this.selectedData;
    Api.exportToExcelPre('/product/exporttoexcelpre/', results).then(result => {
        window.location = Constants.API_URL + '/product/exporttoexcel/';
    });
}
}

Final code:

import { connect } from 'react-redux';

export default class ProductList extends Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        loading: true
    };
}

updateProductList() {
    Api.getProducts().then(products => {
        this.setState({ data: products, loading: false });
    });
}

componentDidMount() {
    this.updateProductList();
}

componentWillReceiveProps(props) {
    if (props.refreshProductList) {
        this.updateProductList();
    }
}

render() {
    if (this.state.loading) {
        return (
            <div>Läser in produkter...</div>
        );
    }
    return (
        <div>
            <ProductResultList products={this.state.data} />
        </div>
    );
}
}
class Filter extends Component {
constructor(props) {
    super(props);
}

onChange(e) {
    this.props.setFilter(e.target.value);
}

render() {
    var imgExcelLogo = <img src={PathHelper.getCurrentPathAppend("img/excel_logo.png")} className="export-symbol" onClick={this.props.export} style={{ float: "right" }} />;
    return (
        <div>
            <div className="row">
                <div className="form-group col-md-6 label-floating is-empty">
                    <label class="control-label" htmlFor="search-product">Sök på valfritt fält, exempelvis produktnamn/produktkategori osv.</label>
                    <input className="form-control" type="text" name="search-product" id="search-product" onChange={this.onChange.bind(this)} />
                </div>
                <div className="col-md-6 form-group" style={{ minHeight: "35px" }}>
                    {imgExcelLogo}
                </div>
            </div>
        </div>
    );
}
}

export class ProductResultList extends Component {
constructor(props) {
    super(props);
    this.rowIds = [];
    this.selectedData = [];
    this.styleConfig = {
        classNames: {
            Row: 'row-class',
            Cell: "col-md-2",
            TableHeadingCell: "col-md-2 cursor",
            Table: "table table-striped table-hover",
            Filter: "form-control"
        },
    }
    this.sortMethod = {
        data: this.props.products,
        column: "generatedId"
    }
    this.settings = {
        // The height of the table
        tableHeight: 100,
        // The width of the table
        tableWidth: null,
        // The minimum row height
        rowHeight: 10,
        // The minimum column width
        defaultColumnWidth: null,
        // Whether or not the header should be fixed
        fixedHeader: false,
        // Disable pointer events while scrolling to improve performance
        disablePointerEvents: false
    };
    this.pageProps = {
        currentPage: 1,
        pageSize: 1000
    }

    this.rowDataSelector = (state, { griddleKey }) => {
        if (griddleKey === 0) {
            this.selectedData = this.rowIds.map(function (id) {
                return state.get('data')
                    .find(rowMap => rowMap.get('griddleKey') === id)
                    .toJSON();
            });
        }
        return state
            .get('data')
            .find(rowMap => rowMap.get('griddleKey') === griddleKey)
            .toJSON();
    }
    this.exportToExcel = this.exportToExcel.bind(this);
    this.enhancedWithRowData = connect((state, props) => {
        return {
            // rowData will be available into MyCustomComponent
            rowData: this.rowDataSelector(state, props)
        };
    });
}

exportToExcel() {
    if (this.selectedData.length != 0) {
        var results = this.selectedData;
        Api.exportToExcelPre('/product/exporttoexcelpre/', results).then(result => {
            window.location = Constants.API_URL + '/product/exporttoexcel/';
        });
    }
}

LinkComponent({ value, griddleKey, rowData }) {
    return (
        <Link to={PathHelper.getCurrentPath() + "product/edit/" + rowData.id}>{rowData.name}</Link>
    );
}

render() {
    return (
        <Griddle
            ref='Griddle'
            styleConfig={this.styleConfig}
            data={this.props.products}
            pageProperties={this.pageProps}
            sortProperties={this.sortProperties}
            components={{
                Layout: ({ Table, Filter }) => <div><Filter /><div className="table-responsive"><Table /></div></div>,
                Settings: () => <span />,
                SettingsContainer: () => <span />,
                SettingsToggle: () => <span />,
                PageDropdown: () => <span />,
                NextButton: () => <span />,
                Filter: (filter) => {
                    return <Filter products={this.props.products} export={this.exportToExcel} setFilter={filter.setFilter} />
                },
                TableBody: (_ref) => {
                    var rowIds = _ref.rowIds,
                        Row = _ref.Row,
                        style = _ref.style,
                        className = _ref.className;

                    this.rowIds = rowIds._tail.array;

                    var list = rowIds && rowIds.map(function (r) {
                        return React.createElement(Row, { key: r, griddleKey: r });
                    });

                    //ie11 felsökningsfix:
                    //console.log(list);
                    //console.log(list._tail.array);

                    return React.createElement(
                        'tbody',
                        { style: style, className: className }, list._tail.array //fix för ie11! orginalkoden skickade bara in list, men krachade då i ie11.
                    );
                }
            }}
            plugins={[plugins.LocalPlugin]}>
            <RowDefinition>
                <ColumnDefinition id="generatedId" title="Produkt-Id" />
                <ColumnDefinition id="name" title="Namn" customComponent={this.enhancedWithRowData(this.LinkComponent)} />
                <ColumnDefinition id="productCategoryName" title="Produktkategori" />
                <ColumnDefinition id="productTypeName" title="Produkttyp" />
                <ColumnDefinition id="supplierName" title="Leverantör" />
                <ColumnDefinition id="toBeInspectedString" title="Besiktigas" />
            </RowDefinition>
        </Griddle>
    );
};
}


来源: stackexchange

问:
Hosmer-Lemeshow statistic in R
I have run the Hosmer Lemeshow statistic in R, but I have obtained an p-value of 1. This seems strange to me. I know that a high p-valvalue means that we do not reject the null hypothesis that observed and expected are the same, but is it possible i have an error somewhere?

How do i interpret such p-value?

Below is the code i have used to run the test. I also attach how my model looks like. Response variable is a count variable, while all regressors are continous. I have run a negative binomial model, due to detected overdispersion in my initial poisson model.

```<code>> hosmerlem <- function(y, yhat, g=10)
+     {cutyhat <- cut(yhat, breaks = quantile(yhat, probs=seq(0,1, 1/g)), include.lowest=TRUE)
+     obs <- xtabs(cbind(1 - y, y) ~ cutyhat)
+     expect <- xtabs(cbind(1 - yhat, yhat) ~ cutyhat)
+     chisq <- sum((obs - expect)^2/expect)
+     P <- 1 - pchisq(chisq, g - 2)
+     return(list(chisq=chisq,p.value=P))}
>   hosmerlem(y=TOT.N, yhat=fitted(final.model))
$chisq
[1] -2.529054

$p.value
[1] 1

> final.model <-glm.nb(TOT.N ~ D.PARK + OPEN.L + L.WAT.C + sqrt(L.P.ROAD))
> summary(final.model)

Call:
glm.nb(formula = TOT.N ~ D.PARK + OPEN.L + L.WAT.C + sqrt(L.P.ROAD),
    init.theta = 4.979895131, link = log)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-3.08218  -0.70494  -0.09268   0.55575   1.67860

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)     4.032e+00  3.363e-01  11.989  < 2e-16 ***
D.PARK         -1.154e-04  1.061e-05 -10.878  < 2e-16 ***
OPEN.L         -1.085e-02  3.122e-03  -3.475  0.00051 ***
L.WAT.C         1.597e-01  7.852e-02   2.034  0.04195 *
sqrt(L.P.ROAD)  4.924e-01  3.101e-01   1.588  0.11231
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for Negative Binomial(4.9799) family taken to be 1)

    Null deviance: 197.574  on 51  degrees of freedom
Residual deviance:  51.329  on 47  degrees of freedom
AIC: 383.54

Number of Fisher Scoring iterations: 1

              Theta:  4.98
          Std. Err.:  1.22

 2 x log-likelihood:  -371.542
</code>```

答:
As correctly pointed out by @BenBolker, Hosmer-Lemeshow is a test for logistic regression, not for a negative binomial generalized linear model.

If we consider to apply the test to a logistic regression,
the inputs of the function hosmerlem (a copy of the hoslem.test function in the package ResourceSelection) should be:

- y = a numeric vector of observations, binary (0/1)

- yhat = expected values (probabilities)

Here is an illustrative example that shows how to get the correct inputs:

```<code>set.seed(123)
n <- 500
x <- rnorm(n)
y <- rbinom(n, 1, plogis(0.1 + 0.5*x))
logmod <- glm(y ~ x, family=binomial)

# Important: use the type="response" option
yhat <- predict(logmod, type="response")
hosmerlem(y, yhat)

########
$chisq
[1] 4.522719

$p.value
[1] 0.8071559
</code>```

The same result is given by the function hoslem.test:

```<code>library(ResourceSelection)
hoslem.test(y, yhat)

########
Hosmer and Lemeshow goodness of fit (GOF) test

data:  y, yhat
X-squared = 4.5227, df = 8, p-value = 0.8072
</code>```

ContentLicense: CC BY-SA 3.0

Title: Hosmer-Lemeshow statistic in R

Body:
I have run the Hosmer Lemeshow statistic in R, but I have obtained an p-value of 1. This seems strange to me. I know that a high p-valvalue means that we do not reject the null hypothesis that observed and expected are the same, but is it possible i have an error somewhere?

How do i interpret such p-value?

Below is the code i have used to run the test. I also attach how my model looks like. Response variable is a count variable, while all regressors are continous. I have run a negative binomial model, due to detected overdispersion in my initial poisson model.

> hosmerlem <- function(y, yhat, g=10)
+     {cutyhat <- cut(yhat, breaks = quantile(yhat, probs=seq(0,1, 1/g)), include.lowest=TRUE)
+     obs <- xtabs(cbind(1 - y, y) ~ cutyhat)
+     expect <- xtabs(cbind(1 - yhat, yhat) ~ cutyhat)
+     chisq <- sum((obs - expect)^2/expect)
+     P <- 1 - pchisq(chisq, g - 2)
+     return(list(chisq=chisq,p.value=P))}
>   hosmerlem(y=TOT.N, yhat=fitted(final.model))
$chisq
[1] -2.529054

$p.value
[1] 1

> final.model <-glm.nb(TOT.N ~ D.PARK + OPEN.L + L.WAT.C + sqrt(L.P.ROAD))
> summary(final.model)

Call:
glm.nb(formula = TOT.N ~ D.PARK + OPEN.L + L.WAT.C + sqrt(L.P.ROAD),
    init.theta = 4.979895131, link = log)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-3.08218  -0.70494  -0.09268   0.55575   1.67860

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)     4.032e+00  3.363e-01  11.989  < 2e-16 ***
D.PARK         -1.154e-04  1.061e-05 -10.878  < 2e-16 ***
OPEN.L         -1.085e-02  3.122e-03  -3.475  0.00051 ***
L.WAT.C         1.597e-01  7.852e-02   2.034  0.04195 *
sqrt(L.P.ROAD)  4.924e-01  3.101e-01   1.588  0.11231
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for Negative Binomial(4.9799) family taken to be 1)

    Null deviance: 197.574  on 51  degrees of freedom
Residual deviance:  51.329  on 47  degrees of freedom
AIC: 383.54

Number of Fisher Scoring iterations: 1

              Theta:  4.98
          Std. Err.:  1.22

 2 x log-likelihood:  -371.542

Body:
As correctly pointed out by @BenBolker, Hosmer-Lemeshow is a test for logistic regression, not for a negative binomial generalized linear model.

If we consider to apply the test to a logistic regression,
the inputs of the function hosmerlem (a copy of the hoslem.test function in the package ResourceSelection) should be:

- y = a numeric vector of observations, binary (0/1)

- yhat = expected values (probabilities)

Here is an illustrative example that shows how to get the correct inputs:

set.seed(123)
n <- 500
x <- rnorm(n)
y <- rbinom(n, 1, plogis(0.1 + 0.5*x))
logmod <- glm(y ~ x, family=binomial)

# Important: use the type="response" option
yhat <- predict(logmod, type="response")
hosmerlem(y, yhat)

########
$chisq
[1] 4.522719

$p.value
[1] 0.8071559

The same result is given by the function hoslem.test:

library(ResourceSelection)
hoslem.test(y, yhat)

########
Hosmer and Lemeshow goodness of fit (GOF) test

data:  y, yhat
X-squared = 4.5227, df = 8, p-value = 0.8072


问:
C# How to convert irregular date and time String into DateTime?
I have a program which converts a irregular date and time string into a system DateTime.

However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.

There are only 2 types of date time strings that the program needs to convert:

```<code> Thu Dec  9 05:12:42 2010
 Mon Dec 13 06:45:58 2010
</code>```

Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.

May someone please advise on the codes? Thanks!

The codes:

```<code>        String rb = re.Replace("  ", " 0");

        DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);

        Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
</code>```

答:
This is sample code which you can try:</p>

```<code>        var str = "Thu Dec  9 06:45:58 2010";
        if (str.IndexOf("  ") > -1)
        {
            str = str.Replace("  ", " ");
            DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null);
        }
        else
        {
            DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null);
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a program which converts a irregular date and time string into a system DateTime.

However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.

There are only 2 types of date time strings that the program needs to convert:

 Thu Dec  9 05:12:42 2010
 Mon Dec 13 06:45:58 2010

Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.

May someone please advise on the codes? Thanks!

The codes:

        String rb = re.Replace("  ", " 0");

        DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);

        Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));

Body:
This is sample code which you can try:

        var str = "Thu Dec  9 06:45:58 2010";
        if (str.IndexOf("  ") > -1)
        {
            str = str.Replace("  ", " ");
            DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null);
        }
        else
        {
            DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null);
        }


问:
Why app crashes when i set image to ImageView and run it on android 7.1.1
I am new to Android. I want to know why my app crashes on Android 7.1.1 while setting the image to imageView using explicit intent, as it totally runs fine on other versions of Android. I have tried to understand and solve the issue but unable to do.

Can anyone please help me to understand why this is happening and what's the reason behind this?

Thanks.

This is what it showing :

```<code>eAnimators on 0x97c5ee80 (RippleDrawable) with handle 0x9affd880
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.himanshu.imageviewintent, PID: 5049
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/41 }} to activity {com.example.himanshu.imageviewintent/com.example.himanshu.imageviewintent.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.os.Parcel.readException(Parcel.java:1684)
                      at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                      at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
                      at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1147)
                      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
                      at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
                      at com.example.himanshu.imageviewintent.MainActivity.onActivityResult(MainActivity.java:44)
                      at android.app.Activity.dispatchActivityResult(Activity.java:6932)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
</code>```

And this is my code :

Java :

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

    final static int ImageIntentRequest = 1;

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

    public void setImage(View view) {

        Intent intent = new Intent(Intent.ACTION_PICK);
        File imageViewPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        String path =  imageViewPath.getPath();
        intent.setDataAndType(Uri.parse(path),"image/*");
        startActivityForResult(intent,ImageIntentRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK && requestCode == ImageIntentRequest) {

            InputStream stream;
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            try {
             stream = getContentResolver().openInputStream(data.getData());
                Bitmap bitmap = BitmapFactory.decodeStream(stream);
                imageView.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                Toast.makeText(this,"There is no File Present",Toast.LENGTH_SHORT).show();;
                e.printStackTrace();
            }
        }
    }
}
</code>```

XML :

```<code>   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.himanshu.imageviewintent.MainActivity"
>

<Button
    android:text="@string/set_image_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn_set_image"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="setImage"
    />

<ImageView
    android:src="@mipmap/ic_launcher"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView"
    android:contentDescription="@null"
    android:layout_above="@+id/btn_set_image"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>
</code>```

I found an easy fix for this :

I just replaced,

```<code>Intent.ACTION_PICK by -

Intent intent = Intent(Intent.ACTION_GET_CONTENT);
</code>```

and now the app runs totally fine on old and latest releases of Android.

But still have doubts:

Why ACTION_PICK works on old versions of Android but not on new Releases?
Why ACTION_GET_CONTENT works on all releases?

I will be thankful if someone clarify this?

答:
If you look at the documentation on the changes introduced in Android Nougat, you'll find this -

For apps targeting Android 7.0, the Android framework enforces the
  StrictMode API policy that prohibits exposing file:// URIs outside
  your app. If an intent containing a file URI leaves your app, the app
  fails with a FileUriExposedException exception.

To share files between applications, you should send a content:// URI
  and grant a temporary access permission on the URI. The easiest way to
  grant this permission is by using the FileProvider class.

Here, your intent

```<code> Intent intent = new Intent(Intent.ACTION_PICK);
    File imageViewPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String path =  imageViewPath.getPath();
    intent.setDataAndType(Uri.parse(path),"image/*");
</code>```

is leaving your app to open the Gallery/Camera to pick an image, which results into a crash, as it does not follow Android Nougat Protocol.

To resolve your problem, change the targetApi in your gradle file to 23 (marshmallow) down from 24/25/26 (whichever you may be having as of now).

Or, you can read more on File Sharing and do it in a way that does not violate StrictMode policy.

In case you are short on time, you can use EasyImage library to solve your purpose.

Body:
I am new to Android. I want to know why my app crashes on Android 7.1.1 while setting the image to imageView using explicit intent, as it totally runs fine on other versions of Android. I have tried to understand and solve the issue but unable to do.

Can anyone please help me to understand why this is happening and what's the reason behind this?

Thanks.

This is what it showing :

eAnimators on 0x97c5ee80 (RippleDrawable) with handle 0x9affd880
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.himanshu.imageviewintent, PID: 5049
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/41 }} to activity {com.example.himanshu.imageviewintent/com.example.himanshu.imageviewintent.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.os.Parcel.readException(Parcel.java:1684)
                      at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                      at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
                      at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1147)
                      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
                      at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
                      at com.example.himanshu.imageviewintent.MainActivity.onActivityResult(MainActivity.java:44)
                      at android.app.Activity.dispatchActivityResult(Activity.java:6932)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.

And this is my code :

Java :

public class MainActivity extends Activity {

    final static int ImageIntentRequest = 1;

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

    public void setImage(View view) {

        Intent intent = new Intent(Intent.ACTION_PICK);
        File imageViewPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        String path =  imageViewPath.getPath();
        intent.setDataAndType(Uri.parse(path),"image/*");
        startActivityForResult(intent,ImageIntentRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK && requestCode == ImageIntentRequest) {

            InputStream stream;
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            try {
             stream = getContentResolver().openInputStream(data.getData());
                Bitmap bitmap = BitmapFactory.decodeStream(stream);
                imageView.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                Toast.makeText(this,"There is no File Present",Toast.LENGTH_SHORT).show();;
                e.printStackTrace();
            }
        }
    }
}

XML :

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.himanshu.imageviewintent.MainActivity"
>

<Button
    android:text="@string/set_image_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn_set_image"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="setImage"
    />

<ImageView
    android:src="@mipmap/ic_launcher"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView"
    android:contentDescription="@null"
    android:layout_above="@+id/btn_set_image"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>

I found an easy fix for this :

I just replaced,

Intent.ACTION_PICK by -

Intent intent = Intent(Intent.ACTION_GET_CONTENT);

and now the app runs totally fine on old and latest releases of Android.

But still have doubts:

Why ACTION_PICK works on old versions of Android but not on new Releases?
Why ACTION_GET_CONTENT works on all releases?

I will be thankful if someone clarify this?

Body:
If you look at the documentation on the changes introduced in Android Nougat, you'll find this -

For apps targeting Android 7.0, the Android framework enforces the
  StrictMode API policy that prohibits exposing file:// URIs outside
  your app. If an intent containing a file URI leaves your app, the app
  fails with a FileUriExposedException exception.

To share files between applications, you should send a content:// URI
  and grant a temporary access permission on the URI. The easiest way to
  grant this permission is by using the FileProvider class.

Here, your intent

 Intent intent = new Intent(Intent.ACTION_PICK);
    File imageViewPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String path =  imageViewPath.getPath();
    intent.setDataAndType(Uri.parse(path),"image/*");

is leaving your app to open the Gallery/Camera to pick an image, which results into a crash, as it does not follow Android Nougat Protocol.

To resolve your problem, change the targetApi in your gradle file to 23 (marshmallow) down from 24/25/26 (whichever you may be having as of now).

Or, you can read more on File Sharing and do it in a way that does not violate StrictMode policy.

In case you are short on time, you can use EasyImage library to solve your purpose.


问:
Rails | Session & Search Params
I have to get a business_model data as session when user clicks to link such as;

```<code>http://localhost:3000/tr/booking_requests/new?business_model=Sleep
</code>```

I also have a search button, where we can search for a user name. After search the url becomes;

```<code>http://localhost:3000/tr/booking_requests/new?utf8=%E2%9C%93&search=Bill
</code>```

So, business_model disappears. Normally, I take this params and assign it to a session

```<code>session[:business_model] = params[:business_model]
</code>```

But once you click to search button new action kicks in and session becomes nil.

How can I achieve this?

EDIT:

When user clicks to link it goes to new action and session is stored.

```<code>def new
    @users = User.search(params[:search]).order('id DESC').paginate(:page => params[:page], :per_page => 15)
    @booking = BookingRequest.new
    session[:business_model] = params[:business_model]
  end
</code>```

But when we click to search button. The request goes to new action again without business_model params. So it becomes nil. How can I store it.

答:
You should not be using the new controller action for something else. 1 action == 1 request. It seems that you are trying to both load the new form and also perform a search in the same action.

One approach would be to have a search action that does not set the session[:business_model] variable. This action can read from the session to make the search results relevant if you need it to and then render the new form.

Alternatively, it may be that the session is not the right approach here and you should really be persisting the business_model in a hidden form field so that it's resubmitted each time.

Title: Rails | Session & Search Params

Body:
I have to get a business_model data as session when user clicks to link such as;

http://localhost:3000/tr/booking_requests/new?business_model=Sleep

I also have a search button, where we can search for a user name. After search the url becomes;

http://localhost:3000/tr/booking_requests/new?utf8=%E2%9C%93&search=Bill

So, business_model disappears. Normally, I take this params and assign it to a session

session[:business_model] = params[:business_model]

But once you click to search button new action kicks in and session becomes nil.

How can I achieve this?

EDIT:

When user clicks to link it goes to new action and session is stored.

def new
    @users = User.search(params[:search]).order('id DESC').paginate(:page => params[:page], :per_page => 15)
    @booking = BookingRequest.new
    session[:business_model] = params[:business_model]
  end

But when we click to search button. The request goes to new action again without business_model params. So it becomes nil. How can I store it.


问:
Why interfaces for message contracts are strongly recommended in MassTransit?
MassTransit states that we should use interfaces for message contracts :

It is strongly suggested to use interfaces for message contracts,
  based on experience over several years with varying levels of
  developer experience. MassTransit will create dynamic interface
  implementations for the messages, ensuring a clean separation of the
  message contract from the consumer.

Source : Docs » Using MassTransit » Creating a message contract

What is downside of using POCO DTOs instead of interfaces, what are the obvious  advantages of Interfaces over classes in the context of messaging with MassTransit?

On the other hand NServiceBus is fine with POCO, and sure it makes sense to not use internal classes like domain object, see below.

Source : NServiceBus » Messaging » Messages, Events and Commands

When creating messages one should follow the following guidelines:

Messages should be simple POCO objects.

Messages should be as small as
  possible.

Messages should satisfy a Single Responsibility Principle.

Classes used for other purposes (e.g. domain objects, data access
  objects and UI binding objects) should not be used as messages.

答:
Although not directly related to MassTransit, but I would say the reason is encapsulation. Creating a simple POCO with setters, but passing it on behind interface that promises only getters encapsulates the data in the DTO.</p>

```<code>public class Program
{
    static void Main(string[] args)
    {
        User user = new User()
        {
            Username = "user99"
        };

        Account account = new Account(user);
    }
}

public interface IUser
{
    string Username { get; }
}

public class User : IUser
{
    public string Username { get; set; }
}

public class Account
{
    private IUser user;

    //Currently used in main
    public Account(User user)
    {
        user.Username = ""; //This is allowed
        this.user = user;
    }

    //But consider this ctor
    public Account(IUser user)
    {
        //user.Username = ""; //Not allowed
        this.user = user;
    }

    ...
}
</code>```

Body:
Although not directly related to MassTransit, but I would say the reason is encapsulation. Creating a simple POCO with setters, but passing it on behind interface that promises only getters encapsulates the data in the DTO.

public class Program
{
    static void Main(string[] args)
    {
        User user = new User()
        {
            Username = "user99"
        };

        Account account = new Account(user);
    }
}

public interface IUser
{
    string Username { get; }
}

public class User : IUser
{
    public string Username { get; set; }
}

public class Account
{
    private IUser user;

    //Currently used in main
    public Account(User user)
    {
        user.Username = ""; //This is allowed
        this.user = user;
    }

    //But consider this ctor
    public Account(IUser user)
    {
        //user.Username = ""; //Not allowed
        this.user = user;
    }

    ...
}


问:
getting stuck at saving a string
i get a encoded string when saving a string
When i save:

```<code>'FFFA
</code>```

i get:

```<code>'FFFA
</code>```

how can i save them using the ff curl request:

```<code>curl "https://api.adbutler.com/v1/banners/custom-html" \
-H "Authorization: Basic {API_KEY}" \
-H "Content-Type: application/json" \
-X POST \
-d '{
      "custom_html": "",
      "expand_horizontal_direction": "left",
      "expand_vertical_direction": "down",
      "height": 250,
      "html_content_below": "Hello 'world",
      "location": "http://www.google.ca",
      "name": "Demo Custom HTML' Banner",
      "tracking_pixel": "url",
      "width": 300
    }'
</code>```

答:
You can try this

```<code>curl "https://api.adbutler.com/v1/banners/custom-html" \
-H "Authorization: Basic {API_KEY}" \
-H "Content-Type: application/json" \
-X POST \
-d '{
  "custom_html": "",
  "expand_horizontal_direction": "left",
  "expand_vertical_direction": "down",
  "height": 250,
  "html_content_below": "Hello '\''world",
  "location": "http://www.google.ca",
  "name": "Demo Custom HTML'\'' Banner",
  "tracking_pixel": "url",
  "width": 300
}'
</code>```

see this link for more info

Title: getting stuck at saving a string

Body:
i get a encoded string when saving a string
When i save:

'FFFA

i get:

'FFFA

how can i save them using the ff curl request:

curl "https://api.adbutler.com/v1/banners/custom-html" \
-H "Authorization: Basic {API_KEY}" \
-H "Content-Type: application/json" \
-X POST \
-d '{
      "custom_html": "",
      "expand_horizontal_direction": "left",
      "expand_vertical_direction": "down",
      "height": 250,
      "html_content_below": "Hello 'world",
      "location": "http://www.google.ca",
      "name": "Demo Custom HTML' Banner",
      "tracking_pixel": "url",
      "width": 300
    }'

Body:
You can try this

curl "https://api.adbutler.com/v1/banners/custom-html" \
-H "Authorization: Basic {API_KEY}" \
-H "Content-Type: application/json" \
-X POST \
-d '{
  "custom_html": "",
  "expand_horizontal_direction": "left",
  "expand_vertical_direction": "down",
  "height": 250,
  "html_content_below": "Hello '\''world",
  "location": "http://www.google.ca",
  "name": "Demo Custom HTML'\'' Banner",
  "tracking_pixel": "url",
  "width": 300
}'

see this link for more info


问:
SMTP "Error: DATA not accepted from server!" Opencart 2.3 on InMotionHosting
I've installed a brand new Opencart 2.3.0.2 on Inmotionhosting with all default settings except MAIL settings which I've tried many different combinations. Although it shows the "Error: DATA not accepted from server!", but it sends mail successfully!

Hosting support center says that all everything is OK, so it should be a coding issue!

Mail Setting:

```<code>Mail Protocol: SMTP
Mail Parameters: -fnoreply@mywebsite.com
SMTP Hostname: mail.mywebsite.com
SMTP Username: noreply@mywebsite.com
SMTP Password: ********
SMTP Port: 587
SMTP Timeout: 5
</code>```

Full Error details:

```<code>Fatal error:  Uncaught exception 'Exception' with message 'Error: DATA not accepted from server!' in /home/mywebsite/public_html/mywebsite.com/oc/system/library/mail.php:409
Stack trace:
#0 /home/mywebsite/public_html/mywebsite.com/oc/catalog/model/account/customer.php(81): Mail->send()
#1 [internal function]: ModelAccountCustomer->addCustomer(Array)
#2 /home/mywebsite/public_html/mywebsite.com/oc/system/engine/loader.php(178): call_user_func_array(Array, Array)
#3 [internal function]: Loader->{closure}(Array, Array)
#4 /home/mywebsite/public_html/mywebsite.com/oc/system/engine/proxy.php(25): call_user_func_array(Object(Closure), Array)
#5 /home/mywebsite/public_html/mywebsite.com/oc/catalog/controller/account/register.php(21): Proxy->__call('addCustomer', Array)
#6 /home/mywebsite/public_html/mywebsite.com/oc/catalog/controller/account/register.php(21): Proxy->addCustomer(Array)
#7 [internal function]: ControllerAccountRegister->index()
#8 /home/mywebsite/public_html/mywebsite.com/oc/system/engine/action.php(51): call_user_func_array(Array, Array)
#9 /home/sabour in /home/mywebsite/public_html/mywebsite.com/oc/system/library/mail.php on line 409
</code>```

Any idea how to get rid of this error?

答:
I have commented above, but if this does not fix your issue, there is a series of config steps to work through below:

Here is the complete article which I obtained from:

https://opencartforum.com/topic/23861-resheno-yandex-takoy-yandex-ne-otpravlyayutsya-pisma-vydaet-oshibku-data-not-accepted-from-server/?page=2

Opencart 2.0+ fix

First edit the file catalog / controller / information / contact.php
Look for line:

```<code>$ Mail-> setFrom ($ this-> request-> post [ 'email']);
</code>```

Change it to:

```<code>$ Mail-> setFrom ($ this-> config-> get ('config_email'));
</code>```

What this will do is set the FROM field to be the same as your shop's main email address.

Now find this line:

```<code>$ Mail-> setSender ($ this-> request-> post ['name']);
</code>```

Change it to:

```<code>$ Mail-> setReplyTo ($ this-> request-> post ['email']);
$ Mail-> setSender ($ this-> config-> get ('config_email'));
</code>```

Now we need to edit system / library / mail.php file
You just need to change one line:

```<code>$ Header = 'Reply-To:? = UTF-8 B??'. . base64_encode ($ this-> replyto). '='. '<'. $ This-> from. '>'. $ This-> newline;
</code>```

change it to:

```<code>$ Header = 'Reply-To:? = UTF-8 B??'. . base64_encode ($ this-> replyto). '='. '<'. $ This-> replyto. '>'. $ This-> newline;
</code>```

There is also a similar issue here:

phpmailer - The following SMTP Error: Data not accepted

Body:
I've installed a brand new Opencart 2.3.0.2 on Inmotionhosting with all default settings except MAIL settings which I've tried many different combinations. Although it shows the "Error: DATA not accepted from server!", but it sends mail successfully!

Hosting support center says that all everything is OK, so it should be a coding issue!

Mail Setting:

Mail Protocol: SMTP
Mail Parameters: -fnoreply@mywebsite.com
SMTP Hostname: mail.mywebsite.com
SMTP Username: noreply@mywebsite.com
SMTP Password: ********
SMTP Port: 587
SMTP Timeout: 5

Full Error details:

Fatal error:  Uncaught exception 'Exception' with message 'Error: DATA not accepted from server!' in /home/mywebsite/public_html/mywebsite.com/oc/system/library/mail.php:409
Stack trace:
#0 /home/mywebsite/public_html/mywebsite.com/oc/catalog/model/account/customer.php(81): Mail->send()
#1 [internal function]: ModelAccountCustomer->addCustomer(Array)
#2 /home/mywebsite/public_html/mywebsite.com/oc/system/engine/loader.php(178): call_user_func_array(Array, Array)
#3 [internal function]: Loader->{closure}(Array, Array)
#4 /home/mywebsite/public_html/mywebsite.com/oc/system/engine/proxy.php(25): call_user_func_array(Object(Closure), Array)
#5 /home/mywebsite/public_html/mywebsite.com/oc/catalog/controller/account/register.php(21): Proxy->__call('addCustomer', Array)
#6 /home/mywebsite/public_html/mywebsite.com/oc/catalog/controller/account/register.php(21): Proxy->addCustomer(Array)
#7 [internal function]: ControllerAccountRegister->index()
#8 /home/mywebsite/public_html/mywebsite.com/oc/system/engine/action.php(51): call_user_func_array(Array, Array)
#9 /home/sabour in /home/mywebsite/public_html/mywebsite.com/oc/system/library/mail.php on line 409

Any idea how to get rid of this error?

Body:
I have commented above, but if this does not fix your issue, there is a series of config steps to work through below:

Here is the complete article which I obtained from:

https://opencartforum.com/topic/23861-resheno-yandex-takoy-yandex-ne-otpravlyayutsya-pisma-vydaet-oshibku-data-not-accepted-from-server/?page=2

Opencart 2.0+ fix

First edit the file catalog / controller / information / contact.php
Look for line:

$ Mail-> setFrom ($ this-> request-> post [ 'email']);

Change it to:

$ Mail-> setFrom ($ this-> config-> get ('config_email'));

What this will do is set the FROM field to be the same as your shop's main email address.

Now find this line:

$ Mail-> setSender ($ this-> request-> post ['name']);

Change it to:

$ Mail-> setReplyTo ($ this-> request-> post ['email']);
$ Mail-> setSender ($ this-> config-> get ('config_email'));

Now we need to edit system / library / mail.php file
You just need to change one line:

$ Header = 'Reply-To:? = UTF-8 B??'. . base64_encode ($ this-> replyto). '='. '<'. $ This-> from. '>'. $ This-> newline;

change it to:

$ Header = 'Reply-To:? = UTF-8 B??'. . base64_encode ($ this-> replyto). '='. '<'. $ This-> replyto. '>'. $ This-> newline;

There is also a similar issue here:

phpmailer - The following SMTP Error: Data not accepted


问:
Why is 'while controller' not working in 'loop controller'?
I need to implement this use case.
I have to use a while controller test fragment in a loop controller and then run a request. After that, I need to run another request which is in a while loop. It should repeat 2 times.
Loop set to =2.

It runs successfully the first time, but the second time it just skips the while controller request.

答:
It worked by setting newValue to variable.
Added BeanShell post processor and added code like</p>
```<code>vars.put("Id_job","newValue");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It worked by setting newValue to variable.
Added BeanShell post processor and added code like

vars.put("Id_job","newValue");


问:
How to calculate the profit of sales orders for a given time if the cost if variable?
I have the below tables in database, I need to calculate the revenue(sum of sell price of all orders ), the cost (sum of all costs of all sold products) and the profit (the revenue minus the cost). However the cost is variable.
The cost of an item may be changed with time.

Example: I bought 10 items of item X for $ 5
3 items were sold. Then I bought 3 items of X for $ 4

I tried getting the average cost of item x and then use it to calculate the profit, but it is not a good approach.

How can I know the cost of item x for each sales order? Is there a way to do that?

I don't want a code . I just need an idea for solving this issue!

sales_order

id

grand_total (sum of sell_price of its items)

order_status (pending/complete)

delivery_date (date)

sales_order_item

id

sales_order_id

product_id (unique)

quantity (ordered quantity)

sell_price (sell price for single item)

purchase_order

id

created_at

status (pending / approved)

purchase_order_items

id

purchase_order_id

product_id

cost  (cost of each item)

答:
Well if I understand correctly, you can fetch purchase_order_items and sales_order_item (with product_id) and for each product_id income is sell_price * quantity and cost is cost * quantity.

UPDATE: Using inner join.

UPDATE: If you are not keeping the actual variable that effects the cost then the only solution is machine learning or statistics (probability theory).


问:
Mysql join tables with or without a condition
I have a problem i've been having quite a lot recently and it would be great to find a solution for it.
Let's say we have two tables Table1 and Table2. Is there a way to make a join on these tables with or without a condition?

e.g:

```<code>Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in (v1,v2,v3) and ...;

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in ('') and ....;
</code>```

So in these two cases i wanna be able to do a join, if I point a condition on the t2 column then it would show me results related to that otherwise show everything.

At the moment if I put the in('') it wouldn't show anything.

Thanks in advance.

答:
```<code>Select *
from Table1 t1 left join
     Table2 t2
     on t1.column = t2.column and
     t2.anothercolumn in (coalesce (@input, t2.anothercolumn)) and ...
     where t1.someColumnName is NOT NULL or @value is NULL
;
</code>```

If @input is not null, then all fields will be returned, else filtered fields will be returned.

Body:
I have a problem i've been having quite a lot recently and it would be great to find a solution for it.
Let's say we have two tables Table1 and Table2. Is there a way to make a join on these tables with or without a condition?

e.g:

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in (v1,v2,v3) and ...;

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in ('') and ....;

So in these two cases i wanna be able to do a join, if I point a condition on the t2 column then it would show me results related to that otherwise show everything.

At the moment if I put the in('') it wouldn't show anything.

Thanks in advance.

Body:
Select *
from Table1 t1 left join
     Table2 t2
     on t1.column = t2.column and
     t2.anothercolumn in (coalesce (@input, t2.anothercolumn)) and ...
     where t1.someColumnName is NOT NULL or @value is NULL
;

If @input is not null, then all fields will be returned, else filtered fields will be returned.


问:
How am I able to move my
 to where I want it?
How can I move my menu
 to the bottom left in this div?

Codepen: https://codepen.io/audn/pen/QgwvNq

I've tried margin-left:auto, but didn't seem to work.
Is it because of my padding?

HTML:

.verified{
  font-size:5px;
}
ul.media {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  margin-left: auto;
  background-color: #111019;
}
li.media {
  float: left;
}
li.media a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
li.media a:hover {
  background-color: #111019;
}
.content-selfmade{
  width: 250px;
  background-color: #111019;
  padding: 15px 15px;
  float:left;
  color: white;
  margin-left: auto;
  margin-right: auto;
  border-radius: .2em;
  margin-bottom: 10px;
  margin-left: 10px;
  height: 120px;
}
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}
.staff-verified{
  color: #e58900;
}
.lightPill{
  color:white;
  background-color:#e58900;
  padding:.1em .35em;
  border-radius:1px;
  font-size:.75em;
}
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
}
.btn-team {
  border: 1px solid #e58900;
  border-radius: 5px;
  font-family: Arial;
  float:left;
  margin-top: 10px;
  color: #ffffff;
  font-size: 12px;
  padding: 5px 15px 5px 15px;
  text-decoration: none;
}

.btn-team:hover {
  cursor: pointer;
  border: 1px solid #7c4b01;
  text-decoration: none;
  float:left;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}
.h2{
  font-size: 11px;
}
#steam-photo{
  background-image: url('http://i.imgur.com/fkue1Ww.png');
  border-radius: 50%;
  width: 75px;
  height: 75px;
}
#team-members{
  width: 25px;
  height:25px;
  border-radius: 50%;
  float:left;
  margin-left: 5px;
  margin-top: 5px;
}
.content-selfmade-name{
  top: 0;
  display: block;
  font-size:  1rem;
  float: right;
  width: 140px;
  margin-top: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="content-selfmade">
    <img id="steam-photo" src="http://i.imgur.com/fkue1Ww.png"></span>
    <span class="content-selfmade-name">Audn
      <font style="color:#0288D1;";>

          <div class="tooltip">
            <i class="fa fa-check-circle" aria-hidden="true"></i>
              <span class="tooltiptext">Verified Staff member.</span>
          </div>

      </font>
      <div class="h2">
        <span class="staff-verified">PUBG.team developer.</span>
      </div>
    <img id="team-members" src="https://cdn.discordapp.com/attachments/301429296390602752/321126144193593345/yggdrasil128.png">
    <img id="team-members" src="http://i.imgur.com/9Ix1SKa.jpg">
    <img id="team-members" src="http://i.imgur.com/RsOTLvl.png">
    <p>
  </span>
  <ul class="media">
    <li class="media">Stats</li>
    <li class="media">Steam</li>
  </ul>
</div></code>```

答:
There are a few isssues with your code, your HTML is pretty messed up :

You have lots of span that have divs inside, which is not really recommended : span is an inline element (takes only the space that they need, don't create a new line), whereas div, p, ul and others are block elements (usually take 100% of the width of the parent, therefore they usually appear on a new line).

Your code is also poorly indented, which is not really helping solve this.

Line 2 of your CodePen, there is a   that doesn't have an opening tag.

The font tag is not supported in HTML5 (see https://www.w3schools.com/tags/tag_font.asp)

You can't use an id more than 1 time. Use class for this.

I tried to correct your code a bit :

```<code><div class="content-selfmade">
    <div class="user-header">
        <div class="featured-photo">
            <img id="steam-photo" src="http://i.imgur.com/fkue1Ww.png">
        </div>
        <div class="user-info">
            <p class="content-selfmade-name">Audn
                <a href="/verified">
                    <span class="tooltip">
                        <i class="fa fa-check-circle" aria-hidden="true"></i>
                        <span class="tooltiptext">Verified Staff member.</span>
                    </span>
                </a>
            </p>
            <h2 class="staff-verified">PUBG.team developer.</h2>
            <p>
                <img class="team-members" src="https://cdn.discordapp.com/attachments/301429296390602752/321126144193593345/yggdrasil128.png">
                <img class="team-members" src="http://i.imgur.com/9Ix1SKa.jpg">
                <img class="team-members" src="http://i.imgur.com/RsOTLvl.png">
            <p>
        </div>
    </div>

    <ul class="media">
        <li class="media"><a href="#index">Stats</a></li>
        <li class="media"><a href="#index">Steam</a></li>
    </ul>
</div>
</code>```

I didn't touch much of your CSS but I added some things and changed others, make sure you understand everything and if you don't, feel free too ask !

```<code>.user-header{
  display:flex;
  align-items:center;

}
ul.media{
  width:100%
}

.user-info{
  margin-left: 20px;
}
.user-info p{
  margin:0;
}

.verified{
    font-size:5px;
  }
    ul.media {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    margin-left: auto;
    background-color: #111019;
    }
    li.media {
    float: left;
    }
    li.media a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    }
    li.media a:hover {
    background-color: #111019;
    }
  .content-selfmade{
    width: 250px;
    background-color: #111019;
    padding: 15px 15px;
    float:left;
    color: white;
    margin-left: auto;
    margin-right: auto;
    border-radius: .2em;
    margin-bottom: 10px;
    margin-left: 10px;
  }
  .tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black;
}
    .staff-verified{
      color: #e58900;
    }
.lightPill{color:white;background-color:#e58900;padding:.1em .35em;border-radius:1px;font-size:.75em}
.tooltip .tooltiptext {
    visibility: hidden;
    width: 120px;
    background-color: black;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px 0;

    /* Position the tooltip */
    position: absolute;
    z-index: 1;
}
    .btn-team {
    border: 1px solid #e58900;
    border-radius: 5px;
    font-family: Arial;
    float:left;
    margin-top: 10px;
    color: #ffffff;
    font-size: 12px;
    padding: 5px 15px 5px 15px;
    text-decoration: none;
    }

    .btn-team:hover {
    cursor: pointer;
    border: 1px solid #7c4b01;
    text-decoration: none;
    float:left;
    }

    .tooltip:hover .tooltiptext {
    visibility: visible;
    }
    h2{
    font-size: 11px;
      margin:0;
    }
  #steam-photo{
    background-image: url('http://i.imgur.com/fkue1Ww.png');
    border-radius: 50%;
    width: 75px;
    height: 75px;
  }
  .team-members{
    width: 25px;
    height:25px;
    border-radius: 50%;
    float:left;
    margin-left: 5px;
    margin-top: 5px;
  }
  .content-selfmade-name{
    top: 0;
    display: block;
    font-size:  1rem;
    float: right;
    width: 140px;
    margin-top: 10px;
    margin-bottom:0;
    }
</code>```

Title: How am I able to move my <ul> to where I want it?

Body:
How can I move my menu
 to the bottom left in this div?

Codepen: https://codepen.io/audn/pen/QgwvNq

I've tried margin-left:auto, but didn't seem to work.
Is it because of my padding?

HTML:

.verified{
  font-size:5px;
}
ul.media {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  margin-left: auto;
  background-color: #111019;
}
li.media {
  float: left;
}
li.media a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
li.media a:hover {
  background-color: #111019;
}
.content-selfmade{
  width: 250px;
  background-color: #111019;
  padding: 15px 15px;
  float:left;
  color: white;
  margin-left: auto;
  margin-right: auto;
  border-radius: .2em;
  margin-bottom: 10px;
  margin-left: 10px;
  height: 120px;
}
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}
.staff-verified{
  color: #e58900;
}
.lightPill{
  color:white;
  background-color:#e58900;
  padding:.1em .35em;
  border-radius:1px;
  font-size:.75em;
}
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
}
.btn-team {
  border: 1px solid #e58900;
  border-radius: 5px;
  font-family: Arial;
  float:left;
  margin-top: 10px;
  color: #ffffff;
  font-size: 12px;
  padding: 5px 15px 5px 15px;
  text-decoration: none;
}

.btn-team:hover {
  cursor: pointer;
  border: 1px solid #7c4b01;
  text-decoration: none;
  float:left;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}
.h2{
  font-size: 11px;
}
#steam-photo{
  background-image: url('http://i.imgur.com/fkue1Ww.png');
  border-radius: 50%;
  width: 75px;
  height: 75px;
}
#team-members{
  width: 25px;
  height:25px;
  border-radius: 50%;
  float:left;
  margin-left: 5px;
  margin-top: 5px;
}
.content-selfmade-name{
  top: 0;
  display: block;
  font-size:  1rem;
  float: right;
  width: 140px;
  margin-top: 10px;
}

    Audn

              Verified Staff member.

        PUBG.team developer.

Stats

Steam

Body:
There are a few isssues with your code, your HTML is pretty messed up :

You have lots of span that have divs inside, which is not really recommended : span is an inline element (takes only the space that they need, don't create a new line), whereas div, p, ul and others are block elements (usually take 100% of the width of the parent, therefore they usually appear on a new line).

Your code is also poorly indented, which is not really helping solve this.

Line 2 of your CodePen, there is a  </span> that doesn't have an opening tag.

The font tag is not supported in HTML5 (see https://www.w3schools.com/tags/tag_font.asp)

You can't use an id more than 1 time. Use class for this.

I tried to correct your code a bit :

<div class="content-selfmade">
    <div class="user-header">
        <div class="featured-photo">
            <img id="steam-photo" src="http://i.imgur.com/fkue1Ww.png">
        </div>
        <div class="user-info">
            <p class="content-selfmade-name">Audn
                <a href="/verified">
                    <span class="tooltip">
                        <i class="fa fa-check-circle" aria-hidden="true"></i>
                        <span class="tooltiptext">Verified Staff member.</span>
                    </span>
                </a>
            </p>
            <h2 class="staff-verified">PUBG.team developer.</h2>
            <p>
                <img class="team-members" src="https://cdn.discordapp.com/attachments/301429296390602752/321126144193593345/yggdrasil128.png">
                <img class="team-members" src="http://i.imgur.com/9Ix1SKa.jpg">
                <img class="team-members" src="http://i.imgur.com/RsOTLvl.png">
            <p>
        </div>
    </div>

    <ul class="media">
        <li class="media"><a href="#index">Stats</a></li>
        <li class="media"><a href="#index">Steam</a></li>
    </ul>
</div>

I didn't touch much of your CSS but I added some things and changed others, make sure you understand everything and if you don't, feel free too ask !

.user-header{
  display:flex;
  align-items:center;

}
ul.media{
  width:100%
}

.user-info{
  margin-left: 20px;
}
.user-info p{
  margin:0;
}

.verified{
    font-size:5px;
  }
    ul.media {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    margin-left: auto;
    background-color: #111019;
    }
    li.media {
    float: left;
    }
    li.media a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    }
    li.media a:hover {
    background-color: #111019;
    }
  .content-selfmade{
    width: 250px;
    background-color: #111019;
    padding: 15px 15px;
    float:left;
    color: white;
    margin-left: auto;
    margin-right: auto;
    border-radius: .2em;
    margin-bottom: 10px;
    margin-left: 10px;
  }
  .tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black;
}
    .staff-verified{
      color: #e58900;
    }
.lightPill{color:white;background-color:#e58900;padding:.1em .35em;border-radius:1px;font-size:.75em}
.tooltip .tooltiptext {
    visibility: hidden;
    width: 120px;
    background-color: black;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px 0;

    /* Position the tooltip */
    position: absolute;
    z-index: 1;
}
    .btn-team {
    border: 1px solid #e58900;
    border-radius: 5px;
    font-family: Arial;
    float:left;
    margin-top: 10px;
    color: #ffffff;
    font-size: 12px;
    padding: 5px 15px 5px 15px;
    text-decoration: none;
    }

    .btn-team:hover {
    cursor: pointer;
    border: 1px solid #7c4b01;
    text-decoration: none;
    float:left;
    }

    .tooltip:hover .tooltiptext {
    visibility: visible;
    }
    h2{
    font-size: 11px;
      margin:0;
    }
  #steam-photo{
    background-image: url('http://i.imgur.com/fkue1Ww.png');
    border-radius: 50%;
    width: 75px;
    height: 75px;
  }
  .team-members{
    width: 25px;
    height:25px;
    border-radius: 50%;
    float:left;
    margin-left: 5px;
    margin-top: 5px;
  }
  .content-selfmade-name{
    top: 0;
    display: block;
    font-size:  1rem;
    float: right;
    width: 140px;
    margin-top: 10px;
    margin-bottom:0;
    }


问:
Performance of C++ STL containers. Better speed in struct or without struct?
I have some container for data and think about to put them into a struct (easier to give it to functions etc).
The program should be as fast as possible. Are the accesses to containers in structs slower or exactly the same?

```<code>// data without struct
double d1;
bool b1;
std::map<std::string, std::deque<double>> map1;
std::vector<std::deque<int>> a1;
std::vector<std::deque<int>> a2;
std::vector<std::vector<<std::deque<int>>> a3;
std::vector<std::vector<<std::deque<int>>> a4;
// ... and perhaps even more
</code>```

VS

```<code>struct containerstruct
{
   double d1;
   bool b1;
   std::map<std::string, std::deque<double>> map1;
   std::vector<std::deque<int>> a1;
   std::vector<std::deque<int>> a2;
   std::vector<std::vector<<std::deque<int>>> a3;
   std::vector<std::vector<<std::deque<int>>> a4;
   // ... and perhaps even more
};
containerstruct data;
</code>```

答:
This is just another one of those "will my program run faster if I use global variables?" questions. Fortunately, unlike the situation some 20+ years ago, the answer is now a resounding no!

With modern, optimizing compilers, the resulting code will be nearly identical. At worst, you'll have one pointer dereference to access a field, which will not make a detectable difference in performance.

Therefore, you should write the code that is readable and maintainable, which means encapsulating related things together. This is, by the way, the whole premise of object-oriented design.

Body:
I have some container for data and think about to put them into a struct (easier to give it to functions etc).
The program should be as fast as possible. Are the accesses to containers in structs slower or exactly the same?

// data without struct
double d1;
bool b1;
std::map<std::string, std::deque<double>> map1;
std::vector<std::deque<int>> a1;
std::vector<std::deque<int>> a2;
std::vector<std::vector<<std::deque<int>>> a3;
std::vector<std::vector<<std::deque<int>>> a4;
// ... and perhaps even more

VS

struct containerstruct
{
   double d1;
   bool b1;
   std::map<std::string, std::deque<double>> map1;
   std::vector<std::deque<int>> a1;
   std::vector<std::deque<int>> a2;
   std::vector<std::vector<<std::deque<int>>> a3;
   std::vector<std::vector<<std::deque<int>>> a4;
   // ... and perhaps even more
};
containerstruct data;


问:
Using Factor Variables to Facet a Histogram Beside a Scatter Plot in R
Is it possible to use a factor variable to facet a histogram below or beside a scatter plot in ggplot2 in R (such that the histograms are of the x- and y-components of the data)?

The reason I ask whether this could be done with a factor variable is because faceting seems to be more general than the available packages that address this issue, where, for example with faceting, facet labels can be turned on or off, and also faceting has a more standard appearance where publication may be a concern. (Faceting also by default preserves the use of the same axes).

So far I haven't been able to get this to work because it seems like all faceted data have to be of the same number of dimensions (e.g., the scatterplot data is 2D, the histogram data are 1D).

答:
I am not sure if I fully understand the question since a histogram of factor variables doesn't quite make sense to me. Also, without sample data, I will just have to use mtcars. Something like this might help. I use grid.extra in addition to ggplot2 in order to make the plots have a custom grid arrangement.

```<code>library(gridExtra)
library(ggplot2)

s_plot <- ggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point()

h1 <- ggplot(data = mtcars, aes(x = hp)) + geom_histogram()

h2 <- ggplot(data = mtcars, aes(x = mpg)) + geom_histogram()

grid.arrange(s_plot, h1, h2, layout_matrix = cbind(c(1, 1), c(2, 3)))
</code>```

Note that in the layout_matrix argument in grid.arrange, I use cbind(c(1,1), c(2, 3)) because I want the first plot to be in a column all by itself and then I want the other two plots to occupy individual rows in the second column of the grid.

Body:
I am not sure if I fully understand the question since a histogram of factor variables doesn't quite make sense to me. Also, without sample data, I will just have to use mtcars. Something like this might help. I use grid.extra in addition to ggplot2 in order to make the plots have a custom grid arrangement.

library(gridExtra)
library(ggplot2)

s_plot <- ggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point()

h1 <- ggplot(data = mtcars, aes(x = hp)) + geom_histogram()

h2 <- ggplot(data = mtcars, aes(x = mpg)) + geom_histogram()

grid.arrange(s_plot, h1, h2, layout_matrix = cbind(c(1, 1), c(2, 3)))

Note that in the layout_matrix argument in grid.arrange, I use cbind(c(1,1), c(2, 3)) because I want the first plot to be in a column all by itself and then I want the other two plots to occupy individual rows in the second column of the grid.


问:
What is double dot(..) and single dot(.) in Linux?
The ls -ai command shows that . and .. have their inodes the same as the current directory and parent directory, respectively.

What exactly are . and ..?

Are they real files or even hard links? But as I have known, it's not allowed to create a hard link to a directory.

答:
. represents the current directory that you are using and
.. represents the parent directory.

Example:

Suppose you are in the directory /etc/mysql and you wanted to move to the parent directory, i.e. /etc/. Then use cd..:

/etc/mysql> cd ..

And if you wanted to set the path of one file in the current directory bash file, use . with file name like this: ./filename


问:
display message on success return in ajax with jquery problem
i am using ajax with jquery .i have written this code:

```<code>   $.ajax({url:"myurl.php",
           data:datastr,
           type:"POST",
           success:function(data){
                      $("#msgbx").text(data);
           }
    });
</code>```

it done what i want at the backend but doesn't show the return message in div with #msgbx id.

what is the problem?

答: use $("#msgbx").html(data);

Body:
i am using ajax with jquery .i have written this code:

   $.ajax({url:"myurl.php",
           data:datastr,
           type:"POST",
           success:function(data){
                      $("#msgbx").text(data);
           }
    });

it done what i want at the backend but doesn't show the return message in div with #msgbx id.

what is the problem?

Body: use $("#msgbx").html(data);


问:
Start Background Task using ASP.Net Core Middleware
I'm attempting to run an asynchronous task when loading a page in ASP.Net Core, i.e., I want the task to run as soon as the user routes to the page but for the page to be displayed before the task has completed. It seems that with ASP.Net core you use middleware to perform such tasks. So I attempted to add the following to Startup.cs

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {

// Other configurations here
app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("PageWithAsyncTask"))
                {
                    var serviceWithAsyncTask = serviceProvider.GetService<IMyService>();
                    await serviceWithAsyncTask .DoAsync();
                }
                await next.Invoke();
            });

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

}
</code>```

The problem with the above is that there is a delay in the page loading until DoAsync has complete since we don't call next.Invoke() until DoAsync is complete. How do I correctly implement the above such that next.Invoke() is called immediately after I've got DoAsync running?

答:
ASP.NET was not designed for background tasks. I strongly recommend using a proper architecture, such as Azure Functions / WebJobs / Worker Roles / Win32 services / etc, with a reliable queue (Azure queues / MSMQ / etc) for the ASP.NET app to talk to its service.

However, if you really want to - and are willing to accept the risks (specifically, that your work may be aborted), then you can use IApplicationLifetime.

Body:
I'm attempting to run an asynchronous task when loading a page in ASP.Net Core, i.e., I want the task to run as soon as the user routes to the page but for the page to be displayed before the task has completed. It seems that with ASP.Net core you use middleware to perform such tasks. So I attempted to add the following to Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {

// Other configurations here
app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("PageWithAsyncTask"))
                {
                    var serviceWithAsyncTask = serviceProvider.GetService<IMyService>();
                    await serviceWithAsyncTask .DoAsync();
                }
                await next.Invoke();
            });

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

}

The problem with the above is that there is a delay in the page loading until DoAsync has complete since we don't call next.Invoke() until DoAsync is complete. How do I correctly implement the above such that next.Invoke() is called immediately after I've got DoAsync running?


问:
Convert NetCDF file to CSV or text using Python
I'm trying to convert a netCDF file to either a CSV or text file using Python. I have read this post but I am still missing a step (I'm new to Python). It's a dataset including latitude, longitude, time and precipitation data.

This is my code so far:

```<code>import netCDF4
import pandas as pd

precip_nc_file = 'file_path'
nc = netCDF4.Dataset(precip_nc_file, mode='r')

nc.variables.keys()

lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
precip = nc.variables['precip'][:]
</code>```

I am not sure how to proceed from here, though I understand it's a matter of creating a dataframe with pandas.

答:
I think pandas.Series should work for you to create a CSV with time, lat,lon,precip.

```<code>import netCDF4
import pandas as pd

precip_nc_file = 'file_path'
nc = netCDF4.Dataset(precip_nc_file, mode='r')

nc.variables.keys()

lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
precip = nc.variables['precip'][:]

# a pandas.Series designed for time series of a 2D lat,lon grid
precip_ts = pd.Series(precip, index=dtime)

precip_ts.to_csv('precip.csv',index=True, header=True)
</code>```

Body:
I'm trying to convert a netCDF file to either a CSV or text file using Python. I have read this post but I am still missing a step (I'm new to Python). It's a dataset including latitude, longitude, time and precipitation data.

This is my code so far:

import netCDF4
import pandas as pd

precip_nc_file = 'file_path'
nc = netCDF4.Dataset(precip_nc_file, mode='r')

nc.variables.keys()

lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
precip = nc.variables['precip'][:]

I am not sure how to proceed from here, though I understand it's a matter of creating a dataframe with pandas.

Body:
I think pandas.Series should work for you to create a CSV with time, lat,lon,precip.

import netCDF4
import pandas as pd

precip_nc_file = 'file_path'
nc = netCDF4.Dataset(precip_nc_file, mode='r')

nc.variables.keys()

lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
precip = nc.variables['precip'][:]

# a pandas.Series designed for time series of a 2D lat,lon grid
precip_ts = pd.Series(precip, index=dtime)

precip_ts.to_csv('precip.csv',index=True, header=True)


问:
MySQL round() not working as expected with sum()
I'm using the following query;

```<code>select round(sum(quantity * calories)) as calories
from tableName;
</code>```

where quantity and calories are of type double and having the values 1.00 & 110.50 respectively. I'm expecting an output of 111, but the above query is instead giving me 110. But if I execute a simple query like the below,

```<code>select round (110.50);
</code>```

It's giving me 111 as the output. I went through this Link, and used a query like the following;

```<code>select round(sum(cast(quantity * calories as char))) as calories
from tableName;
</code>```

but this one also not working for me and giving 110 as output. Can someone tell how to arrive at the desired output of 111?

答:
You can accomplish this by casting the arguments first to DECIMAL. Then we performed the SUM / ROUND operation as DECIMAL.

```<code>SELECT round( sum(
    CAST(quantity AS DECIMAL(10,4)) *
    CAST(calories AS DECIMAL(10,4)) ) ) AS calories
FROM tableName;
</code>```

sample

```<code>mysql> SELECT * FROM tableName;

+----+----------+----------+
| id | quantity | calories |
+----+----------+----------+
|  1 |        1 |    110.5 |
+----+----------+----------+
1 row in set (0,02 sec)

mysql> SELECT round( sum(
    ->     CAST(quantity AS DECIMAL(10,4)) *
    ->     CAST(calories AS DECIMAL(10,4)) ) ) AS calories
    -> FROM tableName;
+----------+
| calories |
+----------+
|      111 |
+----------+
1 row in set (0,00 sec)

mysql>
</code>```

sample 2 with DECIMAL(10,2)

```<code>mysql> SHOW CREATE TABLE tableName\G
*************************** 1. row ***************************
       Table: tableName
Create Table: CREATE TABLE `tableName` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `quantity` decimal(10,1) DEFAULT NULL,
  `calories` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
1 row in set (0,00 sec)

mysql> SELECT * from tableName;
+----+----------+----------+
| id | quantity | calories |
+----+----------+----------+
|  1 |      1.0 |   110.50 |
+----+----------+----------+
1 row in set (0,00 sec)

mysql> select round(sum(quantity * calories)) as calories
    -> from tableName;
+----------+
| calories |
+----------+
|      111 |
+----------+
1 row in set (0,00 sec)

mysql>
</code>```

Body:
I'm using the following query;

select round(sum(quantity * calories)) as calories
from tableName;

where quantity and calories are of type double and having the values 1.00 & 110.50 respectively. I'm expecting an output of 111, but the above query is instead giving me 110. But if I execute a simple query like the below,

select round (110.50);

It's giving me 111 as the output. I went through this Link, and used a query like the following;

select round(sum(cast(quantity * calories as char))) as calories
from tableName;

but this one also not working for me and giving 110 as output. Can someone tell how to arrive at the desired output of 111?

Body:
You can accomplish this by casting the arguments first to DECIMAL. Then we performed the SUM / ROUND operation as DECIMAL.

SELECT round( sum(
    CAST(quantity AS DECIMAL(10,4)) *
    CAST(calories AS DECIMAL(10,4)) ) ) AS calories
FROM tableName;

sample

mysql> SELECT * FROM tableName;

+----+----------+----------+
| id | quantity | calories |
+----+----------+----------+
|  1 |        1 |    110.5 |
+----+----------+----------+
1 row in set (0,02 sec)

mysql> SELECT round( sum(
    ->     CAST(quantity AS DECIMAL(10,4)) *
    ->     CAST(calories AS DECIMAL(10,4)) ) ) AS calories
    -> FROM tableName;
+----------+
| calories |
+----------+
|      111 |
+----------+
1 row in set (0,00 sec)

mysql>

sample 2 with DECIMAL(10,2)

mysql> SHOW CREATE TABLE tableName\G
*************************** 1. row ***************************
       Table: tableName
Create Table: CREATE TABLE `tableName` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `quantity` decimal(10,1) DEFAULT NULL,
  `calories` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
1 row in set (0,00 sec)

mysql> SELECT * from tableName;
+----+----------+----------+
| id | quantity | calories |
+----+----------+----------+
|  1 |      1.0 |   110.50 |
+----+----------+----------+
1 row in set (0,00 sec)

mysql> select round(sum(quantity * calories)) as calories
    -> from tableName;
+----------+
| calories |
+----------+
|      111 |
+----------+
1 row in set (0,00 sec)

mysql>


问:
Ionic 2 : Undefined is not an object
I have an error

undefined is not an object (evaluating 'this.email = '123'')

Why is this happening?

My Ionic 2 code in controller:

```<code>email:string = '' ;

facebook_login() {

    this.fb.login(['public_profile', 'email'])
        .then((res: FacebookLoginResponse) => {

            this.fb.api("/me?fields=name,email", []).then(function(user) {

                this.email = '123' ;

            }) ;

    }).catch(e => {
        alert('Error login') ;
    });

}
</code>```

答:
Use arrow function as callback () => {}.

The this will point to the function object rather than the class in your example.

```<code>this.fb.api("/me?fields=name,email", []).then(function(user) {

                this.email = '123' ;

            }) ;
</code>```

Change the above to:

```<code>this.fb.api("/me?fields=name,email", []).then((user) => {

                this.email = '123' ;

            }) ;
</code>```

Title: Ionic 2 : Undefined is not an object

Body:
I have an error

undefined is not an object (evaluating 'this.email = '123'')

Why is this happening?

My Ionic 2 code in controller:

email:string = '' ;

facebook_login() {

    this.fb.login(['public_profile', 'email'])
        .then((res: FacebookLoginResponse) => {

            this.fb.api("/me?fields=name,email", []).then(function(user) {

                this.email = '123' ;

            }) ;

    }).catch(e => {
        alert('Error login') ;
    });

}

Body:
Use arrow function as callback () => {}.

The this will point to the function object rather than the class in your example.

this.fb.api("/me?fields=name,email", []).then(function(user) {

                this.email = '123' ;

            }) ;

Change the above to:

this.fb.api("/me?fields=name,email", []).then((user) => {

                this.email = '123' ;

            }) ;


问:
jcrfsuite training file format
From what I understand from the example of POS Tagging given in the examples of jcrfsuite. The training file is tab separated and first token is the label. But I do not get the BigCluster| thing. Can somebody help me with how to specify tokens in training file.

Example below:

O   BigCluster|00   BigCluster|0000 BigCluster|000000   BigCluster|00000000 BigCluster|0000000000   BigCluster|000000000000 BigCluster|00000000000000   BigCluster|0000000000000000 NextBigCluster|0100 NextBigCluster|01000101 NextBigCluster|010001011111 POSTagDict|D    POSTagDict|N    POSTagDict|^    POSTagDict|$    POSTagDict|G    NextPOSTag|V    1gramSuff|i 1gramPref|i prevword|    prevcurr||i  nextword|predict    nextword|predict    currnext|i|predict  Word|I  Lower|i Xxdshape|X  charclass|1,    first-shortcap  prevnext||predict    t=0

Test file format:

!   BigCluster|01   BigCluster|0110 BigCluster|011011   BigCluster|01101100 BigCluster|0110110011   BigCluster|011011001100 BigCluster|01101100110000   BigCluster|0110110011000000 NextBigCluster|1000 NextBigCluster|10001000 NextBigCluster|100010000000 POSTagDict|V    NextPOSTag|,    metaph_POSDict|N    1gramSuff|n 2gramSuff|nn    3gramSuff|mnn   4gramSuff|mmnn  5gramSuff|mmmnn 6gramSuff|ammmnn    7gramSuff|aammmnn   8gramSuff|aaammmnn  9gramSuff|daaammmnn 1gramPref|d 2gramPref|da    3gramPref|daa   4gramPref|daaa  5gramPref|daaam 6gramPref|daaamm    7gramPref|daaammm   8gramPref|daaammmn  9gramPref|daaammmnn prevword|    prevcurr||daaammmnn  nextword|.  nextword|.  currnext|daaammmnn|.    Word|Daaammmnn  Lower|daaammmnn Xxdshape|Xxxxxxxxx  charclass|1,2,2,2,2,2,2,2,2,    first-initcap   prevnext||.  t=0

答:
What is specified after the label is a list of feature-name and feature-value.
It is in a sparse representation instead of tabular representation.

BigCluster is just one of the features and it's relevant to the specific example only. You should create your own features if you are training from scratch.

Title: jcrfsuite training file format