问:
Error TokenMismatchException in VerifyCsrfToken.php line 68:
I want to do multiple edit, I want to edit from the data I checked following script .blade, I found the TokenMismatchException error in VerifyCsrfToken.php line 68: when updating.

```<code><form name="form" action="{{url('/update-kb')}}" method="post" onsubmit="return deleteConfirm();"/>
<div class="table table-responsive">
    <table id="example1" class="table table-bordered">
        <thead>
        <tr class="info">
            <th width="3%"><input type="checkbox" name="select_all" id="select_all" value=""/></th>
            <th>No</th>
            <th>Data lengkap</th>
            <th>Aksi</th>
        </tr>
        </thead>
        <tbody>
        <?php $i = 1; ?>
        @foreach( $datasiswa as $row )
            <tr>
                <td>
                    <label class="checkbox-inline"><input type="checkbox" name="checked_id[]" class="checkbox" value="{{$row->id}}"/>
                    </label>
                </td>
                <td width="5%">{{ $i }}</td>
                <td width="95%">
                    <table class="table">
                        <tr>
                            <td class="info">Nama panggilan</td>
                            <td>{{$row->nm_panggilan}}</td>
                            <td class="warning">Pekerjaan ibu</td>
                            <td>{{$row->pekerjaan_ibu}}</td>
                        </tr>
                        <tr>
                            <td class="info">Jenis kelamin</td>
                            <td>{{$row->jenis_kelamin}}</td>
                            <td class="warning">No. Handphone</td>
                            <td>{{$row->hp_ibu}}</td>
                        </tr>
                        <tr>
                            <td class="info">Tempat, Tanggal lahir</td>
                            <td>{{$row->tempat}}, {{$row->tanggal_lahir}}</td>
                            <td class="warning">Alamat</td>
                            <td>{{$row->alamat}}</td>
                        </tr>
                        <tr>
                            <td class="info">Status anak</td>
                            <td>{{$row->status_anak}}</td>
                            <td class="warning">Golongan darah</td>
                            <td>{{$row->goldar}}</td>
                        </tr>
                        <tr>
                            <td class="info">Agama</td>
                            <td>{{$row->agama}}</td>
                            <td class="warning">Nama wali</td>
                            <td>{{$row->nm_wali}}</td>
                        </tr>
                        <tr>
                            <td class="info">Kewarganegaraan</td>
                            <td>{{$row->kewarganegaraan}}</td>
                        </tr>
                        <tr>
                            <td class="info">Anak ke-</td>
                            <td>{{$row->anak_ke}}</td>
                        </tr>
                        <tr>
                            <td class="info">Kelas</td>
                            <td>{{$row->kelas}}</td>
                        </tr>
                    </table>
                </td>
                <td>
                    <a href="{!! url('/'.$row->id.'/edit-siswa') !!}">
                        <button class="btn btn-default btn-block"><i class="fa fa-edit"></i></button><br>
                    </a>
                    <a href="{!! url('/'.$row->id.'/delete-siswa') !!}">
                        <button class="btn btn-danger btn-block"><i class="fa fa-trash"></i></button>
                    </a>
                </td>
                </td>
            </tr>
            <?php $i++; ?>
        @endforeach
        </tbody>
    </table>
    <div class="col-md-3">
        <input type="submit" class="btn btn-danger" name="delete_submit" value="Hapus"/>
    </div>
</div>
</form>
</code>```

But I still have error, what causes it?

```<code>public function updatekb($id, Request $request)
{
    $data = Datasiswa::find($id);
    if (isset($request->delete_submit)) {
        $idArr = $request->checked_id;
        foreach ($idArr as $id) {
            DB::update('update tb_siswa, tb_pernyataan set tb_pernyataan.kelas = "cekcek" where tb_pernyataan.kelas = "TK A" and tb_siswa.sekolah = "KB TK KHALIFAH 25" and id = "' . $id . '" ');
        }

        return back();
        Session::flash('sukses', 'Data berhasil di update', compact('data'));
    }
}
</code>```

答:
Add below to your form element.

```<code><input type="hidden" name="_token" value="{{ csrf_token() }}" />
</code>```

Some answers are suggesting to disable csrf protection which is possible but NOT RECOMENDED. This leaves your application vulnureable.

Body:
I want to do multiple edit, I want to edit from the data I checked following script .blade, I found the TokenMismatchException error in VerifyCsrfToken.php line 68: when updating.

<form name="form" action="{{url('/update-kb')}}" method="post" onsubmit="return deleteConfirm();"/>

            <input type="checkbox" name="select_all" id="select_all" value=""/>
            No
            Data lengkap
            Aksi

        <?php $i = 1; ?>
        @foreach( $datasiswa as $row )

                    <input type="checkbox" name="checked_id[]" class="checkbox" value="{{$row->id}}"/>

                {{ $i }}

                            Nama panggilan
                            {{$row->nm_panggilan}}
                            Pekerjaan ibu
                            {{$row->pekerjaan_ibu}}

                            Jenis kelamin
                            {{$row->jenis_kelamin}}
                            No. Handphone
                            {{$row->hp_ibu}}

                            Tempat, Tanggal lahir
                            {{$row->tempat}}, {{$row->tanggal_lahir}}
                            Alamat
                            {{$row->alamat}}

                            Status anak
                            {{$row->status_anak}}
                            Golongan darah
                            {{$row->goldar}}

                            Agama
                            {{$row->agama}}
                            Nama wali
                            {{$row->nm_wali}}

                            Kewarganegaraan
                            {{$row->kewarganegaraan}}

                            Anak ke-
                            {{$row->anak_ke}}

                            Kelas
                            {{$row->kelas}}

                    id.'/edit-siswa') !!}">
                        <button class="btn btn-default btn-block"></button>

                    id.'/delete-siswa') !!}">
                        <button class="btn btn-danger btn-block"></button>

            <?php $i++; ?>
        @endforeach

        <input type="submit" class="btn btn-danger" name="delete_submit" value="Hapus"/>

</form>

But I still have error, what causes it?

public function updatekb($id, Request $request)
{
    $data = Datasiswa::find($id);
    if (isset($request->delete_submit)) {
        $idArr = $request->checked_id;
        foreach ($idArr as $id) {
            DB::update('update tb_siswa, tb_pernyataan set tb_pernyataan.kelas = "cekcek" where tb_pernyataan.kelas = "TK A" and tb_siswa.sekolah = "KB TK KHALIFAH 25" and id = "' . $id . '" ');
        }

        return back();
        Session::flash('sukses', 'Data berhasil di update', compact('data'));
    }
}

Body:
Add below to your form element.

<input type="hidden" name="_token" value="{{ csrf_token() }}" />

Some answers are suggesting to disable csrf protection which is possible but NOT RECOMENDED. This leaves your application vulnureable.


来源: stackexchange

问:
Nib view differs from Simulator
My nib

My Simulator. I can't understand why constraints don't work

I think code does not have influence, however see it below:

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    if let headeView = Bundle.main.loadNibNamed("HeaderViewCell", owner: self, options: nil)?.first as? HeaderViewCell {

        //headeView.categoryLabel.text = "FFF"
        return headeView
    }

    return UIView()
}
</code>```

答: Please make sure you have given the constraints of the imageView correctly. may be top space leading and the height and width might do. And make the imageView's clip to bounds property to true. </p>

ContentLicense: CC BY-SA 3.0

Title: Nib view differs from Simulator

Body:
My nib

My Simulator. I can't understand why constraints don't work

I think code does not have influence, however see it below:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    if let headeView = Bundle.main.loadNibNamed("HeaderViewCell", owner: self, options: nil)?.first as? HeaderViewCell {

        //headeView.categoryLabel.text = "FFF"
        return headeView
    }

    return UIView()
}


问:
graphite vs collectd. retentions not applied
I have installed collectd on BIND9 hosts and configured it to pass metrics to graphite. I want to be able to view metrics for at least 1 month but retentions in storage-schema.conf not applied for collectd section, and applied last default section that stores only last 24h metrics.
I understand that I need to set correct retentions regex to match metrics but it is seems to me that is correct already but it does not work :(

My storage-schemas.conf looks like this for now:

```<code>[carbon]
pattern = ^carbon\.
retentions = 60:90d

[mxservers]
pattern = ^mx-servers\.*
retentions = 60s:7d,5m:2y

[ns.servers]
pattern = ^ns\d\.collectd\..*
retentions = 60s:7d,10m:2y

[collectd]
pattern =^collectd\.*
retentions = 60s:7d,10m:2y

# *** Netapp Monitoring ***
[netapp.capacity]
pattern = ^netapp\.capacity\.*
retentions = 15m:100d, 1d:5y

[netapp.poller.capacity]
pattern = ^netapp\.poller\.capacity\.*
retentions = 15m:100d, 1d:5y

[netapp.perf]
pattern = ^netapp\.perf\.*
retentions = 60s:35d, 5m:100d, 15m:395d, 1h:5y

[netapp.poller.perf]
pattern = ^netapp\.poller\.perf\.*
retentions = 60s:35d, 5m:100d, 15m:395d, 1h:5y

[netapp.perf7]
pattern = ^netapp\.perf7\.*
retentions = 60s:35d, 5m:100d, 15m:395d, 1h:5y

[netapp.poller.perf7]
pattern = ^netapp\.poller\.perf7\.*
retentions = 60s:35d, 5m:100d, 15m:395d, 1h:5y
# *** Netapp Monitoring ***

