问:
react open file browser on click a div
My react component:

```<code>import React, { PropTypes, Component } from 'react'

class Content extends Component {
    handleClick(e) {
        console.log("Hellooww world")
    }
    render() {
        return (
            <div className="body-content">
                <div className="add-media" onClick={this.handleClick.bind(this)}>
                    <i className="plus icon"></i>
                    <input type="file" id="file" style={{display: "none"}}/>
                </div>
            </div>
        )
    }
}

export default Content
</code>```

Here when I click a div with icon I want to open a <input> file which shows me option to select photos. After selecting the photos I want to get the value which photo is selected. How can I do this in react ??

答:
Other than just put the input on you view, you will need handle the change of input content. To do this implement onChange, and get opened file info, like this:

```<code><input id="myInput"
   type="file"
   ref={(ref) => this.upload = ref}
   style={{display: 'none'}}
   onChange={this.onChangeFile.bind(this)}
/>

<RaisedButton
    label="Open File"
    primary={false}
    onClick={()=>{this.upload.click()}}
/>

onChangeFile(event) {
    event.stopPropagation();
    event.preventDefault();
    var file = event.target.files[0];
    console.log(file);
    this.setState({file}); /// if you want to upload latter
}
</code>```

Console will output:

```<code>File {
  name: "my-super-excel-file.vcs",
  lastModified: 1503267699000,
  lastModifiedDate: Sun Aug 20 2017 19:21:39 GMT-0300 (-03),
  webkitRelativePath: "",
  size: 54170,
  type:"application/vnd.vcs"
}
</code>```

And now you can work with it like you want. But, if you want to UPLOAD it, you must begin with:

```<code>var form = new FormData();
form.append('file', this.state.file);

YourAjaxLib.doUpload('/yourEndpoint/',form).then(result=> console.log(result));
</code>```

Title: react open file browser on click a div

Body:
My react component:

import React, { PropTypes, Component } from 'react'

class Content extends Component {
    handleClick(e) {
        console.log("Hellooww world")
    }
    render() {
        return (

                    <input type="file" id="file" style={{display: "none"}}/>

        )
    }
}

export default Content

Here when I click a div with icon I want to open a <input> file which shows me option to select photos. After selecting the photos I want to get the value which photo is selected. How can I do this in react ??

Body:
Other than just put the input on you view, you will need handle the change of input content. To do this implement onChange, and get opened file info, like this:

<input id="myInput"
   type="file"
   ref={(ref) => this.upload = ref}
   style={{display: 'none'}}
   onChange={this.onChangeFile.bind(this)}
/>

<RaisedButton
    label="Open File"
    primary={false}
    onClick={()=>{this.upload.click()}}
/>

onChangeFile(event) {
    event.stopPropagation();
    event.preventDefault();
    var file = event.target.files[0];
    console.log(file);
    this.setState({file}); /// if you want to upload latter
}

Console will output:

File {
  name: "my-super-excel-file.vcs",
  lastModified: 1503267699000,
  lastModifiedDate: Sun Aug 20 2017 19:21:39 GMT-0300 (-03),
  webkitRelativePath: "",
  size: 54170,
  type:"application/vnd.vcs"
}

And now you can work with it like you want. But, if you want to UPLOAD it, you must begin with:

var form = new FormData();
form.append('file', this.state.file);

YourAjaxLib.doUpload('/yourEndpoint/',form).then(result=> console.log(result));

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
How to give a div element a percentage height in tinyscrollbar?
I'm using a simple jquery plugin tinyscrollbar to create a custom scrollbar for a div element.

everything works fine.

But my div has a height in percentage %.

But the tinyscrollbar is forcing me to use pixels for the height of the div which is not what I want.

I tried to change the height like this without any success:

```<code>#scrollbar1 .viewport { width: 80%; height: 80%;}
</code>```

But this works fine:

```<code>#scrollbar1 .viewport { width: 80%; height: 200px;}
</code>```

This is a working FIDDLE:

https://jsfiddle.net/4a1v0xso/

Can someone please advice on this issue?

Any help would be appreciated.

答:
Change the css like this. Just add position:absoute; it works for me.

```<code>#scrollbar1 .viewport { width: 80%; height: 90%; overflow: hidden; position: absolute; }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using a simple jquery plugin tinyscrollbar to create a custom scrollbar for a div element.

everything works fine.

But my div has a height in percentage %.

But the tinyscrollbar is forcing me to use pixels for the height of the div which is not what I want.

I tried to change the height like this without any success:

#scrollbar1 .viewport { width: 80%; height: 80%;}

But this works fine:

#scrollbar1 .viewport { width: 80%; height: 200px;}

This is a working FIDDLE:

https://jsfiddle.net/4a1v0xso/

Can someone please advice on this issue?

Any help would be appreciated.

Body:
Change the css like this. Just add position:absoute; it works for me.

#scrollbar1 .viewport { width: 80%; height: 90%; overflow: hidden; position: absolute; }


问:
generate an Excel file using PHP
I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
@Ranjit this is the PHP code that displays the table and generate the excel file

edit 1

```<code><?php
$ch="";
if(isset($_POST['historique']))
{
    if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
    {
                $ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
        ?>
<table id="tab" border="1">
                <tr>
              <th><font color="red">Date</font></th>
                <th><font color="red">Agent</font></th>
            <th><font color="red">numéro</font></th>
                </tr>
<?php

$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
                             while ($data = mssql_fetch_assoc($stmt))
                             {
                                     ?>
     <tr>
 <td><?php echo utf8_encode ($data['operationDate']);?></td>
 <td><?php echo utf8_encode ($data['fullName']);?></td>
 <td><?php echo utf8_encode ($data['number']);?></td>
                                     </tr>
<?php
     } }

     ?>
        </table>
<?php
}
$output ='';
if(isset($_POST['excel']))
{
    if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
    {
    $rq = "// my query
                                 where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
    $res = mssql_query($rq);
  if(mssql_num_rows($res)>0)
  {
    $output.='<table border=1>
            <tr>
                  <th>Date</th>
                  <th>Depanneur</th>
                  <th>numéro</th>
              </tr>
              ';
              while ($row=mssql_fetch_array($res))
              {
                $output .='
                <tr>
                    <td>'.$row["operationDate"].'</td>
                    <td>'.$row["fullName"].'</td>
                    <td>'.$row["number"].'</td>
                </tr>';
              }
                            $output .='</table>';
              header("Content-Type: application/xls;charset=UTF-8");
              header("Content-Disposition: attachement; filename=file.xls");

              echo $output;
                            //mssql_close($conn);
}}}
?>
</code>```

答:
Yes,

It is possible. You can follow this

1) Connect to database:

2) Define a filename of excel

```<code>//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
$fp = fopen('database.xls', "w");
$schema_insert = "";
$schema_insert_rows = "";
//start of printing column names as names of MySQL fields
</code>```

Sources - http://www.anillabs.com/2010/03/how-to-create-excel-file-with-mysql-data-using-php-code/

Title: generate an Excel file using PHP

Body:
I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
@Ranjit this is the PHP code that displays the table and generate the excel file

edit 1

<?php
$ch="";
if(isset($_POST['historique']))
{
    if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
    {
                $ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
        ?>

              Date
                Agent
            numéro

<?php

$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
                             while ($data = mssql_fetch_assoc($stmt))
                             {
                                     ?>

 <?php echo utf8_encode ($data['operationDate']);?>
 <?php echo utf8_encode ($data['fullName']);?>
 <?php echo utf8_encode ($data['number']);?>

<?php
     } }

     ?>

<?php
}
$output ='';
if(isset($_POST['excel']))
{
    if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
    {
    $rq = "// my query
                                 where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
    $res = mssql_query($rq);
  if(mssql_num_rows($res)>0)
  {
    $output.='

                  Date
                  Depanneur
                  numéro

              ';
              while ($row=mssql_fetch_array($res))
              {
                $output .='

                    '.$row["operationDate"].'
                    '.$row["fullName"].'
                    '.$row["number"].'

';
              }
                            $output .='
';
              header("Content-Type: application/xls;charset=UTF-8");
              header("Content-Disposition: attachement; filename=file.xls");

              echo $output;
                            //mssql_close($conn);
}}}
?>

Body:
Yes,

It is possible. You can follow this

1) Connect to database:

2) Define a filename of excel

//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
$fp = fopen('database.xls', "w");
$schema_insert = "";
$schema_insert_rows = "";
//start of printing column names as names of MySQL fields

Sources - http://www.anillabs.com/2010/03/how-to-create-excel-file-with-mysql-data-using-php-code/


问:
Devanagaric text processing(NLP) where to start
I am new to Devnagaric NLP, Is there any group or resources that would help me get started with NLP in Devnagaric language(Mostly Nepali language or similar like Hindi).  I want to be able to develop fonts for Devanagaric and also do some font processing application. If anyone (working in this field), could give me some advice then it would be highly appreciable.
Thanks in advance </p>

答:
I am new to Devnagaric NLP, Is there any group or resources that would help me get started with NLP in Devnagaric language(Mostly Nepali language or similar like Hindi)

You can use embeddings given by fasttext [https://fasttext.cc/docs/en/pretrained-vectors.html#content] and use some deep learning RNN models like LSTM for text-classification, sentiment analysis.

You can find some datasets for named entity recoginition here [http://ltrc.iiit.ac.in/ner-ssea-08/index.cgi?topic=5]

For Processing Indian languages, you can refer here [https://github.com/anoopkunchukuttan/indic_nlp_library]

Nltk supports the indian lanugages, for pos tagging and nlp related tasks you can refer here [http://www.nltk.org/_modules/nltk/corpus/reader/indian.html]


问:
Reload on HTML changes in webpack
I'm trying to wrap my head around webpack and how it processes resources.

Here's my project structure:

```<code>/dist
  (files that can be pushed to server)
/src
  /styles
    s.less
  /js
    main.js
    a.js
  /img
    splash.png
  profile.html
entry.js (webpack entry file)
</code>```

What I'm trying to do:

LESS files are compiled to CSS and put into bundle along with JS

Images are either copied /src/img -> /dist/img with their original names (good for big images) or base64'd and put into bundle (good for icons)

htmls are copied /src/ -> /dist/ with their original names

every time I change html or anything in the styles or js, it does above steps and reloads page in browser

Basically I need to be able to see current state of application without ever touching the browser window

What i've tried

I ran

webpack-dev-server --content-base /dist  --hot-loading (with and without --hot-loading), but this doesn't reload on CSS/LESS changes

above along with webpack --watch, this solved CSS reloading, but I still need to copy html and images to /dist manually

above two along with gulp task that watches html and images and copies them to dist. This solved copying problem, but it doesn't notify webpack-dev-server of changes so I need to F5 each time I change HTML; it defeats the whole purpose of hot reloading.

I tried adding file-loader but this doesn't work for HTML since it produces JS script that requires html file

Here's my entry.js

```<code>require("./src/js/main");
require("./src/css/s.less");
</code>```

And webpack.config.js:

```<code>var path = require('path');
var webpack = require("webpack");
module.exports = {
    entry: "./entry.js",
    output: {
        path: path.join(__dirname,'/dist/js'),
        filename: "bundle.js"
    },
    plugins: [
        new webpack.ProvidePlugin({
            $ : "jquery",
            jQuery : "jquery",
            "window.jQuery" : "jquery",
            "root.jQuery" : "jquery"
        })
    ],
    module: {
        loaders: [
            {
                test: /\.less$/,
                loader: "style!raw!less"
            }
        ]
    }
};
</code>```

Is there a way to solve this using webpack only?

答:
I guess the problem is that your output.path /dist/js is not matching with --content-base /dist [root directory of webpack-dev-server].

You can either try changing the output.path to /dist and then link the bundled output js in html or change the content base to /dist/js

Here is the link for your reference: https://stackoverflow.com/a/47658586/1681972

Title: Reload on HTML changes in webpack

Body:
I'm trying to wrap my head around webpack and how it processes resources.

Here's my project structure:

/dist
  (files that can be pushed to server)
/src
  /styles
    s.less
  /js
    main.js
    a.js
  /img
    splash.png
  profile.html
entry.js (webpack entry file)

What I'm trying to do:

LESS files are compiled to CSS and put into bundle along with JS

Images are either copied /src/img -> /dist/img with their original names (good for big images) or base64'd and put into bundle (good for icons)

htmls are copied /src/ -> /dist/ with their original names

every time I change html or anything in the styles or js, it does above steps and reloads page in browser

Basically I need to be able to see current state of application without ever touching the browser window

What i've tried

I ran

webpack-dev-server --content-base /dist  --hot-loading (with and without --hot-loading), but this doesn't reload on CSS/LESS changes

above along with webpack --watch, this solved CSS reloading, but I still need to copy html and images to /dist manually

above two along with gulp task that watches html and images and copies them to dist. This solved copying problem, but it doesn't notify webpack-dev-server of changes so I need to F5 each time I change HTML; it defeats the whole purpose of hot reloading.

I tried adding file-loader but this doesn't work for HTML since it produces JS script that requires html file

Here's my entry.js

require("./src/js/main");
require("./src/css/s.less");

And webpack.config.js:

var path = require('path');
var webpack = require("webpack");
module.exports = {
    entry: "./entry.js",
    output: {
        path: path.join(__dirname,'/dist/js'),
        filename: "bundle.js"
    },
    plugins: [
        new webpack.ProvidePlugin({
            $ : "jquery",
            jQuery : "jquery",
            "window.jQuery" : "jquery",
            "root.jQuery" : "jquery"
        })
    ],
    module: {
        loaders: [
            {
                test: /\.less$/,
                loader: "style!raw!less"
            }
        ]
    }
};

Is there a way to solve this using webpack only?


问:
Error: select command denied to user '<userid>'@'<ip-address>' for table '
'
In my website, I am using MySQL database. I am using a webservice where in I do all my database related manipulations.

Now In one of the methods of that webservice, I get the following Error.

select command denied to user '<userid>'@'<ip-address>' for table '
'

What could be wrong?

Below is the code where I get that error. I tried debugging and found that it fails at the line

MySqlDataReader result1 = command1.ExecuteReader();

Here is my code:

```<code>        String addSQL = "Select Max(`TradeID`) from `jsontest`.`tbl_Positions";
        MySqlConnection objMyCon = new MySqlConnection(strProvider);
        objMyCon.Open();
        MySqlCommand command = objMyCon.CreateCommand();

        command.CommandText = addSQL;
         MySqlDataReader result = command.ExecuteReader();
        //int j = command.ExecuteNonQuery();
         while (result.Read())
         {
             MaxTradeID = Convert.ToInt32(result[0]);
         }
        objMyCon.Close();
        for (i = 1; i <= MaxTradeID; i++)
        {
            String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";
            MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
            objMyCon1.Open();
            MySqlCommand command1 = objMyCon1.CreateCommand();

            command1.CommandText = newSQL;
            MySqlDataReader result1 = command1.ExecuteReader();
           objMyCon2.Close();
</code>```

答:
You need to grant SELECT permissions to the MySQL user who is connecting to MySQL. See:

http://dev.mysql.com/doc/refman/5.0/en/privilege-system.html

http://dev.mysql.com/doc/refman/5.0/en/user-account-management.html

Title: Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

Body:
In my website, I am using MySQL database. I am using a webservice where in I do all my database related manipulations.

Now In one of the methods of that webservice, I get the following Error.

select command denied to user '<userid>'@'<ip-address>' for table '
'

What could be wrong?

Below is the code where I get that error. I tried debugging and found that it fails at the line

MySqlDataReader result1 = command1.ExecuteReader();

Here is my code:

        String addSQL = "Select Max(`TradeID`) from `jsontest`.`tbl_Positions";
        MySqlConnection objMyCon = new MySqlConnection(strProvider);
        objMyCon.Open();
        MySqlCommand command = objMyCon.CreateCommand();

        command.CommandText = addSQL;
         MySqlDataReader result = command.ExecuteReader();
        //int j = command.ExecuteNonQuery();
         while (result.Read())
         {
             MaxTradeID = Convert.ToInt32(result[0]);
         }
        objMyCon.Close();
        for (i = 1; i <= MaxTradeID; i++)
        {
            String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";
            MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
            objMyCon1.Open();
            MySqlCommand command1 = objMyCon1.CreateCommand();

            command1.CommandText = newSQL;
            MySqlDataReader result1 = command1.ExecuteReader();
           objMyCon2.Close();

ContentLicense: CC BY-SA 2.5


问:
Java can't connect to MySQL if password contain % symbol
Here is my connection URL:

```<code>jdbc:mysql://mydbhost:3306/mydatabase?user=username&password=%u16*!ypK@WrUQbr
</code>```

When i call

```<code>DriverManager.getConnection()
</code>```

with current URL i'm catching exception:

```<code>ava.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u1"
</code>```

If connection URL not contain % everything works.

i have found some info about this issue, and there recommend to do next conversion :

```<code>replaceAll("%(?![0-9a-fA-F]{2})", "%25")
</code>```

With this conversion i have error:

```<code>Access denied for user(incorrect password)
</code>```

Can somebody help to convert url correctly?

答:
Try it with below string, where all reserved characters in your password are replaced with the appropriate percent-encoded value:

```<code>% : %25
* : %2A
! : %21
@ : %40

"jdbc:mysql://mydbhost:3306/mydatabase?user=username&password=%25u16%2A%21ypK%40WrUQbr"
</code>```

More information about percent-encoding Wikipedia

Body:
Here is my connection URL:

jdbc:mysql://mydbhost:3306/mydatabase?user=username&password=%u16*!ypK@WrUQbr

When i call

DriverManager.getConnection()

with current URL i'm catching exception:

ava.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u1"

If connection URL not contain % everything works.

i have found some info about this issue, and there recommend to do next conversion :

replaceAll("%(?![0-9a-fA-F]{2})", "%25")

With this conversion i have error:

Access denied for user(incorrect password)

Can somebody help to convert url correctly?

Body:
Try it with below string, where all reserved characters in your password are replaced with the appropriate percent-encoded value:

% : %25
* : %2A
! : %21
@ : %40

"jdbc:mysql://mydbhost:3306/mydatabase?user=username&password=%25u16%2A%21ypK%40WrUQbr"

More information about percent-encoding Wikipedia


问:
Can't format the date using moment.js
Can't format the below date using moment.js, the below statement returns Invalid Date

```<code>moment('20171206T062406927Z').format('D-MMM-YYYY');
</code>```

Please help me on this.

答:
You need to tell moment which format your date string is in:

```<code>moment('20171206T062406927Z', 'YYYYMMDD[T]HHmmssSSSZ', true).format('D-MMM-YYYY');
</code>```

Edit: updated as per @VincenzoC comment to ensure the timestamp is parsed in UTC

Also fix: use HH for 24-hour format (not hh), and pass a third true parameter to ensure the timestamp is parsed in strict mode.

Title: Can't format the date using moment.js

Body:
Can't format the below date using moment.js, the below statement returns Invalid Date

moment('20171206T062406927Z').format('D-MMM-YYYY');

Please help me on this.

Body:
You need to tell moment which format your date string is in:

moment('20171206T062406927Z', 'YYYYMMDD[T]HHmmssSSSZ', true).format('D-MMM-YYYY');

Edit: updated as per @VincenzoC comment to ensure the timestamp is parsed in UTC

Also fix: use HH for 24-hour format (not hh), and pass a third true parameter to ensure the timestamp is parsed in strict mode.


问:
Laravel order by custom date field
laravel orderBy id works fine with this function:

```<code>News::orderBy('id', 'desc')->paginate(20);
</code>```

But I'm struggling to achieve this with a custom field.

My custom date field (sorting) is a jQuery UI datepicker field that fills a chosen date and it's in this format:

```<code>yy-mm-dd
</code>```

so, if I choose from the datepicker let's say today it will be displayed as a 2017-12-05 and that saves in the database in a same format.

The reason for using this custom field is to add a old news articles, but in a different order.

I've tried to do this with:

```<code>News::orderBy('sorting', 'desc')->paginate(20);
</code>```

but this error is displayed:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sorting' in 'order clause' (SQL: select * from `news` order by `sorting` desc limit 20 offset 0)
</code>```

That column does exists in my database.

How can I order my created articles using my custom "sorting" date field in Laravel?

EDIT:

This is the function for the news lists:

```<code>public function newsList() {
        $news = News::orderBy('id', 'desc')->paginate(20);
        return view('news-list', compact('news'));
    }
</code>```

As I mention before this works, but the idea is to order by a custom date field.

答:
OK, guys I've found the problem! :)

I'll post it here, so it might be useful for someone else.

I'm using the Laravel Translatable plugin. It has two models and two database for the articles. For an example "news" and "newsTranslation".

So, when I want to use orderBy, I cannot order by fields records from the "newsTranslation". That will be only possible from the "news" table.

This error was displayed

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sorting' in 'order clause' (SQL: select * from `news` order by `sorting` desc limit 20 offset 0)
</code>```

because the orderBy is trying to order the articles from the "news", not the "newsTranslation" and in my case that field wasn't available in the "news" table.

I've fix that by creating a date custom field in the "news". Now everything works fine.

Title: Laravel order by custom date field

Body:
laravel orderBy id works fine with this function:

News::orderBy('id', 'desc')->paginate(20);

But I'm struggling to achieve this with a custom field.

My custom date field (sorting) is a jQuery UI datepicker field that fills a chosen date and it's in this format:

yy-mm-dd

so, if I choose from the datepicker let's say today it will be displayed as a 2017-12-05 and that saves in the database in a same format.

The reason for using this custom field is to add a old news articles, but in a different order.

I've tried to do this with:

News::orderBy('sorting', 'desc')->paginate(20);

but this error is displayed:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sorting' in 'order clause' (SQL: select * from `news` order by `sorting` desc limit 20 offset 0)

That column does exists in my database.

How can I order my created articles using my custom "sorting" date field in Laravel?

EDIT:

This is the function for the news lists:

public function newsList() {
        $news = News::orderBy('id', 'desc')->paginate(20);
        return view('news-list', compact('news'));
    }

As I mention before this works, but the idea is to order by a custom date field.

Body:
OK, guys I've found the problem! :)

I'll post it here, so it might be useful for someone else.

I'm using the Laravel Translatable plugin. It has two models and two database for the articles. For an example "news" and "newsTranslation".

So, when I want to use orderBy, I cannot order by fields records from the "newsTranslation". That will be only possible from the "news" table.

This error was displayed

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sorting' in 'order clause' (SQL: select * from `news` order by `sorting` desc limit 20 offset 0)

because the orderBy is trying to order the articles from the "news", not the "newsTranslation" and in my case that field wasn't available in the "news" table.

I've fix that by creating a date custom field in the "news". Now everything works fine.


问:
How to update a password in a SQLite database (Login and Registration System)?
When I click Submit Button in Change password class or layout the app crashes. What's wrong with my code, please teach me! Thanks in Advance. I am working with Sqlite database for user login system and user can change their password from app bar layout. On clicking >>change password in App Bar new activity pops up i.e changePassword Activity. Upto here everything works fine but after typing password and clicking on submit button the app crashes and sets back to MainActivity.

Here is my change password class

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

EditText oldpasswordEditText;
EditText newpasswordEditText;
EditText confirmpasswordEditText;
Button btnsubmit;

String realusername, realpassword;

String checkoldpass, checknewpass, checkconfirmpass;

SQLiteHelper sqLiteHelper;

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

    oldpasswordEditText = findViewById(R.id.oldpasswordEditText);
    newpasswordEditText = findViewById(R.id.newPasswordEditText);
    confirmpasswordEditText = findViewById(R.id.confirmPasswordEditText);
    btnsubmit= findViewById(R.id.btnsubmit);

    checkoldpass = oldpasswordEditText.getText().toString();
    checknewpass = newpasswordEditText.getText().toString();
    checkconfirmpass = confirmpasswordEditText.getText().toString();

    realusername = getIntent().getStringExtra("USERNAME");
    realpassword= getIntent().getStringExtra("PASSWORD");

    btnsubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(!(checkconfirmpass.equals(checknewpass))) {
                Toast.makeText(changePasswordActivity.this,"New Password didn't matched",Toast.LENGTH_SHORT).show();

            }else if (!(realpassword.equals(checkoldpass))){
                Toast.makeText(changePasswordActivity.this,"Old password didn't matched",Toast.LENGTH_SHORT).show();
            }
            else if (checkconfirmpass.equals(checkoldpass)){
                Toast.makeText(changePasswordActivity.this,"New password cannot be same as old password",Toast.LENGTH_SHORT).show();

            }else if(checkconfirmpass.equals(checknewpass.equals(checkoldpass))) {

                Toast.makeText(changePasswordActivity.this, "New password cannot be same as old password", Toast.LENGTH_SHORT).show();
            }
            else{
                sqLiteHelper = new SQLiteHelper(changePasswordActivity.this);
                sqLiteHelper.changepassword(checknewpass,realusername);
            }

        }
    });
}
}
</code>```

Here is my SQLiteHelper class

```<code>public class SQLiteHelper extends SQLiteOpenHelper {

SQLiteDatabase db;
private static final String DATABASE_NAME = "info.db";
private static final int DATABASE_VERSION = 1;

public static final String TABLE_NAME = "profile";
public static final String COLUMN_ID = "userid";
public static final String COLUMN_FULLNAME = "fullname";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASSWORD = "password";
public static final String COLUMN_MOBILE = "mobile";

private static final String CREATE_TABLE_QUERY =
        "CREATE TABLE " + TABLE_NAME + " (" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_FULLNAME + " TEXT, " +
                COLUMN_EMAIL + " TEXT, " +
                COLUMN_PASSWORD + " TEXT, " +
                COLUMN_MOBILE + " TEXT " + ")";

//modified constructor
public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_QUERY);
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public Cursor getData() {
    String query = "SELECT * FROM" + TABLE_NAME;

    Cursor data = db.rawQuery(query, null);
    return data;
}