[default_1min_for_1day]
pattern = .*
retentions = 60s:1d
</code>```

I have a problem with section named - [ns.servers],
tried to set regex in it to:

```<code>^ns\d\.collectd\.
^ns\d\.collectd\..*
^ns.\.collectd\.
^ns.\.collectd\..*
</code>```

None of them solves the problem.
The metrics are stored with names like this:

```<code>ns1.collectd.load.load.shortterm
ns2.collectd.load.load.longterm
ns1.collectd.interface-bond0.if_packets.rx
ns2.collectd.interface-bond0.if_packets.tx
</code>```

Please help me to set correct regex to get it match.

答:
I finally realized what the problem is! I take a look to /var/log/carbon/creates.log and found that my metrics for collecd is stored as ns2/collectd.* - "hostname"+"/"+"collectd" - because in configuration of collectd on DNS-servers there was an option Postfix "/collectd" that make this.

```<code>05/06/2017 09:54:22 :: creating database file /var/lib/graphite/whisper/ns2/collectd/cpu-1/cpu-idle.wsp (archive=[(60, 1440)] xff=None agg=None)
05/06/2017 09:54:22 :: new metric ns2/collectd.disk-sda.disk_octets.write matched schema default_1min_for_1day
05/06/2017 09:54:22 :: new metric ns2/collectd.disk-sda.disk_octets.write matched aggregation schema default
</code>```

So the solution was to make regex look like this: pattern = ^ns[1-2]\/collectd\.* - escaped "/" - character
and then I deleted old metrics and new metric files was created with correct retentions!

```<code>05/06/2017 11:32:12 :: creating database file /var/lib/graphite/whisper/ns2/collectd/df-boot-efi/df_complex-free.wsp (archive=[(60, 10080), (600, 105120)] xff=None agg=None)
05/06/2017 11:32:12 :: new metric ns2/collectd.interface-eth0.if_errors.tx matched schema ns.servers
05/06/2017 11:32:12 :: new metric ns2/collectd.interface-eth0.if_errors.tx matched aggregation schema default
</code>```

Body:
I have installed collectd on BIND9 hosts and configured it to pass metrics to graphite. I want to be able to view metrics for at least 1 month but retentions in storage-schema.conf not applied for collectd section, and applied last default section that stores only last 24h metrics.
I understand that I need to set correct retentions regex to match metrics but it is seems to me that is correct already but it does not work :(

My storage-schemas.conf looks like this for now:

[carbon]
pattern = ^carbon\.
retentions = 60:90d

[mxservers]
pattern = ^mx-servers\.*
retentions = 60s:7d,5m:2y

[ns.servers]
pattern = ^ns\d\.collectd\..*
retentions = 60s:7d,10m:2y

[collectd]
pattern =^collectd\.*
retentions = 60s:7d,10m:2y

# *** Netapp Monitoring ***
[netapp.capacity]
pattern = ^netapp\.capacity\.*
retentions = 15m:100d, 1d:5y

[netapp.poller.capacity]
pattern = ^netapp\.poller\.capacity\.*
retentions = 15m:100d, 1d:5y

[netapp.perf]
pattern = ^netapp\.perf\.*
retentions = 60s:35d, 5m:100d, 15m:395d, 1h:5y

[netapp.poller.perf]
pattern = ^netapp\.poller\.perf\.*
retentions = 60s:35d, 5m:100d, 15m:395d, 1h:5y

[netapp.perf7]
pattern = ^netapp\.perf7\.*
retentions = 60s:35d, 5m:100d, 15m:395d, 1h:5y

[netapp.poller.perf7]
pattern = ^netapp\.poller\.perf7\.*
retentions = 60s:35d, 5m:100d, 15m:395d, 1h:5y
# *** Netapp Monitoring ***

[default_1min_for_1day]
pattern = .*
retentions = 60s:1d

I have a problem with section named - [ns.servers],
tried to set regex in it to:

^ns\d\.collectd\.
^ns\d\.collectd\..*
^ns.\.collectd\.
^ns.\.collectd\..*

None of them solves the problem.
The metrics are stored with names like this:

ns1.collectd.load.load.shortterm
ns2.collectd.load.load.longterm
ns1.collectd.interface-bond0.if_packets.rx
ns2.collectd.interface-bond0.if_packets.tx

Please help me to set correct regex to get it match.

Body:
I finally realized what the problem is! I take a look to /var/log/carbon/creates.log and found that my metrics for collecd is stored as ns2/collectd.* - "hostname"+"/"+"collectd" - because in configuration of collectd on DNS-servers there was an option Postfix "/collectd" that make this.

05/06/2017 09:54:22 :: creating database file /var/lib/graphite/whisper/ns2/collectd/cpu-1/cpu-idle.wsp (archive=[(60, 1440)] xff=None agg=None)
05/06/2017 09:54:22 :: new metric ns2/collectd.disk-sda.disk_octets.write matched schema default_1min_for_1day
05/06/2017 09:54:22 :: new metric ns2/collectd.disk-sda.disk_octets.write matched aggregation schema default

So the solution was to make regex look like this: pattern = ^ns[1-2]\/collectd\.* - escaped "/" - character
and then I deleted old metrics and new metric files was created with correct retentions!

05/06/2017 11:32:12 :: creating database file /var/lib/graphite/whisper/ns2/collectd/df-boot-efi/df_complex-free.wsp (archive=[(60, 10080), (600, 105120)] xff=None agg=None)
05/06/2017 11:32:12 :: new metric ns2/collectd.interface-eth0.if_errors.tx matched schema ns.servers
05/06/2017 11:32:12 :: new metric ns2/collectd.interface-eth0.if_errors.tx matched aggregation schema default


问:
Can't install Laravel (Windows)
```<code>  C:\Users\User>composer global require "laravel/installer"
Changed current directory to C:/Users/User/AppData/Roaming/Composer
You are running Composer with SSL/TLS protection disabled.
Warning: Accessing packagist.org over http which is an insecure protocol.
Using version ^1.3 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Warning: Accessing packagist.org over http which is an insecure protocol.
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - guzzle/guzzle v3.9.3 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.9.2 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.9.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.9.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.8.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.8.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - rackspace/php-opencloud dev-master requires guzzle/guzzle ~3.8 -> satisfiable by guzzle/guzzle[v3.8.0, v3.8.1, v3.9.0, v3.9.1, v3.9.2, v3.9.3].
    - Installation request for rackspace/php-opencloud dev-master -> satisfiable by rackspace/php-opencloud[dev-master].
</code>```

Can't install Laravel 5.4 on Windows, I am a beginer at beck-end, so I never worked with composer before, I install php and composer, unpack curl to the root directory, but I have an error.

答:
You have not php curl extension.

```<code>[Install curl for windows][1]
</code>```

1:
  How do I install cURL on Windows?

And you should add question in russion language to stack overflow for russian. Stack on russian

Title: Can't install Laravel (Windows)

Body:
  C:\Users\User>composer global require "laravel/installer"
Changed current directory to C:/Users/User/AppData/Roaming/Composer
You are running Composer with SSL/TLS protection disabled.
Warning: Accessing packagist.org over http which is an insecure protocol.
Using version ^1.3 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Warning: Accessing packagist.org over http which is an insecure protocol.
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - guzzle/guzzle v3.9.3 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.9.2 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.9.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.9.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.8.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - guzzle/guzzle v3.8.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - rackspace/php-opencloud dev-master requires guzzle/guzzle ~3.8 -> satisfiable by guzzle/guzzle[v3.8.0, v3.8.1, v3.9.0, v3.9.1, v3.9.2, v3.9.3].
    - Installation request for rackspace/php-opencloud dev-master -> satisfiable by rackspace/php-opencloud[dev-master].

Can't install Laravel 5.4 on Windows, I am a beginer at beck-end, so I never worked with composer before, I install php and composer, unpack curl to the root directory, but I have an error.

Body:
You have not php curl extension.

[Install curl for windows][1]

1:
  How do I install cURL on Windows?

And you should add question in russion language to stack overflow for russian. Stack on russian


问:
How can I remove "/url?q=" from text data in R
I want to remove "/url?q=" from text data in R Studio.
This is my code for google search:

```<code>## Code for Google Search
# Enter Search Term Here
 search.term <- "r-project"
# Creating Function
 getGoogleURL <- function(search.term, domain = '.co.in', quotes=TRUE)
{
   # Getting Search Term
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='')
   # Putting Search Term in Google Search
    getGoogleURL <- paste('http://www.google', domain, '/search?q=', search.term, sep='') }

## Get Links from Google Search
# Creating Function to Get URLs From Search Results
 getGoogleLinks <- function(google.url) {
  # Creating a File to Save URLs
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R(3.4.0)"))
  # Removing HTML code and Setting Nodes
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]])) }

## Remove quoted text, Create URL List
  quotes <- "FALSE"
  search.url <- getGoogleURL(search.term=search.term, quotes=quotes)
  links <- getGoogleLinks(search.url)

## Print URL List
  links
</code>```

And my result is:

[1] "/url?q=https://www.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQFggUMAA&usg=AFQjCNEqtiOAIA7OOTa3meWC8zaTjjTy8A"

  [2] "/url?q=http://www.cran.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQjBAIGzAB&usg=AFQjCNF8QmYbLzG0c66QZM2wsXF1n1-9tQ"

What can I do to remove "/url?q=" from the links above?

答:
You can use gsub.</p>

```<code>## Code for Google Search
# Enter Search Term Here
 search.term <- "r-project"
# Creating Function
 getGoogleURL <- function(search.term, domain = '.co.in', quotes=TRUE)
{
   # Getting Search Term
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='')
   # Putting Search Term in Google Search
    getGoogleURL <- paste('http://www.google', domain, '/search?q=', search.term, sep='') }

## Get Links from Google Search
# Creating Function to Get URLs From Search Results
 getGoogleLinks <- function(google.url) {
  # Creating a File to Save URLs
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R(3.4.0)"))
  # Removing HTML code and Setting Nodes
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]])) }

## Remove quoted text, Create URL List
  quotes <- "FALSE"
  search.url <- getGoogleURL(search.term=search.term, quotes=quotes)
  links <- getGoogleLinks(search.url)