public void changepassword(String mpassword, String mname) {

   Cursor cur= db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
           +SQLiteHelper.COLUMN_PASSWORD
           +" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});

}
}
</code>```

答:
db will be null, there is also no need for a Cursor, so change

```<code>public void changepassword(String mpassword, String mname) {
   Cursor cur= db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
           +SQLiteHelper.COLUMN_PASSWORD
           +" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}
</code>```

To :-

```<code>public void changepassword(String mpassword, String mname) {
   SQLiteDatabase db = this.getWriteableDatabae();
   db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
           +SQLiteHelper.COLUMN_PASSWORD
           +" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}
</code>```

You will also have the same issue with the getData method so you should add SQLiteDatabase db = this.getWriteableDatabae(); to the getData method as well.

Alternately you could change :-

```<code>public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
</code>```

to :-

```<code>public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    db = this.getWriteableDatabase();
}
</code>```

In which case db will be a valid SQLiteDatabase.

Body:
When I click Submit Button in Change password class or layout the app crashes. What's wrong with my code, please teach me! Thanks in Advance. I am working with Sqlite database for user login system and user can change their password from app bar layout. On clicking >>change password in App Bar new activity pops up i.e changePassword Activity. Upto here everything works fine but after typing password and clicking on submit button the app crashes and sets back to MainActivity.

Here is my change password class

public class changePasswordActivity extends AppCompatActivity {

EditText oldpasswordEditText;
EditText newpasswordEditText;
EditText confirmpasswordEditText;
Button btnsubmit;

String realusername, realpassword;

String checkoldpass, checknewpass, checkconfirmpass;

SQLiteHelper sqLiteHelper;

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

    oldpasswordEditText = findViewById(R.id.oldpasswordEditText);
    newpasswordEditText = findViewById(R.id.newPasswordEditText);
    confirmpasswordEditText = findViewById(R.id.confirmPasswordEditText);
    btnsubmit= findViewById(R.id.btnsubmit);

    checkoldpass = oldpasswordEditText.getText().toString();
    checknewpass = newpasswordEditText.getText().toString();
    checkconfirmpass = confirmpasswordEditText.getText().toString();

    realusername = getIntent().getStringExtra("USERNAME");
    realpassword= getIntent().getStringExtra("PASSWORD");

    btnsubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(!(checkconfirmpass.equals(checknewpass))) {
                Toast.makeText(changePasswordActivity.this,"New Password didn't matched",Toast.LENGTH_SHORT).show();

            }else if (!(realpassword.equals(checkoldpass))){
                Toast.makeText(changePasswordActivity.this,"Old password didn't matched",Toast.LENGTH_SHORT).show();
            }
            else if (checkconfirmpass.equals(checkoldpass)){
                Toast.makeText(changePasswordActivity.this,"New password cannot be same as old password",Toast.LENGTH_SHORT).show();

            }else if(checkconfirmpass.equals(checknewpass.equals(checkoldpass))) {

                Toast.makeText(changePasswordActivity.this, "New password cannot be same as old password", Toast.LENGTH_SHORT).show();
            }
            else{
                sqLiteHelper = new SQLiteHelper(changePasswordActivity.this);
                sqLiteHelper.changepassword(checknewpass,realusername);
            }

        }
    });
}
}

Here is my SQLiteHelper class

public class SQLiteHelper extends SQLiteOpenHelper {

SQLiteDatabase db;
private static final String DATABASE_NAME = "info.db";
private static final int DATABASE_VERSION = 1;

public static final String TABLE_NAME = "profile";
public static final String COLUMN_ID = "userid";
public static final String COLUMN_FULLNAME = "fullname";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASSWORD = "password";
public static final String COLUMN_MOBILE = "mobile";

private static final String CREATE_TABLE_QUERY =
        "CREATE TABLE " + TABLE_NAME + " (" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_FULLNAME + " TEXT, " +
                COLUMN_EMAIL + " TEXT, " +
                COLUMN_PASSWORD + " TEXT, " +
                COLUMN_MOBILE + " TEXT " + ")";

//modified constructor
public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_QUERY);
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public Cursor getData() {
    String query = "SELECT * FROM" + TABLE_NAME;

    Cursor data = db.rawQuery(query, null);
    return data;
}

public void changepassword(String mpassword, String mname) {

   Cursor cur= db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
           +SQLiteHelper.COLUMN_PASSWORD
           +" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});

}
}

Body:
db will be null, there is also no need for a Cursor, so change

public void changepassword(String mpassword, String mname) {
   Cursor cur= db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
           +SQLiteHelper.COLUMN_PASSWORD
           +" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}

To :-

public void changepassword(String mpassword, String mname) {
   SQLiteDatabase db = this.getWriteableDatabae();
   db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
           +SQLiteHelper.COLUMN_PASSWORD
           +" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}

You will also have the same issue with the getData method so you should add SQLiteDatabase db = this.getWriteableDatabae(); to the getData method as well.

Alternately you could change :-

public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

to :-

public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    db = this.getWriteableDatabase();
}

In which case db will be a valid SQLiteDatabase.


问:
Python indexing numpy array using a smaller boolean array
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

If obj.ndim == x.ndim, x[obj] returns a 1-dimensional array filled
  with the elements of x corresponding to the True values of obj. The
  search order will be row-major, C-style. If obj has True values at
  entries that are outside of the bounds of x, then an index error will
  be raised. If obj is smaller than x it is identical to filling it with
  False.

I read from the numpy reference that I can index a larger array using a smaller boolean array ,and the rest entries would be automatically filled with False.

Example :
  From an array, select all rows which sum up to less or equal two:

```<code>>>> x = np.array([[0, 1], [1, 1], [2, 2]])
>>> rowsum = x.sum(-1)
>>> x[rowsum <= 2, :]
array([[0, 1],[1, 1]])
</code>```

But if rowsum would have two dimensions as well:

```<code>>>> rowsum = x.sum(-1, keepdims=True)
>>> rowsum.shape
(3, 1)
>>> x[rowsum <= 2, :]    # fails
IndexError: too many indices
>>> x[rowsum <= 2]
array([0, 1])
</code>```

The last one giving only the first elements because of the extra
  dimension.

But the example simply doesn't work ,it says "IndexError: boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1"

How to make it work ?I'm using python 3.6.3 and numpy 1.13.3.

答:
I think what you are looking for is NumPy broadcasting.

```<code>import numpy as np

x = np.array([[0, 1], [1, 1], [2, 2]])
rowsum = x.sum(axis=1)
x[rowsum <= 2]
</code>```

Gives:

```<code>array([[0, 1],
   [1, 1]])
</code>```

The problem is that you used keepdims=True, which means the sum creates a column vector, rather than a rank one array which can be broadcasted.

Body:
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

If obj.ndim == x.ndim, x[obj] returns a 1-dimensional array filled
  with the elements of x corresponding to the True values of obj. The
  search order will be row-major, C-style. If obj has True values at
  entries that are outside of the bounds of x, then an index error will
  be raised. If obj is smaller than x it is identical to filling it with
  False.

I read from the numpy reference that I can index a larger array using a smaller boolean array ,and the rest entries would be automatically filled with False.

Example :
  From an array, select all rows which sum up to less or equal two:

>>> x = np.array([[0, 1], [1, 1], [2, 2]])
>>> rowsum = x.sum(-1)
>>> x[rowsum <= 2, :]
array([[0, 1],[1, 1]])

But if rowsum would have two dimensions as well:

>>> rowsum = x.sum(-1, keepdims=True)
>>> rowsum.shape
(3, 1)
>>> x[rowsum <= 2, :]    # fails
IndexError: too many indices
>>> x[rowsum <= 2]
array([0, 1])

The last one giving only the first elements because of the extra
  dimension.

But the example simply doesn't work ,it says "IndexError: boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1"

How to make it work ?I'm using python 3.6.3 and numpy 1.13.3.

Body:
I think what you are looking for is NumPy broadcasting.

import numpy as np

x = np.array([[0, 1], [1, 1], [2, 2]])
rowsum = x.sum(axis=1)
x[rowsum <= 2]

Gives:

array([[0, 1],
   [1, 1]])

The problem is that you used keepdims=True, which means the sum creates a column vector, rather than a rank one array which can be broadcasted.


问:
How to build boost with boost_thread_win32-mt-s (crosscompile with mingw)
I can't build Boost on Linux for Windows with MinGW (I can't create boost_thread_win32-mt-s).

It's a version of OS:

```<code># lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:        14.04
Codename:       trusty
</code>```

It's a version of mingw:

```<code># i586-mingw32msvc-g++ --version
i586-mingw32msvc-g++ (GCC) 4.2.1-sjlj (mingw32-2)
</code>```

I downloaded Boost version 1.50.
I try to build it:

```<code>echo "using gcc : 4.2 : i586-mingw32msvc-g++ ;" > user-config.jam
./bootstrap.sh
./b2 --user-config=user-config.jam \
     --with-thread \
     --with-system \
     -sNO_BZIP2=1 \
     -sNO_ZLIB=1 \
     --layout=tagged \
     --build-type=complete \
     link=static,shared \
     runtime-link=static,shared \
     threading=single,multi \
     toolset=gcc \
     target-os=windows \
     address-model=32 \
     release stage
</code>```

After:

```<code># pwd
/usr/src/boost_1_50_0/stage/lib
# ls -1
libboost_system-mt-s.a
libboost_system-mt.a
libboost_system-mt.dll
libboost_system-mt.dll.a
libboost_system-s.a
libboost_system.a
libboost_system.dll
libboost_system.dll.a
</code>```

Why I can't build "boost_thread_win32-mt-s" or other "boost_thread_XXX"?

答:
I solved this problem. I forgot to mention the thread model for Win (threadapi=win32).

Solution:

```<code>echo "using gcc : 4.2 : i586-mingw32msvc-g++ ;" > user-config.jam
./bootstrap.sh
./b2 --user-config=user-config.jam \
     --with-thread \
     --with-system \
     -sNO_BZIP2=1 \
     -sNO_ZLIB=1 \
     --layout=tagged \
     --build-type=complete \
     link=static,shared \
     runtime-link=static,shared \
     threading=single,multi \
     toolset=gcc \
     target-os=windows \
     threadapi=win32 \
     address-model=32 \
     release stage
</code>```

Thanks!

Body:
I can't build Boost on Linux for Windows with MinGW (I can't create boost_thread_win32-mt-s).

It's a version of OS:

# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:        14.04
Codename:       trusty

It's a version of mingw:

# i586-mingw32msvc-g++ --version
i586-mingw32msvc-g++ (GCC) 4.2.1-sjlj (mingw32-2)

I downloaded Boost version 1.50.
I try to build it:

echo "using gcc : 4.2 : i586-mingw32msvc-g++ ;" > user-config.jam
./bootstrap.sh
./b2 --user-config=user-config.jam \
     --with-thread \
     --with-system \
     -sNO_BZIP2=1 \
     -sNO_ZLIB=1 \
     --layout=tagged \
     --build-type=complete \
     link=static,shared \
     runtime-link=static,shared \
     threading=single,multi \
     toolset=gcc \
     target-os=windows \
     address-model=32 \
     release stage

After:

# pwd
/usr/src/boost_1_50_0/stage/lib
# ls -1
libboost_system-mt-s.a
libboost_system-mt.a
libboost_system-mt.dll
libboost_system-mt.dll.a
libboost_system-s.a
libboost_system.a
libboost_system.dll
libboost_system.dll.a

Why I can't build "boost_thread_win32-mt-s" or other "boost_thread_XXX"?

Body:
I solved this problem. I forgot to mention the thread model for Win (threadapi=win32).

Solution:

echo "using gcc : 4.2 : i586-mingw32msvc-g++ ;" > user-config.jam
./bootstrap.sh
./b2 --user-config=user-config.jam \
     --with-thread \
     --with-system \
     -sNO_BZIP2=1 \
     -sNO_ZLIB=1 \
     --layout=tagged \
     --build-type=complete \
     link=static,shared \
     runtime-link=static,shared \
     threading=single,multi \
     toolset=gcc \
     target-os=windows \
     threadapi=win32 \
     address-model=32 \
     release stage

Thanks!


问:
Why is my code so slow?
Top-posted (sorry) answer, for those who don't have time to get into it but may have similar problems.

Rule #1, as always, move as much as you can out of loops.

2,  moving TField var := ADODataSet.FieldByname()  out of the loop
3, ADODataSet.DisableControls(); and ADODataSet.EnableControls(); around the loop
4, stringGrid.Rows[r].BeginUpdate() and EndUpdate() on each row (cannot do on teh whle control)
each of these shaved off a few seconds, but I got it down to "faster than the eye can see" by changing

```<code>loop
  stringGrid.RowCount := stringGrid.RowCount + 1;
end loop
</code>```

to putting stringGrid.RowCount := ADODataSet.RecordCount; before the loop

+1 and heartfelt thanks to all who helped.

(now I will go and see what I can do to optimize drawing a TChart, which is also slow ;-)

with about 3,600 rows in the table this takes 45 seconds to populate the string grid. What am I doing wrong?

```
   ADODataSet := TADODataSet.Create(Nil);
   ADODataSet.Connection := AdoConnection;

   ADODataSet.CommandText := 'SELECT * FROM measurements';
   ADODataSet.CommandType := cmdText;
   ADODataSet.Open();

   while not ADODataSet.eof do
   begin
      TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1;

      measurementDateTime   := UnixToDateTime(ADODataSet.FieldByname('time_stamp').AsInteger);
      DoSQlCommandWithResultSet('SELECT * FROM start_time_stamp', AdoConnection, resultSet);
      startDateTime := UnixToDateTime(StrToInt64(resultSet.Strings[0]));
      elapsedTime   := measurementDateTime - startDateTime;
      TestRunDataStringGrid.Cells[0, Pred(TestRunDataStringGrid.RowCount)] := FormatDateTime('hh:mm:ss', elapsedTime);
      TestRunDataStringGrid.Cells[1, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('inputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[2, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('outputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[3, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('flowRate').AsFloat);
      TestRunDataStringGrid.Cells[4, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterPressure').AsFloat * convert);
      TestRunDataStringGrid.Cells[5, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterLevel').AsFloat);
      TestRunDataStringGrid.Cells[6, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('cod').AsFloat);
      ADODataSet.Next;
   end;

   ADODataSet.Close();
   ADODataSet.Free();
```

update:

```
Function  DoSQlCommandWithResultSet(const command : String; AdoConnection : TADOConnection; resultSet : TStringList): Boolean;
  var
        i : Integer;
        AdoQuery : TADOQuery;

begin
  Result := True;
  resultSet.Clear();

  AdoQuery := TADOQuery.Create(nil);
  try
    AdoQuery.Connection := AdoConnection;
    AdoQuery.SQL.Add(command);
    AdoQuery.Open();
    i := 0;
    while not  AdoQuery.eof do
    begin
      resultSet.Add(ADOQuery.Fields[i].Value);
      i := i + 1;
      AdoQuery.Next;
    end;

  finally
    AdoQuery.Close();
    AdoQuery.Free();
  end;
end;

```

答:
If you aren't using data-aware controls you should use TestRunDataStringGrid.BeginUpdate before and TestRunDataStringGrid.EndUpdate after loop. Without this is your grid constantly redrawing after each modification (adding new row, cell update).

Another tip is set AdoQuery.LockType := ltReadOnly before opening query.

Title: Why is my code so slow?

Body:
Top-posted (sorry) answer, for those who don't have time to get into it but may have similar problems.

Rule #1, as always, move as much as you can out of loops.

2,  moving TField var := ADODataSet.FieldByname()  out of the loop
3, ADODataSet.DisableControls(); and ADODataSet.EnableControls(); around the loop
4, stringGrid.Rows[r].BeginUpdate() and EndUpdate() on each row (cannot do on teh whle control)
each of these shaved off a few seconds, but I got it down to "faster than the eye can see" by changing

loop
  stringGrid.RowCount := stringGrid.RowCount + 1;
end loop

to putting stringGrid.RowCount := ADODataSet.RecordCount; before the loop

+1 and heartfelt thanks to all who helped.

(now I will go and see what I can do to optimize drawing a TChart, which is also slow ;-)

with about 3,600 rows in the table this takes 45 seconds to populate the string grid. What am I doing wrong?

   ADODataSet := TADODataSet.Create(Nil);
   ADODataSet.Connection := AdoConnection;

   ADODataSet.CommandText := 'SELECT * FROM measurements';
   ADODataSet.CommandType := cmdText;
   ADODataSet.Open();

   while not ADODataSet.eof do
   begin
      TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1;

      measurementDateTime   := UnixToDateTime(ADODataSet.FieldByname('time_stamp').AsInteger);
      DoSQlCommandWithResultSet('SELECT * FROM start_time_stamp', AdoConnection, resultSet);
      startDateTime := UnixToDateTime(StrToInt64(resultSet.Strings[0]));
      elapsedTime   := measurementDateTime - startDateTime;
      TestRunDataStringGrid.Cells[0, Pred(TestRunDataStringGrid.RowCount)] := FormatDateTime('hh:mm:ss', elapsedTime);
      TestRunDataStringGrid.Cells[1, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('inputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[2, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('outputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[3, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('flowRate').AsFloat);
      TestRunDataStringGrid.Cells[4, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterPressure').AsFloat * convert);
      TestRunDataStringGrid.Cells[5, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterLevel').AsFloat);
      TestRunDataStringGrid.Cells[6, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('cod').AsFloat);
      ADODataSet.Next;
   end;

   ADODataSet.Close();
   ADODataSet.Free();

update:

Function  DoSQlCommandWithResultSet(const command : String; AdoConnection : TADOConnection; resultSet : TStringList): Boolean;
  var
        i : Integer;
        AdoQuery : TADOQuery;

begin
  Result := True;
  resultSet.Clear();

  AdoQuery := TADOQuery.Create(nil);
  try
    AdoQuery.Connection := AdoConnection;
    AdoQuery.SQL.Add(command);
    AdoQuery.Open();
    i := 0;
    while not  AdoQuery.eof do
    begin
      resultSet.Add(ADOQuery.Fields[i].Value);
      i := i + 1;
      AdoQuery.Next;
    end;

  finally
    AdoQuery.Close();
    AdoQuery.Free();
  end;
end;


问:
Run groovy scripts in Jenkins
I am trying to run groovy script in jenkins. But i am getting below error.

```<code>            import groovy.sql.Sql
            def output = []
            def sql = Sql.newInstance('jdbc:mysql://localhost:3306/logging_schema',     'root', '****', 'com.mysql.jdbc.Driver')
            String sqlString = "SELECT * debug DESC Limit 10;"
            sql.eachRow(sqlString){ row ->
                output.push(row[0])`enter code here`
            }
            return output

                FATAL: command execution failed
            java.io.IOException: Cannot run program "groovy" (in directory "/var/lib/jenkins/workspace/TestNexusDeploy"): error=2, No such file or directory
                at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
                at hudson.Proc$LocalProc.<init>(Proc.java:245)
                at hudson.Proc$LocalProc.<init>(Proc.java:214)
                at hudson.Launcher$LocalLauncher.launch(Launcher.java:846)
                at hudson.Launcher$ProcStarter.start(Launcher.java:384)
                at hudson.Launcher$ProcStarter.join(Launcher.java:395)
                at hudson.plugins.groovy.Groovy.perform(Groovy.java:102)
                at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
                at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)
                at hudson.model.Build$BuildExecution.build(Build.java:205)
                at hudson.model.Build$BuildExecution.doRun(Build.java:162)
                at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
                at hudson.model.Run.execute(Run.java:1728)
                at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
                at hudson.model.ResourceController.execute(ResourceController.java:98)
                at hudson.model.Executor.run(Executor.java:404)
            Caused by: java.io.IOException: error=2, No such file or directory
                at java.lang.UNIXProcess.forkAndExec(Native Method)
                at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
                at java.lang.ProcessImpl.start(ProcessImpl.java:134)
                at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
                ... 15 more
            Build step 'Execute Groovy script' marked build as failure
            [WS-CLEANUP] Deleting project workspace...[WS-CLEANUP] done
            Finished: FAILURE
</code>```

Help me with this, should i need to do some global configuration or any other solutions.

答:
I have found the solution, we have to add the appropriate jar file to run sql instance. Jar file can be loaded from classpath or workspace, in that case u have to first create classloader object and try to load the jar file as mentioned below.</p>

```<code>import groovy.sql.Sql;

def classLoader = ClassLoader.systemClassLoader
while (classLoader.parent) {
    classLoader = classLoader.parent
}
classLoader.addURL(new File("/var/lib/jenkins/workspace/egsdloen-
logging/mysql/mysql.jar").toURL())
def sql =
Sql.newInstance('jdbc:mysql://server/dbname',
'user', 'password', 'com.mysql.jdbc.Driver')
sql.execute 'SELECT * FROM tablename limit 10'
sql.close()
</code>```

Title: Run groovy scripts in Jenkins

Body:
I am trying to run groovy script in jenkins. But i am getting below error.

            import groovy.sql.Sql
            def output = []
            def sql = Sql.newInstance('jdbc:mysql://localhost:3306/logging_schema',     'root', '****', 'com.mysql.jdbc.Driver')
            String sqlString = "SELECT * debug DESC Limit 10;"
            sql.eachRow(sqlString){ row ->
                output.push(row[0])`enter code here`
            }
            return output

                FATAL: command execution failed
            java.io.IOException: Cannot run program "groovy" (in directory "/var/lib/jenkins/workspace/TestNexusDeploy"): error=2, No such file or directory
                at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
                at hudson.Proc$LocalProc.<init>(Proc.java:245)
                at hudson.Proc$LocalProc.<init>(Proc.java:214)
                at hudson.Launcher$LocalLauncher.launch(Launcher.java:846)
                at hudson.Launcher$ProcStarter.start(Launcher.java:384)
                at hudson.Launcher$ProcStarter.join(Launcher.java:395)
                at hudson.plugins.groovy.Groovy.perform(Groovy.java:102)
                at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
                at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)
                at hudson.model.Build$BuildExecution.build(Build.java:205)
                at hudson.model.Build$BuildExecution.doRun(Build.java:162)
                at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
                at hudson.model.Run.execute(Run.java:1728)
                at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
                at hudson.model.ResourceController.execute(ResourceController.java:98)
                at hudson.model.Executor.run(Executor.java:404)
            Caused by: java.io.IOException: error=2, No such file or directory
                at java.lang.UNIXProcess.forkAndExec(Native Method)
                at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
                at java.lang.ProcessImpl.start(ProcessImpl.java:134)
                at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
                ... 15 more
            Build step 'Execute Groovy script' marked build as failure
            [WS-CLEANUP] Deleting project workspace...[WS-CLEANUP] done
            Finished: FAILURE

Help me with this, should i need to do some global configuration or any other solutions.

Body:
I have found the solution, we have to add the appropriate jar file to run sql instance. Jar file can be loaded from classpath or workspace, in that case u have to first create classloader object and try to load the jar file as mentioned below.

import groovy.sql.Sql;

def classLoader = ClassLoader.systemClassLoader
while (classLoader.parent) {
    classLoader = classLoader.parent
}
classLoader.addURL(new File("/var/lib/jenkins/workspace/egsdloen-
logging/mysql/mysql.jar").toURL())
def sql =
Sql.newInstance('jdbc:mysql://server/dbname',
'user', 'password', 'com.mysql.jdbc.Driver')
sql.execute 'SELECT * FROM tablename limit 10'
sql.close()


问:
Get highest count and corresponding value in Django query
I have a patient model with "disease" as one of the fields.
I want to count the top 5 diseases in all patient objects and return the counts for each of them. How could I do that?</p>

答:
I think the best approach would be to separate patient and disease in two different models like this:

```<code>class Patient(models.Model):
    ...

class Disease(models.Model):
    patients = models.ManyToManyField(Patient) # One disease can have n patients
    disease_name = models.CharField(# Customize this as you want)
</code>```

then in your method you can do this (it can be a model method or an external method):

```<code>def your_method_name():
    Disease.objects.all().annotate(num_patients=Count('patients'))\
                         .order_by('num_patients')[:5]
</code>```

Body:
I think the best approach would be to separate patient and disease in two different models like this:

class Patient(models.Model):
    ...

class Disease(models.Model):
    patients = models.ManyToManyField(Patient) # One disease can have n patients
    disease_name = models.CharField(# Customize this as you want)

then in your method you can do this (it can be a model method or an external method):

def your_method_name():
    Disease.objects.all().annotate(num_patients=Count('patients'))\
                         .order_by('num_patients')[:5]


问:
How do you delete rows specified from an object in oracle?
I have a drop down box on a page in my oracle apex application, I'd like to use the drop down box which displays a company's data(company name) within the company table (which I have achieved); which the user can use to identify specifically what company they'd like to delete. I'd then like to use a button to delete the selected company, and that's what I cannot figure out.

So far I have got as far as using dynamic actions to delete every entry in the table.

Pseudo code for what I am trying to achieve:

```<code>SELECT COMPANY_ID FROM COMPANYLIST,
DELETE SELECTED;
</code>```

Company list being the drop-down box name.

答:
It sounds like you are just struggling with the delete statement?

It should be something like this.

```<code>DELETE FROM company
WHERE company_id = (SELECT company_id
                    FROM companylist
                    WHERE upper(company_name) = upper(:P1_COMPANY_NAME) );
</code>```

Replacing company with whatever your company table is called, and :P1_COMPANY_NAME with whatever your select list item is.

Body:
I have a drop down box on a page in my oracle apex application, I'd like to use the drop down box which displays a company's data(company name) within the company table (which I have achieved); which the user can use to identify specifically what company they'd like to delete. I'd then like to use a button to delete the selected company, and that's what I cannot figure out.

So far I have got as far as using dynamic actions to delete every entry in the table.

Pseudo code for what I am trying to achieve:

SELECT COMPANY_ID FROM COMPANYLIST,
DELETE SELECTED;

Company list being the drop-down box name.

Body:
It sounds like you are just struggling with the delete statement?

It should be something like this.

DELETE FROM company
WHERE company_id = (SELECT company_id
                    FROM companylist
                    WHERE upper(company_name) = upper(:P1_COMPANY_NAME) );

Replacing company with whatever your company table is called, and :P1_COMPANY_NAME with whatever your select list item is.


问:
Removing character strings in date in R
$ date "20141013T000000", "20141209T000000", "20150225T000000", "20141209T000000"

I have this "date" variable in R dataframe. I want to clean this variable and remove "T000000" such that "20141013T000000" shows only "20141013" so I can then convert my date variable into it's proper date format.

Thank you very much.

答:
Or a lubridate solution:

```<code>data <- "20141013T000000"
library(lubridate)
as_datetime(date)
#[1] "2014-10-13 UTC"
</code>```

Title: Removing character strings in date in R

Body:
Or a lubridate solution:

data <- "20141013T000000"
library(lubridate)
as_datetime(date)
#[1] "2014-10-13 UTC"


问:
How to conditionally add attribute to an object?
I would like to conditionally add an attribute to an object. Currently I have this:

```<code>    const obj = {
    name: car.name,
    battery: car.battery && car.battery,
    fuel: car.fuel && car.fuel
}
</code>```

The problem is that if car.battery is not present I have battery: undefined. I would rather prefer not having that attribute in the object if it is not present. How can I achieve that?

答:
The problem is that if car.battery is not present I have battery:
  undefined. I would rather prefer not having that attribute in the
  object if it is not present.

Simply

```<code>const obj = Object.assign({}, car);
</code>```

If car doesn't have battery or fuel, it won't get copied to obj

Body:
I would like to conditionally add an attribute to an object. Currently I have this:

    const obj = {
    name: car.name,
    battery: car.battery && car.battery,
    fuel: car.fuel && car.fuel
}

The problem is that if car.battery is not present I have battery: undefined. I would rather prefer not having that attribute in the object if it is not present. How can I achieve that?

Body:
The problem is that if car.battery is not present I have battery:
  undefined. I would rather prefer not having that attribute in the
  object if it is not present.

Simply

const obj = Object.assign({}, car);

If car doesn't have battery or fuel, it won't get copied to obj


问:
Authorization code exchange doesn't work with Google OAuth2
I'm implementing google sign-in on backend according to this tutorial.

I have a JS client:

```<code><script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>

function start() {
    gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
             client_id: 'MY_CLIENT_ID',
             scope: 'profile email https://www.googleapis.com/auth/plus.me',
        });
    });
}

<button id="signinButton">Login Google</button>
<script>
    $('#signinButton').click(function() {
        auth2.grantOfflineAccess().then(signInCallback);
    });
</script>
</code>```

And in signInCallback function I'm sending authResult['code'] to the server.

On the server I need to generate id_token and access_token from serverAuthCode. My backend is written in ASP.NET CORE.

The tutorial has backend implementation examples for Java and Python. On the server I'm doing the following:

```<code>var data = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("code", serverAuthCode),
    new KeyValuePair<string, string>("client_id", "MY_CLIENT_ID"),
    new KeyValuePair<string, string>("client_secret", "MY_CLIENT_SECRET"),
    new KeyValuePair<string, string>("grant_type", "authorization_code"),
    new KeyValuePair<string, string>("redirect_uri", "MY_REDIRECT_URI_DEFINED_IN_GOOGLE_CONSOLE")
});
var tokenResponse = await _httpClient.PostAsync("https://www.googleapis.com/oauth2/v4/token", data);
</code>```

And I'm always getting bad request with one of the errors (randomly):

redirect_uri_mismatch

invalid_grant

Am I doing something wrong with the request?

答:
Your code looks exactly like the method I use successfully with an other OAuth2
/OIDC provider. The only exception is an Accept header, so can you add this to your code (not sure if it will fix your random behavior but it might be worth to try).

```<code>_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
</code>```

For completeness, this is the method I'm using:

```<code>public async Task<TokenResponse> ExchangeCodeForTokens(Uri tokenEndpoint, string code, Uri redirectUri, string clientId, string clientSecret)
{
    var content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        {"grant_type", "authorization_code"},
        {"code", code},
        {"redirect_uri", redirectUri.ToString()},
        {"client_id", clientId},
        {"client_secret", clientSecret}
    });

    using (var client = _httpClientFactory())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = await client.PostAsync(tokenEndpoint, content);
        var responseContent = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
            throw new OpenIdConnectException($"Request to token endpoint {tokenEndpoint} not successful: {responseContent}");

        var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(responseContent);
        if (tokenResponse == null)
            throw new OpenIdConnectException($"Request to token endpoint {tokenEndpoint} did not return a valid response: {responseContent}");

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

Where TokenResponse is:

```<code>public class TokenResponse
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresInSeconds { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }

    [JsonProperty("id_token")]
    public string IdToken { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonIgnore]
    public TimeSpan ExpiresIn => TimeSpan.FromSeconds(ExpiresInSeconds);
}
</code>```

Body:
I'm implementing google sign-in on backend according to this tutorial.

I have a JS client:

function start() {
    gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
             client_id: 'MY_CLIENT_ID',
             scope: 'profile email https://www.googleapis.com/auth/plus.me',
        });
    });
}

<button id="signinButton">Login Google</button>

And in signInCallback function I'm sending authResult['code'] to the server.

On the server I need to generate id_token and access_token from serverAuthCode. My backend is written in ASP.NET CORE.

The tutorial has backend implementation examples for Java and Python. On the server I'm doing the following:

var data = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("code", serverAuthCode),
    new KeyValuePair<string, string>("client_id", "MY_CLIENT_ID"),
    new KeyValuePair<string, string>("client_secret", "MY_CLIENT_SECRET"),
    new KeyValuePair<string, string>("grant_type", "authorization_code"),
    new KeyValuePair<string, string>("redirect_uri", "MY_REDIRECT_URI_DEFINED_IN_GOOGLE_CONSOLE")
});
var tokenResponse = await _httpClient.PostAsync("https://www.googleapis.com/oauth2/v4/token", data);