## Print URL List
  gsub("/url?q=", "", links)
</code>```

Body:
I want to remove "/url?q=" from text data in R Studio.
This is my code for google search:

## Code for Google Search
# Enter Search Term Here
 search.term <- "r-project"
# Creating Function
 getGoogleURL <- function(search.term, domain = '.co.in', quotes=TRUE)
{
   # Getting Search Term
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='')
   # Putting Search Term in Google Search
    getGoogleURL <- paste('http://www.google', domain, '/search?q=', search.term, sep='') }

## Get Links from Google Search
# Creating Function to Get URLs From Search Results
 getGoogleLinks <- function(google.url) {
  # Creating a File to Save URLs
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R(3.4.0)"))
  # Removing HTML code and Setting Nodes
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]])) }

## Remove quoted text, Create URL List
  quotes <- "FALSE"
  search.url <- getGoogleURL(search.term=search.term, quotes=quotes)
  links <- getGoogleLinks(search.url)

## Print URL List
  links

And my result is:

[1] "/url?q=https://www.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQFggUMAA&usg=AFQjCNEqtiOAIA7OOTa3meWC8zaTjjTy8A"

  [2] "/url?q=http://www.cran.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQjBAIGzAB&usg=AFQjCNF8QmYbLzG0c66QZM2wsXF1n1-9tQ"

What can I do to remove "/url?q=" from the links above?

Body:
You can use gsub.

## Code for Google Search
# Enter Search Term Here
 search.term <- "r-project"
# Creating Function
 getGoogleURL <- function(search.term, domain = '.co.in', quotes=TRUE)
{
   # Getting Search Term
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='')
   # Putting Search Term in Google Search
    getGoogleURL <- paste('http://www.google', domain, '/search?q=', search.term, sep='') }

## Get Links from Google Search
# Creating Function to Get URLs From Search Results
 getGoogleLinks <- function(google.url) {
  # Creating a File to Save URLs
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R(3.4.0)"))
  # Removing HTML code and Setting Nodes
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]])) }

## Remove quoted text, Create URL List
  quotes <- "FALSE"
  search.url <- getGoogleURL(search.term=search.term, quotes=quotes)
  links <- getGoogleLinks(search.url)

## Print URL List
  gsub("/url?q=", "", links)


问:
PHP - Do (and echo) operation only when remainder from is 0 - Going into infinite loop
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

```<code>$x = mt_rand(1,10);
$y = mt_rand(1,10);
</code>```

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

```<code><?php

function hello(){
      echo "Hello!";
}

hello();
?>
</code>```

Why not up the ante as I said before and use it, so I mix the up:

```<code><?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>
</code>```

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

答:
In the "It doesn't work" link that you posted, you're not calling the function foo().

A couple of notes:

y may be zero so you might get a "divide by zero" error.

You are using recursion and a majority of the time your code would go into the else case. If your nesting depth gets large, you might encounter a stack overflow.

ContentLicense: CC BY-SA 2.5

Body:
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

$x = mt_rand(1,10);
$y = mt_rand(1,10);

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

<?php

function hello(){
      echo "Hello!";
}

hello();
?>

Why not up the ante as I said before and use it, so I mix the up:

<?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)


问:
Adding a button to a popup content in javascript
I'm trying to add a button to a popup content and then control the button elsewhere but the button seems to not function properly. The function of the button works fine without binding it with the button.    </p>

```<code>var popupContent = "<br><button class='btn' id='btn_del' type='submit'>del</button>";
$("#btn_del").click(function() {
    console.log("test");
    layer.setStyle(test);
})
</code>```

答:
You can change your event-binding to this:

```<code>$("body").on("click", "#btn_del", function() {
  console.log("test");
  layer.setStyle(test);
});
</code>```

Example:

$('body').on('click', '.btn', function() {
  $('body').append('<button class="btn">Add another button!</button>
');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Add another button!</button><br/></code>```

This is useful for binding events to elements that does not yet exist in the DOM, but will exist at some given point.

Body:
I'm trying to add a button to a popup content and then control the button elsewhere but the button seems to not function properly. The function of the button works fine without binding it with the button.

var popupContent = "
<button class='btn' id='btn_del' type='submit'>del</button>";
$("#btn_del").click(function() {
    console.log("test");
    layer.setStyle(test);
})

Body:
You can change your event-binding to this:

$("body").on("click", "#btn_del", function() {
  console.log("test");
  layer.setStyle(test);
});

Example:

$('body').on('click', '.btn', function() {
  $('body').append('<button class="btn">Add another button!</button><br/>');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Add another button!</button><br/>

This is useful for binding events to elements that does not yet exist in the DOM, but will exist at some given point.


问:
String equality in generic class
What is the difference between == and Equals in generic class if T is a string.

I prepared sample code with 2 tests. TestMethod1 fails on 2nd assert, but TestMethod2 passes.

Source code:

```<code>[TestFixture]
public class Test
{
    class Foo<T> where T : class
    {
        public static bool Foo1(T item1, T item2)
        {
            return item1 == item2;
        }

        public static bool Foo2(T item1, T item2)
        {
            return item1.Equals(item2);
        }
    }

    [TestCase]
    public void TestMethod1()
    {
        var name = "str" + 1;
        // passes
        Assert.IsTrue(Foo<string>.Foo2(name, "str1"));
        // fails !
        Assert.IsTrue(Foo<string>.Foo1(name, "str1"));
    }

    [TestCase]
    public void TestMethod2()
    {
        // passes
        Assert.IsTrue(Foo<string>.Foo2("str1", "str1"));
        // also passes!
        Assert.IsTrue(Foo<string>.Foo1("str1", "str1"));
    }
}
</code>```

Related question:
c# compare two generic values

答:
Using == in this case resolves to System.Reference.Equals.

.Equals is a virtual method so the overridden version will be used, in this case it will be content comparison for string.

The first test compares a local variable to a literal (interned) string.

The second test compares the same interned string so both == and Equals return true.

If you change your TestMethod1() to this:

```<code>        Assert.IsTrue(Foo<string>.Foo1(name, name));
</code>```

it will pass because you are comparing the same object, so the reference equality returns true.

Edit: If we add this method:

```<code>    public static bool Foo3(string item1, string item2)
    {
        return item1 == item2;
    }
</code>```

Then the following test will return true:

```<code>    Assert.IsTrue(Foo<string>.Foo3(name, "str1"));
</code>```

because C# will resolve == in this case to the string value check.

This question is really a duplicate of this, with additional generic complexity.

Edit 2:
OK, time to dive into the MSIL. Foo1 looks like this:

```<code>.method public hidebysig static bool  Foo1(!T item1,
                                           !T item2) cil managed
{
  // Code size       20 (0x14)
  .maxstack  2
  .locals init ([0] bool V_0)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  box        !T
  IL_0007:  ldarg.1
  IL_0008:  box        !T
  IL_000d:  ceq
  IL_000f:  stloc.0
  IL_0010:  br.s       IL_0012
  IL_0012:  ldloc.0
  IL_0013:  ret
} // end of method Foo`1::Foo1
</code>```

You can see here it is using ceq which is Push 1 (of type int32) if value1 equals value2, else push 0.

Here is Foo2:

```<code>.method public hidebysig static bool  Foo2(!T item1,
                                           !T item2) cil managed
{
  // Code size       23 (0x17)
  .maxstack  2
  .locals init ([0] bool V_0)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  box        !T
  IL_0007:  ldarg.1
  IL_0008:  box        !T
  IL_000d:  callvirt   instance bool [mscorlib]System.Object::Equals(object)
  IL_0012:  stloc.0
  IL_0013:  br.s       IL_0015
  IL_0015:  ldloc.0
  IL_0016:  ret
} // end of method Foo`1::Foo2
</code>```

This uses System.Object::Equals - this is the virtual method and behaves as such, being overridden in the concrete type of the parameter - in this case string.

Foo3 (which I added, which uses == on declared string parameters) looks like this:

```<code>.method public hidebysig static bool  Foo3(string item1,
                                           string item2) cil managed
{
  // Code size       13 (0xd)
  .maxstack  2
  .locals init ([0] bool V_0)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldarg.1
  IL_0003:  call       bool [mscorlib]System.String::op_Equality(string,
                                                                 string)
  IL_0008:  stloc.0
  IL_0009:  br.s       IL_000b
  IL_000b:  ldloc.0
  IL_000c:  ret
} // end of method Foo`1::Foo3
</code>```

Here we observe explicit use of the System.String::op_Equality(string, string) which is the string value check comparison.

Title: String equality in generic class

Body:
What is the difference between == and Equals in generic class if T is a string.

I prepared sample code with 2 tests. TestMethod1 fails on 2nd assert, but TestMethod2 passes.

Source code:

[TestFixture]
public class Test
{
    class Foo<T> where T : class
    {
        public static bool Foo1(T item1, T item2)
        {
            return item1 == item2;
        }

        public static bool Foo2(T item1, T item2)
        {
            return item1.Equals(item2);
        }
    }

    [TestCase]
    public void TestMethod1()
    {
        var name = "str" + 1;
        // passes
        Assert.IsTrue(Foo<string>.Foo2(name, "str1"));
        // fails !
        Assert.IsTrue(Foo<string>.Foo1(name, "str1"));
    }

    [TestCase]
    public void TestMethod2()
    {
        // passes
        Assert.IsTrue(Foo<string>.Foo2("str1", "str1"));
        // also passes!
        Assert.IsTrue(Foo<string>.Foo1("str1", "str1"));
    }
}

Related question:
c# compare two generic values

Body:
Using == in this case resolves to System.Reference.Equals.

.Equals is a virtual method so the overridden version will be used, in this case it will be content comparison for string.

The first test compares a local variable to a literal (interned) string.

The second test compares the same interned string so both == and Equals return true.

If you change your TestMethod1() to this:

        Assert.IsTrue(Foo<string>.Foo1(name, name));

it will pass because you are comparing the same object, so the reference equality returns true.

Edit: If we add this method:

    public static bool Foo3(string item1, string item2)
    {
        return item1 == item2;
    }

Then the following test will return true:

    Assert.IsTrue(Foo<string>.Foo3(name, "str1"));

because C# will resolve == in this case to the string value check.

This question is really a duplicate of this, with additional generic complexity.

Edit 2:
OK, time to dive into the MSIL. Foo1 looks like this:

.method public hidebysig static bool  Foo1(!T item1,
                                           !T item2) cil managed
{
  // Code size       20 (0x14)
  .maxstack  2
  .locals init ([0] bool V_0)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  box        !T
  IL_0007:  ldarg.1
  IL_0008:  box        !T
  IL_000d:  ceq
  IL_000f:  stloc.0
  IL_0010:  br.s       IL_0012
  IL_0012:  ldloc.0
  IL_0013:  ret
} // end of method Foo`1::Foo1

You can see here it is using ceq which is Push 1 (of type int32) if value1 equals value2, else push 0.

Here is Foo2:

.method public hidebysig static bool  Foo2(!T item1,
                                           !T item2) cil managed
{
  // Code size       23 (0x17)
  .maxstack  2
  .locals init ([0] bool V_0)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  box        !T
  IL_0007:  ldarg.1
  IL_0008:  box        !T
  IL_000d:  callvirt   instance bool [mscorlib]System.Object::Equals(object)
  IL_0012:  stloc.0
  IL_0013:  br.s       IL_0015
  IL_0015:  ldloc.0
  IL_0016:  ret
} // end of method Foo`1::Foo2

This uses System.Object::Equals - this is the virtual method and behaves as such, being overridden in the concrete type of the parameter - in this case string.

Foo3 (which I added, which uses == on declared string parameters) looks like this:

.method public hidebysig static bool  Foo3(string item1,
                                           string item2) cil managed
{
  // Code size       13 (0xd)
  .maxstack  2
  .locals init ([0] bool V_0)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldarg.1
  IL_0003:  call       bool [mscorlib]System.String::op_Equality(string,
                                                                 string)
  IL_0008:  stloc.0
  IL_0009:  br.s       IL_000b
  IL_000b:  ldloc.0
  IL_000c:  ret
} // end of method Foo`1::Foo3

Here we observe explicit use of the System.String::op_Equality(string, string) which is the string value check comparison.


问:
Close material-ui dialog by onClick on an image
I'm trying to add a clickable  image to close a material-ui dialog.
The props.onRequestClose works properly when I click outside the dialog but the onClick doesn't response.

What am I missing?

```<code>const ChangePasswordDialog = (props) =>  (
        <Dialog open={props.open} onRequestClose={props.onRequestClose} modal={false}>
            <div className="close-popup">
                <Svg onClick={props.onRequestClose} viewBox="0 0 22.75 22.75">{closePopup}
                </Svg >
            </div>
        </Dialog>
);

ChangePasswordDialog.propTypes = {
open:PropTypes.bool.isRequired,
onRequestClose:PropTypes.func.isRequired
};
</code>```

答:
I solved it by adding a prop called onClick to the Svg components.
Here is the code for the Svg components if someone needs:</p>

```<code>class Svg extends Component{
render() {
    const {children, viewBox, onClick} = this.props;
    return(
        <div onClick={onClick}>
            <SvgIcon viewBox={viewBox}>
                {children}
            </SvgIcon>
        </div>
       )
    };
  }

Svg.propTypes = {
   children:PropTypes.any.isRequired,
   viewBox:PropTypes.string,
   onClick:PropTypes.function
 };

export default Svg;
</code>```

Body:
I'm trying to add a clickable  image to close a material-ui dialog.
The props.onRequestClose works properly when I click outside the dialog but the onClick doesn't response.

What am I missing?

const ChangePasswordDialog = (props) =>  (
        <Dialog open={props.open} onRequestClose={props.onRequestClose} modal={false}>

                <Svg onClick={props.onRequestClose} viewBox="0 0 22.75 22.75">{closePopup}
                </Svg >

        </Dialog>
);

ChangePasswordDialog.propTypes = {
open:PropTypes.bool.isRequired,
onRequestClose:PropTypes.func.isRequired
};

Body:
I solved it by adding a prop called onClick to the Svg components.
Here is the code for the Svg components if someone needs:

class Svg extends Component{
render() {
    const {children, viewBox, onClick} = this.props;
    return(
        <div onClick={onClick}>
            <SvgIcon viewBox={viewBox}>
                {children}
            </SvgIcon>
        </div>
       )
    };
  }

Svg.propTypes = {
   children:PropTypes.any.isRequired,
   viewBox:PropTypes.string,
   onClick:PropTypes.function
 };

export default Svg;


问:
JavaFX TableView Disable CheckBox
I've created a TableView which contains a checkbox column(isSelected), and three info column(name, surname, job). I want to disable some checkbox according to user info. For example, if user name is "Peter", the checkbox near the Peter will be disabled. But I couldn't. Here is some of my code:

Person.java

```<code>public class Person {

private final SimpleStringProperty name;
private final SimpleStringProperty surname;
private final SimpleStringProperty job;
private final BooleanProperty isSelected;

public Person(SimpleStringProperty name, SimpleStringProperty surname, SimpleStringProperty job,
        BooleanProperty isSelected) {
    super();
    this.name = name;
    this.surname = surname;
    this.job = job;
    this.isSelected = isSelected;
}

public SimpleStringProperty getName() {
    return name;
}

public SimpleStringProperty getSurname() {
    return surname;
}

public SimpleStringProperty getJob() {
    return job;
}

public BooleanProperty getIsSelected() {
    return isSelected;
}

}
</code>```

Controller.java

```<code>public class Controller {

@FXML
private final TableView<Person> fxPersonTableView;

@FXML
private final TableColumn<Person, Boolean> fxSelectColumnCheckbox;

@FXML
private final TableColumn<Person, String> fxNameTableColumn;

@FXML
private final TableColumn<Person, String> fxSurnameTableColumn;

@FXML
private final TableColumn<Person, String> fxJobTableColumn;

private ObservableList<Person> persons;

private void createTableView(){

    fxSelectColumnCheckbox.setCellValueFactory(c -> c.getValue().getIsSelected());

    fxSelectColumnCheckbox.setCellFactory(CheckBoxTableCell.forTableColumn(c -> {
    //I guess here I will put some control like as name check and disable
    //the checkbox in this row. But I can't reach the checkbox individually.
        return persons.get(c).getIsSelected();
    }));

    fxNameTableColumn.setCellValueFactory(c -> persons.get(c).getName());
    fxSurnameTableColumn.setCellValueFactory(c -> persons.get(c).getSurname());
    fxJobTableColumn.setCellValueFactory(c -> persons.get(c).getJob());
    fxPersonTableView.getSelectionModel.setSelectionMode(SelectionMode.MULTIPLE);
    fxPersonTableView.setItems(persons);

}

}
</code>```

答:
Thank you @Ammar, I've resolved it like this make use of your answer:</p>

```<code>fxSelectColumnCheckbox.setCellFactory(column -> {
        return new CheckBoxTableCell<Person, Boolean>() {
            @Override
            public void updateItem(Boolean item, boolean empty) {
                super.updateItem(item, empty);

                TableRow<Person> currentRow = getTableRow();
                this.setDisable(false); // it is required to fit default state
                if (currentRow.getItem() != null && !empty) {
                    if (currentRow.getItem().getName().equals("Peter")) {
                        this.setDisable(true);
                        setStyle(fxPersonTableView.getStyle());
                    }
                } else {

                    setStyle(fxPersonTableView.getStyle());
                }
            }
        };
    });
</code>```

Title: JavaFX TableView Disable CheckBox

Body:
I've created a TableView which contains a checkbox column(isSelected), and three info column(name, surname, job). I want to disable some checkbox according to user info. For example, if user name is "Peter", the checkbox near the Peter will be disabled. But I couldn't. Here is some of my code:

Person.java

public class Person {

private final SimpleStringProperty name;
private final SimpleStringProperty surname;
private final SimpleStringProperty job;
private final BooleanProperty isSelected;

public Person(SimpleStringProperty name, SimpleStringProperty surname, SimpleStringProperty job,
        BooleanProperty isSelected) {
    super();
    this.name = name;
    this.surname = surname;
    this.job = job;
    this.isSelected = isSelected;
}

public SimpleStringProperty getName() {
    return name;
}

public SimpleStringProperty getSurname() {
    return surname;
}

public SimpleStringProperty getJob() {
    return job;
}

public BooleanProperty getIsSelected() {
    return isSelected;
}

}

Controller.java

public class Controller {

@FXML
private final TableView<Person> fxPersonTableView;

@FXML
private final TableColumn<Person, Boolean> fxSelectColumnCheckbox;

@FXML
private final TableColumn<Person, String> fxNameTableColumn;

@FXML
private final TableColumn<Person, String> fxSurnameTableColumn;

@FXML
private final TableColumn<Person, String> fxJobTableColumn;

private ObservableList<Person> persons;

private void createTableView(){

    fxSelectColumnCheckbox.setCellValueFactory(c -> c.getValue().getIsSelected());

    fxSelectColumnCheckbox.setCellFactory(CheckBoxTableCell.forTableColumn(c -> {
    //I guess here I will put some control like as name check and disable
    //the checkbox in this row. But I can't reach the checkbox individually.
        return persons.get(c).getIsSelected();
    }));

    fxNameTableColumn.setCellValueFactory(c -> persons.get(c).getName());
    fxSurnameTableColumn.setCellValueFactory(c -> persons.get(c).getSurname());
    fxJobTableColumn.setCellValueFactory(c -> persons.get(c).getJob());
    fxPersonTableView.getSelectionModel.setSelectionMode(SelectionMode.MULTIPLE);
    fxPersonTableView.setItems(persons);

}

}

Body:
Thank you @Ammar, I've resolved it like this make use of your answer:

fxSelectColumnCheckbox.setCellFactory(column -> {
        return new CheckBoxTableCell<Person, Boolean>() {
            @Override
            public void updateItem(Boolean item, boolean empty) {
                super.updateItem(item, empty);

                TableRow<Person> currentRow = getTableRow();
                this.setDisable(false); // it is required to fit default state
                if (currentRow.getItem() != null && !empty) {
                    if (currentRow.getItem().getName().equals("Peter")) {
                        this.setDisable(true);
                        setStyle(fxPersonTableView.getStyle());
                    }
                } else {

                    setStyle(fxPersonTableView.getStyle());
                }
            }
        };
    });


问:
Selecting distinct keys and their counts from a dictionary series in python
I have a pandas dictionary series, that takes the values like

```<code>   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}
</code>```

I want to create a dictionary out of it based on the key and its occurrence in series, like:

```<code>{AA:3,BB:2,CC:1,CD:1}
</code>```

答:
Turn your series in to a series of lists of keys, sum those creating a single list of keys, and use a Counter:

```<code>In [23]: pd.Series([{'AA':25,'BB':31},{'CC':45,'AA':3},{'BB':3,'CD':4,'AA':5}])
Out[23]:
0           {'AA': 25, 'BB': 31}
1            {'AA': 3, 'CC': 45}
2    {'CD': 4, 'AA': 5, 'BB': 3}
dtype: object

In [24]: series = _

In [34]: from collections import Counter

In [35]: Counter(series.apply(lambda x: list(x.keys())).sum())
Out[35]: Counter({'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1})
</code>```

Or using generator expressions and flattening:

```<code>In [37]: Counter(k for d in series for k in d.keys())
Out[37]: Counter({'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1})
</code>```

Body:
I have a pandas dictionary series, that takes the values like

   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}

I want to create a dictionary out of it based on the key and its occurrence in series, like:

{AA:3,BB:2,CC:1,CD:1}

Body:
Turn your series in to a series of lists of keys, sum those creating a single list of keys, and use a Counter:

In [23]: pd.Series([{'AA':25,'BB':31},{'CC':45,'AA':3},{'BB':3,'CD':4,'AA':5}])
Out[23]:
0           {'AA': 25, 'BB': 31}
1            {'AA': 3, 'CC': 45}
2    {'CD': 4, 'AA': 5, 'BB': 3}
dtype: object

In [24]: series = _

In [34]: from collections import Counter

In [35]: Counter(series.apply(lambda x: list(x.keys())).sum())
Out[35]: Counter({'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1})

Or using generator expressions and flattening:

In [37]: Counter(k for d in series for k in d.keys())
Out[37]: Counter({'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1})


问:
Reading Oracle Explain plan
```<code>explain plan for
    SELECT * FROM schema2.mv_a_data mv
      WHERE mv.routing_code_type_id    = 3
      AND mv.static_data_status_id    IN(5, 8)
      AND mv.acct_currency_ind_id NOT IN
         (SELECT DISTINCT te.acct_currency_ind_id
          FROM schema1.tem_ele te
          WHERE te.lis_tem_id IN
                  (SELECT lis_tem_id
                   FROM schema1.lis_tem
                   WHERE lis_tem.template_type_id = 2
                   AND lis_tem.deleted_flag       = 'N'      )
      AND te.acct_currency_ind_id IS NOT NULL
    )
 ORDER BY mv.treasury_region_code,
          mv.legal_entity_mnemonic,
          mv.currency_code;

 select *
 from TABLE(DBMS_XPLAN.DISPLAY('PLAN_TABLE', null,'ADVANCED'));
</code>```

------------------------------------------------------------------------------------
|  Id  | Operation             | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT       |           |   892 |   318K|    69   (2)| 00:00:01 |
|   1 |  SORT ORDER BY         |           |   892 |   318K|    69   (2)| 00:00:01 |
|*  2 |   HASH JOIN RIGHT ANTI |           |   892 |   318K|    68   (0)| 00:00:01 | `
|   3 |    VIEW                | VW_NSO_1  |  1457 |  8742 |    11  (0) | 00:00:01 |
|*  4 |     HASH JOIN          |           |  1457 | 33511 |    11   (0)| 00:00:01 |
|*  5 |      TABLE ACCESS FULL | lis_tem   |   100 |  1100 |     3   (0)| 00:00:01 |
|*  6 |      TABLE ACCESS FULL | tem_ele   |  3271 | 39252 |     8   (0)| 00:00:01 |
|*  7 |    MAT_VIEW ACCESS FULL| mv_a_data |  2348 |   825K|    57   (0)| 00:00:01 |
```

I am trying to read the given explain plan. After looking at the explain plan and according
    to my understanding, first of all, FTS of LIS_TEM table and TEM_ELE are done and then they are joined using HASH JOIN.

Question 1 - can I change this HASH JOIN to NESTED LOOP?

I am asking just for learning purpose. I know HASH JOIN is good here.
        After HASH JOIN, I guess it is going to ID3 ie VIEW VW_NSO_1 and ID7 MAT_VIEW.

Question 2 - what is this VIEW VW_NSO_1, which clause of the SQL query was responsible to brought it here?

Question 3 - How I will read the rest of the plan?

Question 4 - Why HASH JOIN RIGHT ANTI came in picture?

Please assist me to understand the above explain plan in detail. Thanks and let me know if you need any further details.

答:
"can I change this HASH JOIN to NESTED LOOP?"

You can try the use_nl hint. Find out more

"what is this VIEW VW_NSO_1, which clause of the SQL query was responsible to brought it here?"

VW_NSO_1 indicates the unnesting of the IN sub-query into a view. That is because your sub-query uses DISTINCT, so guarantees a unique set. This operation isn't documented in the 11g docs but you can find it in the older Tuning Guides.

"How I will read the rest of the plan?"

Ummm, with due attention to detail? Basically all the tables involved are small enough and lack helpful indexes, so the optimizer has plumped for Full table Scans.

"Why HASH JOIN RIGHT ANTI came in picture?"

Think of the NOT IN sub-query as a sort of an outer join. You want records in the MView which don't match rows in the sub-query - an anti-join. In your query that would be a LEFT OUTER JOIN. However, the optimizer has decided it would be more efficient to gather the result set of the sub-query first than evaluate the anti-join on the MView, which is a right outer join. Dion Cho wrote a very good piece on this. Find out more.

Title: Reading Oracle Explain plan

Body:
explain plan for
    SELECT * FROM schema2.mv_a_data mv
      WHERE mv.routing_code_type_id    = 3
      AND mv.static_data_status_id    IN(5, 8)
      AND mv.acct_currency_ind_id NOT IN
         (SELECT DISTINCT te.acct_currency_ind_id
          FROM schema1.tem_ele te
          WHERE te.lis_tem_id IN
                  (SELECT lis_tem_id
                   FROM schema1.lis_tem
                   WHERE lis_tem.template_type_id = 2
                   AND lis_tem.deleted_flag       = 'N'      )
      AND te.acct_currency_ind_id IS NOT NULL
    )
 ORDER BY mv.treasury_region_code,
          mv.legal_entity_mnemonic,
          mv.currency_code;

 select *
 from TABLE(DBMS_XPLAN.DISPLAY('PLAN_TABLE', null,'ADVANCED'));

------------------------------------------------------------------------------------
|  Id  | Operation             | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT       |           |   892 |   318K|    69   (2)| 00:00:01 |
|   1 |  SORT ORDER BY         |           |   892 |   318K|    69   (2)| 00:00:01 |
|*  2 |   HASH JOIN RIGHT ANTI |           |   892 |   318K|    68   (0)| 00:00:01 | `
|   3 |    VIEW                | VW_NSO_1  |  1457 |  8742 |    11  (0) | 00:00:01 |
|*  4 |     HASH JOIN          |           |  1457 | 33511 |    11   (0)| 00:00:01 |
|*  5 |      TABLE ACCESS FULL | lis_tem   |   100 |  1100 |     3   (0)| 00:00:01 |
|*  6 |      TABLE ACCESS FULL | tem_ele   |  3271 | 39252 |     8   (0)| 00:00:01 |
|*  7 |    MAT_VIEW ACCESS FULL| mv_a_data |  2348 |   825K|    57   (0)| 00:00:01 |

I am trying to read the given explain plan. After looking at the explain plan and according
    to my understanding, first of all, FTS of LIS_TEM table and TEM_ELE are done and then they are joined using HASH JOIN.

Question 1 - can I change this HASH JOIN to NESTED LOOP?

I am asking just for learning purpose. I know HASH JOIN is good here.
        After HASH JOIN, I guess it is going to ID3 ie VIEW VW_NSO_1 and ID7 MAT_VIEW.

Question 2 - what is this VIEW VW_NSO_1, which clause of the SQL query was responsible to brought it here?

Question 3 - How I will read the rest of the plan?

Question 4 - Why HASH JOIN RIGHT ANTI came in picture?

Please assist me to understand the above explain plan in detail. Thanks and let me know if you need any further details.


问:
Supervisord - program number as a parameter
I have a set of programs managed by supervisord. There is a program, let's call it myprogram, which I need to run in 15 instances. That's easy with the numprocs parameter.

Is there a way to pass the process number as a command line agrument to the program, so that each instance is aware of its number?

I need to achieve the same thing as if I run in command line:

```<code>$ myprogram 1
$ myprogram 2
$ myprogram 3
$ myprogram 4
....
</code>```

答:
you can also  use an envionment variable:
like this:

```<code>environment=num=%(process_num)02d
</code>```

You can then use a getenv() function to get the process number. I usually prefer this method because I prefere reserving parameters to fonctional matters.

Body:
I have a set of programs managed by supervisord. There is a program, let's call it myprogram, which I need to run in 15 instances. That's easy with the numprocs parameter.

Is there a way to pass the process number as a command line agrument to the program, so that each instance is aware of its number?

I need to achieve the same thing as if I run in command line:

$ myprogram 1
$ myprogram 2
$ myprogram 3
$ myprogram 4
....

Body:
you can also  use an envionment variable:
like this:

environment=num=%(process_num)02d

You can then use a getenv() function to get the process number. I usually prefer this method because I prefere reserving parameters to fonctional matters.


问:
Symfony2: don't update image in db, if it's empty
I have 2 fields logo and images, which I use for storing images. In db they are represented as strings.

```<code>   /**
     * @ORM\PrePersist
     */
    public function preUpload()
    {
        if ($this->logo !== null) {
            $image_name = uniqid().'.'.$this->logo->guessExtension();
            if($image_name) {
                $this->logo->move($this->getUploadRootDir(), $image_name);
                unset($this->logo);
                $this->logo = $image_name;
            }
            else{
                unset($this->logo);
            }
        }
        if(is_array($this->images) && !empty($this->images)){
            $images = array();
            foreach($this->images as $image){
                if($image) {
                    $image_name = uniqid() . '.' . $image->guessExtension();
                    $image->move($this->getUploadRootDir(), $image_name);
                    $images[] = $image_name;
                }
            }
            if($images){
                $this->images = json_encode($images);
            }
        }
    }
</code>```

Good.orm.yml

```<code>lifecycleCallbacks:
            prePersist: [ preUpload, setCreatedAtValue]
            preUpdate: [ preUpload, setUpdatedAtValue ]
</code>```

Here I move images in right folders and after assign this vars string values. It works well. But I have one problem. If I update another fields, and don't upload new image, I will have empty image fields in db. Symfony erases this fields. How can I change this behavior?

Creation form:

```<code>       /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('name')
                ->add('logo', FileType::class, array('required' => false, 'data_class' => null))
                ->add('description', TextareaType::class)
                ->add('images', FileType::class, array('attr' => array("multiple" => "multiple"), 'data_class' => null, 'required' => false))
                ->add('price')
                ->add('is_active')
                ->add('category');
        }
</code>```

Edit action

```<code>/**
 * Displays a form to edit an existing good entity.
 *
 */
public function editAction(Request $request, Good $good)
{
    $deleteForm = $this->createDeleteForm($good);
    $editForm = $this->createForm('Shop\ShopBundle\Form\GoodType', $good);
    $editForm->handleRequest($request);
    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $this->getDoctrine()->getManager()->flush();
        //return $this->redirectToRoute('app_good_edit', array('id' => $good->getId()));
    }
    $form_edit = $editForm->createView();

    //\Doctrine\Common\Util\Debug::dump($form_edit->children['images']->vars);

    $form_edit->children['images']->vars = array_replace($form_edit->children['images']->vars, array('full_name' => 'shop_shopbundle_good[images][]'));
    return $this->render('ShopShopBundle:good:edit.html.twig', array(
        'good' => $good,
        'edit_form' => $form_edit,
        'delete_form' => $deleteForm->createView(),
    ));
}
</code>```

答:
A simple work around is the retrive, in the case of image field of the form is empy, the old value from the db.
Something like this:

```<code>if ($editForm->isSubmitted() && $editForm->isValid()) {
    $goodSubmitted = $editForm->getData();
    if(empty($goodSubmitted->getImages()) {
        $goodSaved = $this->getDoctrine()->getManager()->getRepository("good repository name here")->find($goodSubmitted->getId());
        $goodSubmitted->setImages($goodSaved->getImages());
    }
    $this->getDoctrine()->getManager()->flush();
}
</code>```

I don't know your entity structure, this is just an idea.

If you want to edit in order to add an image, you have to handle that too.

However, this could be painful. My advice is to keep things simple: create one entity for all images and link to your Good entity with a proper relationship.
I've found that article describing the above structure.

Body:
I have 2 fields logo and images, which I use for storing images. In db they are represented as strings.

   /**
     * @ORM\PrePersist
     */
    public function preUpload()
    {
        if ($this->logo !== null) {
            $image_name = uniqid().'.'.$this->logo->guessExtension();
            if($image_name) {
                $this->logo->move($this->getUploadRootDir(), $image_name);
                unset($this->logo);
                $this->logo = $image_name;
            }
            else{
                unset($this->logo);
            }
        }
        if(is_array($this->images) && !empty($this->images)){
            $images = array();
            foreach($this->images as $image){
                if($image) {
                    $image_name = uniqid() . '.' . $image->guessExtension();
                    $image->move($this->getUploadRootDir(), $image_name);
                    $images[] = $image_name;
                }
            }
            if($images){
                $this->images = json_encode($images);
            }
        }
    }

Good.orm.yml

lifecycleCallbacks:
            prePersist: [ preUpload, setCreatedAtValue]
            preUpdate: [ preUpload, setUpdatedAtValue ]

Here I move images in right folders and after assign this vars string values. It works well. But I have one problem. If I update another fields, and don't upload new image, I will have empty image fields in db. Symfony erases this fields. How can I change this behavior?

Creation form:

       /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('name')
                ->add('logo', FileType::class, array('required' => false, 'data_class' => null))
                ->add('description', TextareaType::class)
                ->add('images', FileType::class, array('attr' => array("multiple" => "multiple"), 'data_class' => null, 'required' => false))
                ->add('price')
                ->add('is_active')
                ->add('category');
        }

Edit action

/**
 * Displays a form to edit an existing good entity.
 *
 */
public function editAction(Request $request, Good $good)
{
    $deleteForm = $this->createDeleteForm($good);
    $editForm = $this->createForm('Shop\ShopBundle\Form\GoodType', $good);
    $editForm->handleRequest($request);
    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $this->getDoctrine()->getManager()->flush();
        //return $this->redirectToRoute('app_good_edit', array('id' => $good->getId()));
    }
    $form_edit = $editForm->createView();

    //\Doctrine\Common\Util\Debug::dump($form_edit->children['images']->vars);

    $form_edit->children['images']->vars = array_replace($form_edit->children['images']->vars, array('full_name' => 'shop_shopbundle_good[images][]'));
    return $this->render('ShopShopBundle:good:edit.html.twig', array(
        'good' => $good,
        'edit_form' => $form_edit,
        'delete_form' => $deleteForm->createView(),
    ));
}

Body:
A simple work around is the retrive, in the case of image field of the form is empy, the old value from the db.
Something like this:

if ($editForm->isSubmitted() && $editForm->isValid()) {
    $goodSubmitted = $editForm->getData();
    if(empty($goodSubmitted->getImages()) {
        $goodSaved = $this->getDoctrine()->getManager()->getRepository("good repository name here")->find($goodSubmitted->getId());
        $goodSubmitted->setImages($goodSaved->getImages());
    }
    $this->getDoctrine()->getManager()->flush();
}

I don't know your entity structure, this is just an idea.

If you want to edit in order to add an image, you have to handle that too.

However, this could be painful. My advice is to keep things simple: create one entity for all images and link to your Good entity with a proper relationship.
I've found that article describing the above structure.


问:
Close a specific window(frame) in opencv2. Using python
I have this kind of code at the end of my whole code . This is the command to close the window when i click on letter 'e'

```<code>if   cv2.waitKey(0) & 0xFF == ord("e") :
     cv2.destroyWindow('Train Device')
break
</code>```

I just want to close only a specific window when i am clicking on the letter (e) but when i use this one it close everything all the frames and not only the specific one. 'Train Device' is name of my window. When am i doing wrong?

答: I think the problem is that the break must be aligned inside the if, to be performed only in the case the condition is satisfied. If not, it will break at first step of your execution.

Body:
I have this kind of code at the end of my whole code . This is the command to close the window when i click on letter 'e'

if   cv2.waitKey(0) & 0xFF == ord("e") :
     cv2.destroyWindow('Train Device')
break

I just want to close only a specific window when i am clicking on the letter (e) but when i use this one it close everything all the frames and not only the specific one. 'Train Device' is name of my window. When am i doing wrong?


问:
Wrong positions of group bars in plot
Trying to draw group bar plot using MatPlotLib but positions of my bars is wrong.

So, I have a data:

```<code>groups = [
    np.array([ group1.count(0), group1.count(1) ]),
    np.array([ group2.count(0), group2.count(1) ]),
]
</code>```

The group is [[1, 3], [0, 5]], and that means that each group has two colors. In first group just 1 people choose the first color, and other 3 people choose the second color. I am trying to draw it but positions of bars are wrong: 3 from the first group moved to the second group and so on.

Where is my mistake and why that happens?

The code to draw the data:

```<code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

def draw(groups):
    group_labels = ['G1', 'G2']
    num_items = len(group_labels)
    ind = np.arange(num_items)
    margin = 0.05
    width = (1.-2.*margin)/num_items
    colors = ['#f5abb5', '#2fc2ef']

    s = plt.subplot(1,1,1)
    for num, vals in enumerate(groups):
        xdata = ind+margin+(num*width)
        plt.bar(xdata, vals, width, color=colors[num])
    s.set_xticks(ind+0.5)
    s.set_xticklabels(group_labels)

draw(groups)
</code>```

答:
You may transpose the input array

```<code>groups = numpy.array([[1, 3], [0, 5]]).T
</code>```

Title: Wrong positions of group bars in plot

Body:
Trying to draw group bar plot using MatPlotLib but positions of my bars is wrong.

So, I have a data:

groups = [
    np.array([ group1.count(0), group1.count(1) ]),
    np.array([ group2.count(0), group2.count(1) ]),
]

The group is [[1, 3], [0, 5]], and that means that each group has two colors. In first group just 1 people choose the first color, and other 3 people choose the second color. I am trying to draw it but positions of bars are wrong: 3 from the first group moved to the second group and so on.

Where is my mistake and why that happens?

The code to draw the data:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

def draw(groups):
    group_labels = ['G1', 'G2']
    num_items = len(group_labels)
    ind = np.arange(num_items)
    margin = 0.05
    width = (1.-2.*margin)/num_items
    colors = ['#f5abb5', '#2fc2ef']

    s = plt.subplot(1,1,1)
    for num, vals in enumerate(groups):
        xdata = ind+margin+(num*width)
        plt.bar(xdata, vals, width, color=colors[num])
    s.set_xticks(ind+0.5)
    s.set_xticklabels(group_labels)

draw(groups)

Body:
You may transpose the input array

groups = numpy.array([[1, 3], [0, 5]]).T


问:
Credit Card validation & checking
HI. I see some libraries of detecting credit card # is valid or not.  However, it is based on the algorithm, not really checking with the credit card company.

is there a way or API so that I can pass in the card name & the card # and see if they are valid and match?

also, which payment getway is good?

答:
Credit card numbers are validated against a check digit using the Luhn algorithm. The Wikipedia article includes links to implementations in a variety of languages.

See also here.

OwnerDisplayName: seatoskyhk

Title: Credit Card validation & checking

OwnerDisplayName: Dennis Williamson


问:
Return database connection from function
I'm trying to return $db connection from function, so that I could use it in another function. But someone functions don't understand $db variable.

```<code>function dbConnection(){
   $dbhost = 'localhost';
   $dbuser = '...';
   $dbpass = '...';
   $dbname = '...';

   try {
     $db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=UTF8", $dbuser, $dbpass);
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     return $db;
   } catch (PDOException $e){
     echo 'Connection failed: ' . $e->getMessage();
   }
}
</code>```

Then use it in all of my functions.

```<code>function getCurrentFile(){
   dbConnection();

   $stmt = $db->prepare(...);
   $stmt->execute();

}
</code>```

Are there more preferable way to handle db connections? I used to require_once config.php(where is only db connection) file every time, but I don't want to do it anymore.

答:
One of the options is define singletone class providing database object:

```<code>// File: DbConection.php

class DbConnection
{

    /**
     * @var \PDO
     */
    private static $pdo;

    private function __constructor()
    {

    }

    public static function getInstance()
    {
        if(null === self::$pdo) {
            self::$pdo = new \PDO('....);
        }

        return $self::pdo;
    }

    private function __clone()
    {

    }

    private function __wakeup()
    {

    }
}
</code>```

If you are using composer tool, add this line to composer.json file:

```<code>"autoload": {
    "classmap": [
        "path_to_your_file/DbConnection.php"
    ]
},
</code>```

In your project, on bootstrap include generated by composer vendor/autoload.php file and start using class by:

```<code>use DbConnection;

DbConnection::getInstance();
</code>```

in whole projec.

Body:
I'm trying to return $db connection from function, so that I could use it in another function. But someone functions don't understand $db variable.

function dbConnection(){
   $dbhost = 'localhost';
   $dbuser = '...';
   $dbpass = '...';
   $dbname = '...';

   try {
     $db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=UTF8", $dbuser, $dbpass);
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     return $db;
   } catch (PDOException $e){
     echo 'Connection failed: ' . $e->getMessage();
   }
}

Then use it in all of my functions.

function getCurrentFile(){
   dbConnection();

   $stmt = $db->prepare(...);
   $stmt->execute();

}

Are there more preferable way to handle db connections? I used to require_once config.php(where is only db connection) file every time, but I don't want to do it anymore.

Body:
One of the options is define singletone class providing database object:

// File: DbConection.php

class DbConnection
{

    /**
     * @var \PDO
     */
    private static $pdo;

    private function __constructor()
    {

    }

    public static function getInstance()
    {
        if(null === self::$pdo) {
            self::$pdo = new \PDO('....);
        }

        return $self::pdo;
    }

    private function __clone()
    {

    }

    private function __wakeup()
    {

    }
}

If you are using composer tool, add this line to composer.json file:

"autoload": {
    "classmap": [
        "path_to_your_file/DbConnection.php"
    ]
},

In your project, on bootstrap include generated by composer vendor/autoload.php file and start using class by:

use DbConnection;

DbConnection::getInstance();

in whole projec.


问:
How to make a fast QTableView with HTML-formatted and clickable cells?
I'm making a dictionary program that displays word definitions in a 3-column QTableView subclass, as user types them, taking data from a QAbstractTableModel subclass. Something like that:

I want to add various formatting to the text, I'm using QAbstractItemView::setIndexWidget to add a QLabel to each cell as data comes in:

WordView.h

```<code>#include <QTableView>

class QLabel;

class WordView : public QTableView {
    Q_OBJECT

public:
    explicit WordView(QWidget *parent = 0);

    void rowsInserted(const QModelIndex &parent, int start, int end);

private:
    void insertLabels(int row);
    void removeLabels(int row);
};
</code>```

WordView.cpp

```<code>#include <QLabel>
#include "WordView.h"

WordView::WordView(QWidget *parent) :
    QTableView(parent)
{}

void WordView::rowsInserted(const QModelIndex &parent, int start, int end) {
    QTableView::rowsInserted(parent, start, end);

    for (int row = start; row <= end; ++row) {
        insertLabels(row);
    }
}

void WordView::insertLabels(int row) {
    for (int i = 0; i < 3; ++i) {
        auto label = new QLabel(this);
        label->setTextFormat(Qt::RichText);
        label->setAutoFillBackground(true);
        QModelIndex ix = model()->index(row, i);
        label->setText(model()->data(ix, Qt::DisplayRole).toString()); // this has HTML
        label->setWordWrap(true);
        setIndexWidget(ix, label); // this calls QAbstractItemView::dataChanged
    }
}
</code>```

However, this is very slow - it takes around 1 second to refresh 100 rows (remove all, then add 100 new ones) like that. With original QTableView it worked fast, but I did not have formatting and ability to add links (cross-references in dictionary). How to make this much faster? Or what other widget can I use to display that data?

My requirements are:

Adding/removing around 1000 rows in ~0.2s, where around 30 will be visible at once

Clickable, multiple internal links (?) in each cell (e.g. QLabel has that, QItemDelegate might have been fast, but I don't know how to get info which link I clicked there)

Formatting that allows different font sizes and colors, word wrap, different cell heights

I'm not really dead-set on QTableView, anything that looks like a scrollable table and looks consistent with Qt graphics is okay

Notes:

I tried making a single label with HTML
 instead, but it wasn't much faster. Seems like QLabel isn't the way to go.

Data in the sample courtesy of the JMdict project.

答:
Many thanks for these code examples, it helped me implement similar functionalaity in my application. I'm working with Python 3 and QT5 and I would like to share my Python code, is case it may be helpful implementing this in Python.

Note that if you are using QT Designer for the UI design, you can use "promote" to change a regular "QTableView" widget to use your custom widget automatically when converting the XML to Python code with "pyuic5".

Code as follows:

    from PyQt5 import QtCore, QtWidgets, QtGui

    class CustomTableView(QtWidgets.QTableView):

        link_activated = QtCore.pyqtSignal(str)

        def __init__(self, parent=None):
            self.parent = parent
            super().__init__(parent)

            self.setMouseTracking(True)
            self._mousePressAnchor = ''
            self._lastHoveredAnchor = ''

        def mousePressEvent(self, event):
            anchor = self.anchorAt(event.pos())
            self._mousePressAnchor = anchor

        def mouseMoveEvent(self, event):
            anchor = self.anchorAt(event.pos())
            if self._mousePressAnchor != anchor:
                self._mousePressAnchor = ''

            if self._lastHoveredAnchor != anchor:
                self._lastHoveredAnchor = anchor
                if self._lastHoveredAnchor:
                    QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
                else:
                    QtWidgets.QApplication.restoreOverrideCursor()

        def mouseReleaseEvent(self, event):
            if self._mousePressAnchor:
                anchor = self.anchorAt(event.pos())
                if anchor == self._mousePressAnchor:
                    self.link_activated.emit(anchor)
                self._mousePressAnchor = ''

        def anchorAt(self, pos):
            index = self.indexAt(pos)
            if index.isValid():
                delegate = self.itemDelegate(index)
                if delegate:
                    itemRect = self.visualRect(index)
                    relativeClickPosition = pos - itemRect.topLeft()
                    html = self.model().data(index, QtCore.Qt.DisplayRole)
                    return delegate.anchorAt(html, relativeClickPosition)
            return ''

    class CustomDelegate(QtWidgets.QStyledItemDelegate):

        def anchorAt(self, html, point):
            doc = QtGui.QTextDocument()
            doc.setHtml(html)
            textLayout = doc.documentLayout()
            return textLayout.anchorAt(point)

        def paint(self, painter, option, index):
            options = QtWidgets.QStyleOptionViewItem(option)
            self.initStyleOption(options, index)

            if options.widget:
                style = options.widget.style()
            else:
                style = QtWidgets.QApplication.style()

            doc = QtGui.QTextDocument()
            doc.setHtml(options.text)
            options.text = ''

            style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)
            ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()

            textRect = style.subElementRect(QtWidgets.QStyle.SE_ItemViewItemText, options)

            painter.save()

            painter.translate(textRect.topLeft())
            painter.setClipRect(textRect.translated(-textRect.topLeft()))
            painter.translate(0, 0.5*(options.rect.height() - doc.size().height()))
            doc.documentLayout().draw(painter, ctx)

            painter.restore()

        def sizeHint(self, option, index):
            options = QtWidgets.QStyleOptionViewItem(option)
            self.initStyleOption(options, index)

            doc = QtGui.QTextDocument()
            doc.setHtml(options.text)
            doc.setTextWidth(options.rect.width())

            return QtCore.QSize(doc.idealWidth(), doc.size().height())
```

Body:
I'm making a dictionary program that displays word definitions in a 3-column QTableView subclass, as user types them, taking data from a QAbstractTableModel subclass. Something like that:

I want to add various formatting to the text, I'm using QAbstractItemView::setIndexWidget to add a QLabel to each cell as data comes in:

WordView.h

#include <QTableView>

class QLabel;

class WordView : public QTableView {
    Q_OBJECT

public:
    explicit WordView(QWidget *parent = 0);

    void rowsInserted(const QModelIndex &parent, int start, int end);

private:
    void insertLabels(int row);
    void removeLabels(int row);
};

WordView.cpp

#include <QLabel>
#include "WordView.h"

WordView::WordView(QWidget *parent) :
    QTableView(parent)
{}

void WordView::rowsInserted(const QModelIndex &parent, int start, int end) {
    QTableView::rowsInserted(parent, start, end);

    for (int row = start; row <= end; ++row) {
        insertLabels(row);
    }
}

void WordView::insertLabels(int row) {
    for (int i = 0; i < 3; ++i) {
        auto label = new QLabel(this);
        label->setTextFormat(Qt::RichText);
        label->setAutoFillBackground(true);
        QModelIndex ix = model()->index(row, i);
        label->setText(model()->data(ix, Qt::DisplayRole).toString()); // this has HTML
        label->setWordWrap(true);
        setIndexWidget(ix, label); // this calls QAbstractItemView::dataChanged
    }
}

However, this is very slow - it takes around 1 second to refresh 100 rows (remove all, then add 100 new ones) like that. With original QTableView it worked fast, but I did not have formatting and ability to add links (cross-references in dictionary). How to make this much faster? Or what other widget can I use to display that data?

My requirements are:

Adding/removing around 1000 rows in ~0.2s, where around 30 will be visible at once

Clickable, multiple internal links (?) in each cell (e.g. QLabel has that, QItemDelegate might have been fast, but I don't know how to get info which link I clicked there)

Formatting that allows different font sizes and colors, word wrap, different cell heights

I'm not really dead-set on QTableView, anything that looks like a scrollable table and looks consistent with Qt graphics is okay

Notes:

I tried making a single label with HTML
 instead, but it wasn't much faster. Seems like QLabel isn't the way to go.

Data in the sample courtesy of the JMdict project.

ContentLicense: CC BY-SA 4.0


问:
Relative layout how to align to other element instead of parent
I have a relative layout where i already aligned almost all elements like i want, but there are two elements at the right bottom(textView and the icon of forbiden photo), they are aligned related to the parent, the parent is not the photo.

I want to align those elements to the bottom of the image that i have:

here is a

expected results:

the rectangle is where i want the textView and the camera forbiden icon!

and here is the xml:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="142dp"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp"
        card_view:cardCornerRadius="@dimen/card_specie_radius">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/Avaliation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/plantName"
                android:layout_marginStart="92dp"
                android:layout_marginTop="15dp"
                android:text="Avalie a fotografia" />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/plantPhoto"
                android:textColor="@color/base"
                android:layout_marginTop="4dp"
                android:layout_toStartOf="@+id/cameraForbiden"
                android:text="TextView" />

            <ImageView
                android:id="@+id/reportImg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/color_cursor_white" />

            <ImageView
                android:id="@+id/plantPhoto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp" />

            <ImageView
                android:id="@+id/userIcon"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:layout_alignParentBottom="true"
                android:layout_below="@id/plantPhoto"
                android:src="@drawable/ic_user"
                />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/plantName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/plantPhoto"
                android:textColor="@color/nephritis"
                android:textSize="18sp" />

            <ImageView
                android:id="@+id/starIcon"
                android:layout_width="23dp"
                android:layout_height="23dp"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/plantName"
                android:src="@drawable/ic_star"
                android:layout_marginLeft="10dp"
                />

            <ImageView
                android:id="@+id/cameraForbiden"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_toRightOf="@+id/plantName"
                android:layout_marginLeft="10dp"
                android:src="@drawable/ic_no_photos"
                android:layout_below="@id/plantPhoto"
                />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/plantPhoto"
                android:textColor="@color/base"
                android:layout_marginEnd="29dp"
                android:layout_marginTop="8dp"
                android:layout_toEndOf="@+id/userIcon"
                android:layout_toLeftOf="@+id/userIcon"
                android:paddingLeft="10px"/>
        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

答:
Use following code:</p>

```<code>    <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

    <ImageView
                    android:id="@+id/plantPhoto"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginRight="16dp" />

     <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentBottom="true"
                android:layout_margin="5dp"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/userIcon"
                    android:layout_width="15dp"
                    android:layout_height="15dp"
                    android:src="@drawable/ic_user"
                    />

              <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                    android:id="@+id/plantName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/nephritis"
                    android:textSize="18sp" />
</LinearLayout>
</RelativeLayout>
</code>```

Body:
I have a relative layout where i already aligned almost all elements like i want, but there are two elements at the right bottom(textView and the icon of forbiden photo), they are aligned related to the parent, the parent is not the photo.

I want to align those elements to the bottom of the image that i have:

here is a

expected results:

the rectangle is where i want the textView and the camera forbiden icon!

and here is the xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="142dp"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp"
        card_view:cardCornerRadius="@dimen/card_specie_radius">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/Avaliation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/plantName"
                android:layout_marginStart="92dp"
                android:layout_marginTop="15dp"
                android:text="Avalie a fotografia" />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/plantPhoto"
                android:textColor="@color/base"
                android:layout_marginTop="4dp"
                android:layout_toStartOf="@+id/cameraForbiden"
                android:text="TextView" />

            <ImageView
                android:id="@+id/reportImg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/color_cursor_white" />

            <ImageView
                android:id="@+id/plantPhoto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp" />

            <ImageView
                android:id="@+id/userIcon"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:layout_alignParentBottom="true"
                android:layout_below="@id/plantPhoto"
                android:src="@drawable/ic_user"
                />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/plantName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/plantPhoto"
                android:textColor="@color/nephritis"
                android:textSize="18sp" />

            <ImageView
                android:id="@+id/starIcon"
                android:layout_width="23dp"
                android:layout_height="23dp"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/plantName"
                android:src="@drawable/ic_star"
                android:layout_marginLeft="10dp"
                />

            <ImageView
                android:id="@+id/cameraForbiden"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_toRightOf="@+id/plantName"
                android:layout_marginLeft="10dp"
                android:src="@drawable/ic_no_photos"
                android:layout_below="@id/plantPhoto"
                />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/plantPhoto"
                android:textColor="@color/base"
                android:layout_marginEnd="29dp"
                android:layout_marginTop="8dp"
                android:layout_toEndOf="@+id/userIcon"
                android:layout_toLeftOf="@+id/userIcon"
                android:paddingLeft="10px"/>
        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

Body:
Use following code:

    <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

    <ImageView
                    android:id="@+id/plantPhoto"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginRight="16dp" />

     <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentBottom="true"
                android:layout_margin="5dp"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/userIcon"
                    android:layout_width="15dp"
                    android:layout_height="15dp"
                    android:src="@drawable/ic_user"
                    />

              <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                    android:id="@+id/plantName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/nephritis"
                    android:textSize="18sp" />
</LinearLayout>
</RelativeLayout>


答: You can check the number for transcription errors (or for a really stupid forger) on your own (see Dennis's answer). To check the credit card number for actual validity (as in: has the card been issued, has it been declared as stolen, etc.), or to check that the expiration date, name, etc., you need to contact the issuing bank (or credit card organization). You need to open an account with them (or more typically through your own bank acting as a forwarder). This is a service that you pay for. It's usually provided as part of a bigger package including the possibility of issuing credit card payments. Once you have chosen a provider, they will supply a piece of software to contact their service, and more importantly credentials for their service that will remain valid as long as your contract with them runs.</p>

Title: Credit Card validation & checking

Body:
HI. I see some libraries of detecting credit card # is valid or not.  However, it is based on the algorithm, not really checking with the credit card company.

is there a way or API so that I can pass in the card name & the card # and see if they are valid and match?

also, which payment getway is good?

OwnerDisplayName: Gilles


问:
Detect if a browser in a mobile device (iOS/Android phone/tablet) is used
Is there a way to detect if a handheld browser is used (iOS/Android phone/tablet)?

I tried this with the goal to make an element half as wide in a browser on a handheld device but it doesn't make a difference.

```<code>width: 600px;
@media handheld { width: 300px; }
</code>```

Can it be done and if so how?

edit: From the referred page in jmaes' answer I used

@media only screen and (max-device-width: 480px).

答:
I know this is an old thread but I thought this might help someone:

Mobile devices have greater height than width, in contrary, computers have greater width than height. For example:

```<code>@media all and (max-width: 320px) and (min-height: 320px)
</code>```

so that would have to be done for every width i guess.

Body:
Is there a way to detect if a handheld browser is used (iOS/Android phone/tablet)?

I tried this with the goal to make an element half as wide in a browser on a handheld device but it doesn't make a difference.

width: 600px;
@media handheld { width: 300px; }

Can it be done and if so how?

edit: From the referred page in jmaes' answer I used

@media only screen and (max-device-width: 480px).

Body:
I know this is an old thread but I thought this might help someone:

Mobile devices have greater height than width, in contrary, computers have greater width than height. For example:

@media all and (max-width: 320px) and (min-height: 320px)

so that would have to be done for every width i guess.