And I'm always getting bad request with one of the errors (randomly):

redirect_uri_mismatch

invalid_grant

Am I doing something wrong with the request?

Body:
Your code looks exactly like the method I use successfully with an other OAuth2
/OIDC provider. The only exception is an Accept header, so can you add this to your code (not sure if it will fix your random behavior but it might be worth to try).

_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

For completeness, this is the method I'm using:

public async Task<TokenResponse> ExchangeCodeForTokens(Uri tokenEndpoint, string code, Uri redirectUri, string clientId, string clientSecret)
{
    var content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        {"grant_type", "authorization_code"},
        {"code", code},
        {"redirect_uri", redirectUri.ToString()},
        {"client_id", clientId},
        {"client_secret", clientSecret}
    });

    using (var client = _httpClientFactory())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = await client.PostAsync(tokenEndpoint, content);
        var responseContent = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
            throw new OpenIdConnectException($"Request to token endpoint {tokenEndpoint} not successful: {responseContent}");

        var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(responseContent);
        if (tokenResponse == null)
            throw new OpenIdConnectException($"Request to token endpoint {tokenEndpoint} did not return a valid response: {responseContent}");

        return tokenResponse;
    }
}

Where TokenResponse is:

public class TokenResponse
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresInSeconds { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }

    [JsonProperty("id_token")]
    public string IdToken { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonIgnore]
    public TimeSpan ExpiresIn => TimeSpan.FromSeconds(ExpiresInSeconds);
}


问:
Plone: list all ldap users
I'm trying to get the list of all users - local accounts and ldap ones.

If I know an userid (ldap or local account) this is simple, I can get it and check it's properties:

```<code>site = self.context.portal_url.getPortalObject() from
Products.CMFCore.utils import getToolByName
membership_tool = getToolByName(site, 'portal_membership')
membership_tool.getMemberById('some_user_id')
</code>```

^ This is working for both: ldap and local.

```<code>membership_tool.listMemberIds()  # local accounts ids are listed
</code>```

The same with:

```<code>users_tool = getToolByName(self, 'acl_users')
users_tool.getUserIds()  # local accounts ids are listed
</code>```

Any idea how to get the list of users that are using ldap account?

答:
Solved by iterating the keys of _members in portal_memberdata tool. We have some fields for each user.</p>

```<code>md = getToolByName(self, 'portal_memberdata')
all_members = [x for x in md._members.keys()]  # ids of ldap and local accounts are listed
</code>```

Title: Plone: list all ldap users

Body:
I'm trying to get the list of all users - local accounts and ldap ones.

If I know an userid (ldap or local account) this is simple, I can get it and check it's properties:

site = self.context.portal_url.getPortalObject() from
Products.CMFCore.utils import getToolByName
membership_tool = getToolByName(site, 'portal_membership')
membership_tool.getMemberById('some_user_id')

^ This is working for both: ldap and local.

membership_tool.listMemberIds()  # local accounts ids are listed

The same with:

users_tool = getToolByName(self, 'acl_users')
users_tool.getUserIds()  # local accounts ids are listed

Any idea how to get the list of users that are using ldap account?

Body:
Solved by iterating the keys of _members in portal_memberdata tool. We have some fields for each user.

md = getToolByName(self, 'portal_memberdata')
all_members = [x for x in md._members.keys()]  # ids of ldap and local accounts are listed


问:
event when user check some checkbox
I want to make event when user check some checkbox.

I wrote the code below but nothing happened -

I added "alert", but it doesn't shown

HTML

```<code><td id='checkbox_val_to_reveal'>

    <div class="form-group">
        <label>Status</label>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
    </div>

</td>

<div class='reveal_div_by_checkbox_val'>
    <p><label class="title">Ticket Cause</label><br />
</div>
</code>```

JS

```<code><script>
//  $("#checkbox_val_to_reveal .flat").change(function() {

    $("#checkbox_val_to_reveal input[type='checkbox']").change(function() {
        alert("RRR");

    if ($(this).val() === "3" && $(this).is(":checked")) {
        $(".reveal_div_by_checkbox_val").show();
    } else {
        $(".reveal_div_by_checkbox_val").hide();
    }
    });
</script>
</code>```

答:
```<code><script>
    $("input[type='checkbox']").on("click",function() {  // Check the updated line here
        alert("RRR");

    if ($(this).val() === "3" && $(this).is(":checked")) {
        $(".reveal_div_by_checkbox_val").show();
    } else {
        $(".reveal_div_by_checkbox_val").hide();
    }
    });
</script>
</code>```

Title: event when user check some checkbox

Body:
I want to make event when user check some checkbox.

I wrote the code below but nothing happened -

I added "alert", but it doesn't shown

HTML

        Status

<input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved

<input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA

<input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply

Ticket Cause

JS


问:
Redirecting images to php script with .htaccess
I am trying to incorporate Adaptive images - http://www.adaptive-images.com/ into my website.

Github account - https://github.com/MattWilcox/Adaptive-Images

Ideally the .htaccess should redirect all images to adaptive-images.php and the output should be resized images.

The images aren't loading. I checked the response headers and its returning text/html. It seems like the request is going to index.php file.

Below is the current .htaccess which i am using

```<code><IfModule mod_rewrite.c>

  RewriteEngine On

  # Send any GIF, JPG, or PNG request that IS NOT stored inside ai-cache
  # to adaptive-images.php

  RewriteCond %{REQUEST_URI} !/ai-cache
  RewriteRule \.(jpe?g|gif|png)$ adaptive-images.php

  # Send all files except css, js or image files to index.php

  RewriteBase /
  RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
  RewriteRule ^.*$ index.php

</IfModule>
</code>```

The first part is where I'm trying to make it work

The second part works perfectly.

答:
You can change REQUEST_URI with THE_REQUEST that represents original Apache request and it doesn't change after application of other rules unlike REQUEST_URI.

```<code>DirectoryIndex index.php

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /

  # Send any GIF, JPG, or PNG request that IS NOT stored inside ai-cache
  # to adaptive-images.php

  RewriteCond %{REQUEST_URI} !/ai-cache [NC]
  RewriteRule \.(jpe?g|gif|png)$ adaptive-images.php [L]

  # Send all files except css, js or image files to index.php

  RewriteCond %{THE_REQUEST} !(robots\.txt|\.(css|js|png|jpe?g|gif)) [NC]
  RewriteRule . index.php [L]

</IfModule>
</code>```

Body:
I am trying to incorporate Adaptive images - http://www.adaptive-images.com/ into my website.

Github account - https://github.com/MattWilcox/Adaptive-Images

Ideally the .htaccess should redirect all images to adaptive-images.php and the output should be resized images.

The images aren't loading. I checked the response headers and its returning text/html. It seems like the request is going to index.php file.

Below is the current .htaccess which i am using

<IfModule mod_rewrite.c>

  RewriteEngine On

  # Send any GIF, JPG, or PNG request that IS NOT stored inside ai-cache
  # to adaptive-images.php

  RewriteCond %{REQUEST_URI} !/ai-cache
  RewriteRule \.(jpe?g|gif|png)$ adaptive-images.php

  # Send all files except css, js or image files to index.php

  RewriteBase /
  RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
  RewriteRule ^.*$ index.php

</IfModule>

The first part is where I'm trying to make it work

The second part works perfectly.

Body:
You can change REQUEST_URI with THE_REQUEST that represents original Apache request and it doesn't change after application of other rules unlike REQUEST_URI.

DirectoryIndex index.php

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /

  # Send any GIF, JPG, or PNG request that IS NOT stored inside ai-cache
  # to adaptive-images.php

  RewriteCond %{REQUEST_URI} !/ai-cache [NC]
  RewriteRule \.(jpe?g|gif|png)$ adaptive-images.php [L]

  # Send all files except css, js or image files to index.php

  RewriteCond %{THE_REQUEST} !(robots\.txt|\.(css|js|png|jpe?g|gif)) [NC]
  RewriteRule . index.php [L]

</IfModule>


问:
Activate CSS3 animation when the content scrolls into view
I have a bar chart that animates with CSS3 and the animation currently activates as the page loads.

The problem I have is that the given bar chart is placed off screen due to lots of content before it so by the time a user scrolls down to it, the animation has already finished.

I was looking for ways either through CSS3 or jQuery to only activate the CSS3 animation on the bar chart when the viewer sees the chart.

lots of content here, it fills the height of the screen and then some

animating bar chat here

```

If you scroll down really fast right after page load, you can see it animating.

Here is a jsfiddle of my code. Also, I don't know if this matters, but I have several instances of this bar chart on the page.

I have come across a jQuery plug-in called waypoint but I had absolutely no luck getting it to work.

答:
CSS FOR TRIGGER :

```<code><style>
    .trigger{
      width: 100px;
      height: 2px;
      position: fixed;
      top: 20%;
      left: 0;
      background: red;
      opacity: 0;
      z-index: -1;
    }
</style>
<script>
        $('body').append('<div class="trigger js-trigger"></div>');

        $(document).scroll(function () {

           $('YOUR SECTIONS NAME').each(function () {

               let $this = $(this);

               if($this.offset().top <= $('.js-trigger').offset().top) {

                   if (!$this.hasClass('CLASS NAME FOR CHECK ACTIVE SECTION')) {
                       $this
                           .addClass('currSec')
                           .siblings()
                           .removeClass('currSec');
                   }
               }

           });

        });
</script>
</code>```

Body:
I have a bar chart that animates with CSS3 and the animation currently activates as the page loads.

The problem I have is that the given bar chart is placed off screen due to lots of content before it so by the time a user scrolls down to it, the animation has already finished.

I was looking for ways either through CSS3 or jQuery to only activate the CSS3 animation on the bar chart when the viewer sees the chart.

lots of content here, it fills the height of the screen and then some

animating bar chat here

If you scroll down really fast right after page load, you can see it animating.

Here is a jsfiddle of my code. Also, I don't know if this matters, but I have several instances of this bar chart on the page.

I have come across a jQuery plug-in called waypoint but I had absolutely no luck getting it to work.

Body:
CSS FOR TRIGGER :

<style>
    .trigger{
      width: 100px;
      height: 2px;
      position: fixed;
      top: 20%;
      left: 0;
      background: red;
      opacity: 0;
      z-index: -1;
    }
</style>
<script>
        $('body').append('<div class="trigger js-trigger"></div>');

        $(document).scroll(function () {

           $('YOUR SECTIONS NAME').each(function () {

               let $this = $(this);

               if($this.offset().top <= $('.js-trigger').offset().top) {

                   if (!$this.hasClass('CLASS NAME FOR CHECK ACTIVE SECTION')) {
                       $this
                           .addClass('currSec')
                           .siblings()
                           .removeClass('currSec');
                   }
               }

           });

        });
</script>


问:
Show Time in 12 and 24 hour format in UIDatepicker on the basis of app settings not on device Settings
My problem is there is a switch in my app which toggles for 12 hour and 24 hour time format.I am displaying my labels time according to that, but the UIDatePicker time is not getting changed.It's time is depending on device time settings format.Is it possible to show time in UIDatePicker according to my app settings which might be different from device time settings.
Somewhere I read that UIDatePicker respects only device settings but still I want to ask if it is possible to show time in 12 and 24 hour format in UIDatePicker based on my app settings.

Please help me.
Any suggestions would be highly appreciated!

答:
Swift 4 version of ak2g's answer:

```<code>// myDatePicker is yourUIDatePicker Outlet
@IBOutlet weak var myDatePicker: UIDatePicker!

// For 24 Hrs
myDatePicker.locale = Locale(identifier: "en_GB")

//For 12 Hrs
myDatePicker.locale = Locale(identifier: "en_US")
</code>```

Body:
Swift 4 version of ak2g's answer:

// myDatePicker is yourUIDatePicker Outlet
@IBOutlet weak var myDatePicker: UIDatePicker!

// For 24 Hrs
myDatePicker.locale = Locale(identifier: "en_GB")

//For 12 Hrs
myDatePicker.locale = Locale(identifier: "en_US")


答:
Try the following query:

```<code>from django.db.models import Count

Patient.objects.values('disease').order_by().annotate(Count('disease'))
</code>```

If You have the following data in your Patient table,

```<code>+---------+
| disease |
+---------+
| A       |
| B       |
| A       |
| C       |
| A       |
| A       |
| C       |
+---------+
</code>```

The output will be :-

```<code><QuerySet [{'disease': 'A', 'disease__count': 4}, {'disease': 'B','disease__count': 1}, {'disease': 'C', 'disease__count': 2}]>
</code>```

There are many ways to find the max value from this output.

```<code>from django.db.models import Count
from django.db.models import Max

Patient.objects.values('disease').order_by().annotate(disease_count=Count('disease')).aggregate(maxval=Max('disease_count'))
</code>```

Output will be :- {'maxval': 4}

OR

```<code>from django.db.models import Count

query_result = Patient.objects.values('disease').order_by().annotate(disease_count=Count('disease'))
maxval = max(query_result, key=lambda x:x['disease_count'])
</code>```

Output will be :- {'disease': 'A', 'disease_count': 4}

Hope that helps!

Title: Get highest count and corresponding value in Django query

Body:
I have a patient model with "disease" as one of the fields.
I want to count the top 5 diseases in all patient objects and return the counts for each of them. How could I do that?

Body:
Try the following query:

from django.db.models import Count

Patient.objects.values('disease').order_by().annotate(Count('disease'))

If You have the following data in your Patient table,

+---------+
| disease |
+---------+
| A       |
| B       |
| A       |
| C       |
| A       |
| A       |
| C       |
+---------+

The output will be :-

<QuerySet [{'disease': 'A', 'disease__count': 4}, {'disease': 'B','disease__count': 1}, {'disease': 'C', 'disease__count': 2}]>

There are many ways to find the max value from this output.

from django.db.models import Count
from django.db.models import Max

Patient.objects.values('disease').order_by().annotate(disease_count=Count('disease')).aggregate(maxval=Max('disease_count'))

Output will be :- {'maxval': 4}

OR

from django.db.models import Count

query_result = Patient.objects.values('disease').order_by().annotate(disease_count=Count('disease'))
maxval = max(query_result, key=lambda x:x['disease_count'])

Output will be :- {'disease': 'A', 'disease_count': 4}

Hope that helps!


问:
String variable value as a property in a type
i try to create a type which has a variable value as a property

For example:

```<code>const myProp: string = 'my prop';
type Foo ={
    [myProp]: string
};
</code>```

i expected that i can do:

```<code>const test: Foo = {
   [myProp] = myProp
}
</code>```

But get error of:

[ts] A computed property name in a type literal must directly refer to
  a built-in symbol.

答:
You will able to do this once next version of Typescript released.

This feature already available in typescript@next. If you want to, you can install it with:

npm install typescript@next --save-dev

Meanwhile you can use method provided by @Titian Cernicova-Dragomir

Body:
i try to create a type which has a variable value as a property

For example:

const myProp: string = 'my prop';
type Foo ={
    [myProp]: string
};

i expected that i can do:

const test: Foo = {
   [myProp] = myProp
}

But get error of:

[ts] A computed property name in a type literal must directly refer to
  a built-in symbol.


问:
Having trouble when publishing android app to google play store. "Fully Shadowed APK"
I received this message

Fully shadowed APK
  PROBLEM
  This APK will not be served to any users because it is completely shadowed by one or more APKs with higher version codes.
  RESOLUTION
  Remove this APK from your release or review the targeting and version codes of the APKs that you are including in this release.

If i deactivate the previous apk, will it stop other user from using that version they have installed.

I want to be safe. Don't want user fail to use the current application because I deactivate it.

答: Deactivating a version means, that new users won't be able to download it anymore. Keeping it might be useful if the new version has limited compatibility. In this case, users with incompatible devices will be able to download an older compatible version.</p>


问:
Running php files stored on OneDrive
I am developing a php project, having the project files stored on OneDrive so that I can access them from anywhere.

I have set up XAMPP, with a VirtualHost pointing to my project folder inside OneDrive so that I can run it in my browser.

This has been working great up until yesterday, when OneDrive started crashing and I had to reinstall it. Now I'm no longer able to run php files stored on OneDrive.

I get this error in my browser:

```<code>Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Fatal error: Unknown: Failed opening required 'D:/OneDrive/MyProject/index.php' (include_path='C:\xampp\php\PEAR') in Unknown on line 0
</code>```

My OneDrive folder is D:\OneDrive. If I set up a VirtualHost pointing to D:\, I am able to run files such as D:\index.php or D:\MyProject\index.php in my browser. But I'm not able to run files such as D:\OneDrive\index.php or D:\OneDrive\MyProject\index.php.

Does anyone have an idea what might cause this issue?

Edit:

The issue does not seem to be related to .htaccess, as the behavior is independent of whether a .htaccess file exists in the project folder or not.

Here is my VirtualHost, in case anyone is interested:

```<code><VirtualHost *:80>
    ServerAdmin webmaster@myproject.com
    DocumentRoot "D:/OneDrive/MyProject/"
    ServerName myproject.com
    ServerAlias www.myproject.com

    <Directory "D:/OneDrive/MyProject/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Require local
    </Directory>
</VirtualHost>
</code>```

答:
I've not been able to solve the issue, but I've found a workaround:

Store the project files outside of OneDrive.

Make a symbolic link in the OneDrive folder to the project folder outside of OneDrive.

With this setup I'm able to run my PHP application, since the project files are not physically located in the OneDrive folder, and the project files are still uploaded and backed up on OneDrive due to the symbolic link.

Title: Running php files stored on OneDrive

Body:
I am developing a php project, having the project files stored on OneDrive so that I can access them from anywhere.

I have set up XAMPP, with a VirtualHost pointing to my project folder inside OneDrive so that I can run it in my browser.

This has been working great up until yesterday, when OneDrive started crashing and I had to reinstall it. Now I'm no longer able to run php files stored on OneDrive.

I get this error in my browser:

Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Fatal error: Unknown: Failed opening required 'D:/OneDrive/MyProject/index.php' (include_path='C:\xampp\php\PEAR') in Unknown on line 0

My OneDrive folder is D:\OneDrive. If I set up a VirtualHost pointing to D:\, I am able to run files such as D:\index.php or D:\MyProject\index.php in my browser. But I'm not able to run files such as D:\OneDrive\index.php or D:\OneDrive\MyProject\index.php.

Does anyone have an idea what might cause this issue?

Edit:

The issue does not seem to be related to .htaccess, as the behavior is independent of whether a .htaccess file exists in the project folder or not.

Here is my VirtualHost, in case anyone is interested:

<VirtualHost *:80>
    ServerAdmin webmaster@myproject.com
    DocumentRoot "D:/OneDrive/MyProject/"
    ServerName myproject.com
    ServerAlias www.myproject.com

    <Directory "D:/OneDrive/MyProject/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Require local
    </Directory>
</VirtualHost>


问:
How to get sorting complete/finished event of jsgrid
I have 2 different jsGrid table.I have to update the other table data after finishing sorting event of 1st table.I searched the documentation but i couldn't find any complete/finished event for sorting.I found onDataLoaded event,but it does not fire after filtering.
How would i find the completion of sorting event.

答:
I found out the event which gets fired as the data of a grid changes - onRefreshed. Link - documentation link It gives out the grid instance as a argument.

Inside that I used var sorting = $("#grid").jsGrid("getSorting");
to get the sorting which gives -
{
    field,      // the name of the field by which grid is sorted
    order       // 'asc' or 'desc' depending on sort order
}.

If the table has been sorted the object will have the details - {field:'A',order:'asc'} if not then {field:undefined,order:undefined}.

onRefreshed: function (args) {
var sorting = $("#jsgrid").jsGrid("getSorting");
}