问:
Positioning circle directly behind objects
How would I get the circular arrow behind the 7 items I have created. Similar to what shows in this picture: http://imgur.com/Zz6HqWZ I cant get it to work for some reason. Does anyone have any idea on how to achieve this? Anything helps, cheers.

.container .row {text-align:center; position:relative;}
.center {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left:-35px;
}

.circle {
  display:inline-block;
  background-color:#006850;
  width:85px;
  height:85px;
  border-width:3px;
  border-style:solid;
  border-color:#fefefe;
  border-radius:50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom:-15px;
}

.invisible {
  visibility:hidden;
  display:inline-block;
  background-color:#1f497d;
  width:130px;
  height:65px;
  border-width:3px;
  border-style:solid;
  border-color:#d6d6d6;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color:#d0d3d8;
  width: 200px;
  height: 200px;
  border: 17px solid;
  border-radius: 50%;
  position: relative;
}
.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}
.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 106px;
  right: -25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="invisible"></div>
    <div class="circle"></div>
    <div class="invisible"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="arrow"></div>
</div></code>```

答:
You need to give .container this CSS style:

```<code>.container {
  margin-top: -17px;
  height: 313px;
  width: 371px;
  display: flex;
  align-items: center;
}
</code>```

Surround everything inside .container with another div with the id stuff except the .arrow div.

Give .stuff the following styles:

```<code>.stuff {
  position: absolute;
  top: 0;
}
</code>```

Add the following CSS line to .arrow

```<code>  margin: 0 auto;
</code>```

Move the .arrow div before the .stuff div

And that should work.

Here is the result I got:

.container {
  height: 313px;
  width: 371px;
  display: flex;
  align-items: center;
  margin-top: -17px;
}
.container .row {
  text-align: center;
  position: relative;
}

.center {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left: -35px;
}

.circle {
  display: inline-block;
  background-color: #006850;
  width: 85px;
  height: 85px;
  border-width: 3px;
  border-style: solid;
  border-color: #fefefe;
  border-radius: 50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom: -15px;
}

.invisible {
  visibility: hidden;
  display: inline-block;
  background-color: #1f497d;
  width: 130px;
  height: 65px;
  border-width: 3px;
  border-style: solid;
  border-color: #d6d6d6;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color: #d0d3d8;
  width: 200px;
  height: 200px;
  border: 17px solid;
  border-radius: 50%;
  position: relative;
  margin: 0 auto;
}

.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}

.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 106px;
  right: -25px;
}
.stuff {
  position: absolute;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="arrow"></div>
  <div class="stuff">
    <div class="row">
      <div class="center"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="left"></div>
      <div class="invisible"></div>
      <div class="right"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="invisible"></div>
      <div class="circle"></div>
      <div class="invisible"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="left"></div>
      <div class="invisible"></div>
      <div class="right"></div>
    </div>
    <div class="row">
      <div class="center"></div>
    </div>
  </div>
</div></code>```

To resize it and rotate it, you need to add this to the .arrow CSS:

```<code>  transform: rotate(-112deg) scale(1.2);
</code>```

.container {
  height: 313px;
  width: 371px;
  display: flex;
  align-items: center;
  margin-top: -17px;
}
.container .row {
  text-align: center;
  position: relative;
}

.center {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left: -35px;
}

.circle {
  display: inline-block;
  background-color: #006850;
  width: 85px;
  height: 85px;
  border-width: 3px;
  border-style: solid;
  border-color: #fefefe;
  border-radius: 50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom: -15px;
}

.invisible {
  visibility: hidden;
  display: inline-block;
  background-color: #1f497d;
  width: 130px;
  height: 65px;
  border-width: 3px;
  border-style: solid;
  border-color: #d6d6d6;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color: #d0d3d8;
  width: 200px;
  height: 200px;
  border: 17px solid;
  border-radius: 50%;
  position: relative;
  margin: 0 auto;
  transform: rotate(-112deg) scale(1.2);
}

.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}

.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 106px;
  right: -25px;
}
.stuff {
  position: absolute;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="arrow"></div>
  <div class="stuff">
    <div class="row">
      <div class="center"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="left"></div>
      <div class="invisible"></div>
      <div class="right"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="invisible"></div>
      <div class="circle"></div>
      <div class="invisible"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="left"></div>
      <div class="invisible"></div>
      <div class="right"></div>
    </div>
    <div class="row">
      <div class="center"></div>
    </div>
  </div>
</div></code>```

Body:
You need to give .container this CSS style:

.container {
  margin-top: -17px;
  height: 313px;
  width: 371px;
  display: flex;
  align-items: center;
}

Surround everything inside .container with another div with the id stuff except the .arrow div.

Give .stuff the following styles:

.stuff {
  position: absolute;
  top: 0;
}

Add the following CSS line to .arrow

  margin: 0 auto;

Move the .arrow div before the .stuff div

And that should work.

Here is the result I got:

.container {
  height: 313px;
  width: 371px;
  display: flex;
  align-items: center;
  margin-top: -17px;
}
.container .row {
  text-align: center;
  position: relative;
}

.center {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left: -35px;
}

.circle {
  display: inline-block;
  background-color: #006850;
  width: 85px;
  height: 85px;
  border-width: 3px;
  border-style: solid;
  border-color: #fefefe;
  border-radius: 50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom: -15px;
}

.invisible {
  visibility: hidden;
  display: inline-block;
  background-color: #1f497d;
  width: 130px;
  height: 65px;
  border-width: 3px;
  border-style: solid;
  border-color: #d6d6d6;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color: #d0d3d8;
  width: 200px;
  height: 200px;
  border: 17px solid;
  border-radius: 50%;
  position: relative;
  margin: 0 auto;
}

.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}

.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 106px;
  right: -25px;
}
.stuff {
  position: absolute;
  top: 0;
}

<div class="container">
  <div class="arrow"></div>
  <div class="stuff">
    <div class="row">
      <div class="center"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="left"></div>
      <div class="invisible"></div>
      <div class="right"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="invisible"></div>
      <div class="circle"></div>
      <div class="invisible"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="left"></div>
      <div class="invisible"></div>
      <div class="right"></div>
    </div>
    <div class="row">
      <div class="center"></div>
    </div>
  </div>
</div>

To resize it and rotate it, you need to add this to the .arrow CSS:

  transform: rotate(-112deg) scale(1.2);

.container {
  height: 313px;
  width: 371px;
  display: flex;
  align-items: center;
  margin-top: -17px;
}
.container .row {
  text-align: center;
  position: relative;
}

.center {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display: inline-block;
  background-color: #1f497d;
  width: 100px;
  height: 50px;
  border-width: 3px;
  border-style: solid;
  border-color: #ededed;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left: -35px;
}

.circle {
  display: inline-block;
  background-color: #006850;
  width: 85px;
  height: 85px;
  border-width: 3px;
  border-style: solid;
  border-color: #fefefe;
  border-radius: 50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom: -15px;
}

.invisible {
  visibility: hidden;
  display: inline-block;
  background-color: #1f497d;
  width: 130px;
  height: 65px;
  border-width: 3px;
  border-style: solid;
  border-color: #d6d6d6;
  border-radius: 7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color: #d0d3d8;
  width: 200px;
  height: 200px;
  border: 17px solid;
  border-radius: 50%;
  position: relative;
  margin: 0 auto;
  transform: rotate(-112deg) scale(1.2);
}

.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}

.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 106px;
  right: -25px;
}
.stuff {
  position: absolute;
  top: 0;
}

<div class="container">
  <div class="arrow"></div>
  <div class="stuff">
    <div class="row">
      <div class="center"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="left"></div>
      <div class="invisible"></div>
      <div class="right"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="invisible"></div>
      <div class="circle"></div>
      <div class="invisible"></div>
    </div>
    <div class="row" style="margin-top:-15px;">
      <div class="left"></div>
      <div class="invisible"></div>
      <div class="right"></div>
    </div>
    <div class="row">
      <div class="center"></div>
    </div>
  </div>
</div>


来源: stackexchange

问:
Using urllib to get the final redirect of a webpage in Python 3.5
As in this post, I attempt to get the final redirect of a webpage as:

```<code>import urllib.request
response = urllib.request.urlopen(url)
response.geturl()
</code>```

But this doesn't work as I get the "HTTPError: HTTP Error 300: Multiple Choices" error when attempting to use urlopen.

See documentation for these methods here.

EDIT:

This problem is different than the Python: urllib2.HTTPError: HTTP Error 300: Multiple Choices question, because they skip the error-causing pages, while I have to obtain the final destination.

答:
As suggested by @abccd, I used the requests library. So I will describe the solution.

```<code>import requests

url_base = 'something'  # You need this because the redirect URL is relative.
url = url_base + 'somethingelse'

response = requests.get(url)

# Check if the request returned with the 300 error code.
if response.status_code == 300:
    redirect_url = url_base + response.headers['Location']  # Get new URL.
    response = requests.get(redirect_url)  # Make a new request.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As in this post, I attempt to get the final redirect of a webpage as:

import urllib.request
response = urllib.request.urlopen(url)
response.geturl()

But this doesn't work as I get the "HTTPError: HTTP Error 300: Multiple Choices" error when attempting to use urlopen.

See documentation for these methods here.

EDIT:

This problem is different than the Python: urllib2.HTTPError: HTTP Error 300: Multiple Choices question, because they skip the error-causing pages, while I have to obtain the final destination.

Body:
As suggested by @abccd, I used the requests library. So I will describe the solution.

import requests

url_base = 'something'  # You need this because the redirect URL is relative.
url = url_base + 'somethingelse'

response = requests.get(url)

# Check if the request returned with the 300 error code.
if response.status_code == 300:
    redirect_url = url_base + response.headers['Location']  # Get new URL.
    response = requests.get(redirect_url)  # Make a new request.


问:
Connect my Java application to SQL Server 2012
I have a SQL Server 2012 database in the network of my company.
I can access to this database to observe the tables etc... with SQL Server Management Studio giving the following :

Server type : Database Engine

Server name  : xxx-yyy-zzz.eu.company.corp, number_of_port

Authentication : Windows Authentication

Username and password

I also know the name of the database and nothing more.

I would like to connect a new Java program I am writing with Eclipse to this SQL Server database. But I have never connected or even used a SQL Server before so I have no idea how to do it. I understood reading some other posts that I need a driver, but I don't understand where I need to install this driver, which driver and what I need to do to extract data from the database in my Java program.

Could you please tell me more about it ? Thank you :)

答:
I suggest you start here with this Microsoft documentation, Microsoft JDBC Driver for SQL Server.

Looks like you can download the actual driver from Microsoft JDBC Driver 6.0 for SQL Server.

What you need to do may vary depending on the operating system you are using however the above driver looks to be pretty inclusive for Linux, Windows and also works with Azure, Microsoft's cloud offering.

The Programming Guide for JDBC SQL Driver has a number of links explaining what you will need to do and Building the Connection URL describes the actual connect string.

This stack overflow post has a sample program. Java program to connect to Sql Server and running the sample query From Eclipse.

You may also find How to connect to Microsoft SQL Server database using Eclipse to be helpful.

Just remember, you need Eclipse IDE for Java EE developers to access
  the database. It contains tools for database development e.g. database
  explorer. The Eclipse IDE for Java Developers doesn't contain those
  tool by default. FYI, I am using Eclipse Java EE IDE for Web
  Developers, Version: Kepler Service Release 2.


问:
File fails to upload when using xety/cake3-upload plugin
I am not able to upload a file from one folder to another in CakePHP. Here is my code.

First I loaded the plugin and added this code in ProductsTable.php

```<code>$this->addBehavior('Xety/Cake3Upload.Upload', [
    'fields' => [
        'productimg_file' => [
            'path' => 'uploads/avatar/:id/:md5'
        ]
    ]
]);
</code>```

then I added in my add.cpt

```<code><?php
    echo $this->Form->input('productcode');
    echo $this->Form->input('productname');
    echo $this->Form->input('productprice');
    echo $this->Form->input('quantity');
    echo $this->Form->input('productdesc');
    echo $this->Form->input('productimg_file',['type' => 'file']);
?>
</code>```

Still the file doesn't get moved to the webroot dir.

enter code here
public function add()
    {

```<code>    $product = $this->Products->newEntity();

    if ($this->request->is('post')) {

    $product = $this->Products->patchEntity($product, $this->request->data);

        if ($this->Products->save($product)) {
           $this->Flash->success(__('The product has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
           $this->Flash->error(__('The product could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('product'));
    $this->set('_serialize', ['product']);
}
</code>```

答:
_file is a default suffix which you will use only in .ctp file. Not in model.
Change your behavior in model. Hope this will help.</p>

```<code>$this->addBehavior('Xety/Cake3Upload.Upload', [
    'fields' => [
        'productimg' => [
            'path' => 'uploads/avatar/:id/:md5'
        ]
    ]
]);
</code>```

Body:
I am not able to upload a file from one folder to another in CakePHP. Here is my code.

First I loaded the plugin and added this code in ProductsTable.php

$this->addBehavior('Xety/Cake3Upload.Upload', [
    'fields' => [
        'productimg_file' => [
            'path' => 'uploads/avatar/:id/:md5'
        ]
    ]
]);

then I added in my add.cpt

<?php
    echo $this->Form->input('productcode');
    echo $this->Form->input('productname');
    echo $this->Form->input('productprice');
    echo $this->Form->input('quantity');
    echo $this->Form->input('productdesc');
    echo $this->Form->input('productimg_file',['type' => 'file']);
?>

Still the file doesn't get moved to the webroot dir.

enter code here
public function add()
    {

    $product = $this->Products->newEntity();

    if ($this->request->is('post')) {

    $product = $this->Products->patchEntity($product, $this->request->data);

        if ($this->Products->save($product)) {
           $this->Flash->success(__('The product has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
           $this->Flash->error(__('The product could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('product'));
    $this->set('_serialize', ['product']);
}

Body:
_file is a default suffix which you will use only in .ctp file. Not in model.
Change your behavior in model. Hope this will help.

$this->addBehavior('Xety/Cake3Upload.Upload', [
    'fields' => [
        'productimg' => [
            'path' => 'uploads/avatar/:id/:md5'
        ]
    ]
]);


问:
Partitioning graph into 2 sets of vertices
I want to partition a connected graph into 2 sets of vertices, such that the difference of sum of edge-weights among vertices of each set is minimized.

For example, if a graph consists of vertices 1,2,3,4,5, consider this partition:

Set A - {1,2,3}

Set B - {4,5}

Sum A = {w(1 2) + w(2 3) + w(1 3)}

Sum B = {w(4 5)}

Diff = abs(Sum A - Sum B) ... (This is one possible partition difference.)

So, how do I find a partition such that the difference is minimized?

答:
The following algorithmic sketch is based on Iterated Local Search. The idea is to greedily optimize the current solution until a local optimal solution is found. Then disturb this solution to overcome the local optimal solution. Always keep track of the best solution found so far.

Randomly divide the set of vertice into V1 and V2

Iterate

Calculate the costs (edge-weight-difference) of your current division

Select two random vertices v1 from V1 and v2 from V2

Check whether swapping these vertices (move v1 to V2 and v2 to V1) would lead to lower costs (edge-weight-difference). If so, swap vertices v1 and v2, else keep the sets.

Disturb a converged solution by swapping half of the vertices in V1 with half of the vertices in V2. Goto 2.

Iterated Local Search is a surprisingly effective and practical heuristic -- even for NP-complete problems.


问:
Testing values of a JSON file with Rspec
I'm using Packer to create AMIs with baked in services. I know I can test the end product using serverspec, but I have a number of naming and tagging standards I'd like to enforce before the AMI is created. Such as version, OS, name etc. These values are held in a JSON file which is fed into packer during image creation.

My question is, is there a way to test/ pass in these values to Rspec and then use regex matcher to validate them. For example if I had in my variables.json

```<code>{"version: "0.1.0", "region": "eu-west-1"}
</code>```

How could I check it using Rspecs regex matcher like

```<code>expect(region).to match(/^[a-z]{2}-[a-z]+-[0-9]$/)
</code>```

答:
I test such things by parsing JSON and then using the mighty include against resulting hashes. E.g. try this packed_json_spec.rb:

```<code>require "json"

describe "packed JSON data" do
  let(:input) {'{"version" : "0.1.0", "region" : "eu-west-1"}'}
  it "is valid" do
    h = JSON.parse(input)
    expect(h).to include("version" => match(/^\d+\.\d+\.\d+$/))
    expect(h).to include("region" => match(/^eu-\w+-\d+$/))
  end
end
</code>```

Notes:

Don't forget that RSpec is still Ruby.

JSON means structure. So validity tests should cover structure as well as individual values.

Hope that was helpful. Cheers!

Body:
I'm using Packer to create AMIs with baked in services. I know I can test the end product using serverspec, but I have a number of naming and tagging standards I'd like to enforce before the AMI is created. Such as version, OS, name etc. These values are held in a JSON file which is fed into packer during image creation.

My question is, is there a way to test/ pass in these values to Rspec and then use regex matcher to validate them. For example if I had in my variables.json

{"version: "0.1.0", "region": "eu-west-1"}

How could I check it using Rspecs regex matcher like

expect(region).to match(/^[a-z]{2}-[a-z]+-[0-9]$/)

Body:
I test such things by parsing JSON and then using the mighty include against resulting hashes. E.g. try this packed_json_spec.rb:

require "json"

describe "packed JSON data" do
  let(:input) {'{"version" : "0.1.0", "region" : "eu-west-1"}'}
  it "is valid" do
    h = JSON.parse(input)
    expect(h).to include("version" => match(/^\d+\.\d+\.\d+$/))
    expect(h).to include("region" => match(/^eu-\w+-\d+$/))
  end
end

Notes:

Don't forget that RSpec is still Ruby.

JSON means structure. So validity tests should cover structure as well as individual values.

Hope that was helpful. Cheers!


问:
Iterating and adding all column names to a ComboBox using EPPlus
I need to add the column names within a sheet to a combobox

I have tried the following

```<code> var pck = new OfficeOpenXml.ExcelPackage();
            pck.Load(new System.IO.FileInfo("test.xlsx").OpenRead());
            var ws = pck.Workbook.Worksheets[1];

            int totalCols = ws.Dimension.End.Column;

            for (int i = 1; i <= totalCols; i++)
            {
              comboBox1.Items.Add(  (ws.Column(i).ToString()));
            }
        }
</code>```

But this produces a Null Reference Exception.

Why is that happening?

答:
Ensure that you're loading the package correctly and selecting the values correctly:

```<code>// Select workbook
var fileInfo = new FileInfo(@"yourfile.xlsx");

// Load workbook
using (var package = new ExcelPackage(fileInfo)) {
// Itterate through workbook sheets
    foreach (var sheet in package.Workbook.Worksheets){
// Itterate through each column until final column
        for (int i = 1; i <= sheet.Dimension.End.Column; i++) {
            comboBox1.Items.Add(sheet.Cells[1, i].Text);
        }
    }
}
</code>```

This runs correctly in a new workbook with two sheets and values in the columns of each sheet.

ContentLicense: CC BY-SA 4.0

Body:
I need to add the column names within a sheet to a combobox

I have tried the following

 var pck = new OfficeOpenXml.ExcelPackage();
            pck.Load(new System.IO.FileInfo("test.xlsx").OpenRead());
            var ws = pck.Workbook.Worksheets[1];

            int totalCols = ws.Dimension.End.Column;

            for (int i = 1; i <= totalCols; i++)
            {
              comboBox1.Items.Add(  (ws.Column(i).ToString()));
            }
        }

But this produces a Null Reference Exception.

Why is that happening?

Body:
Ensure that you're loading the package correctly and selecting the values correctly:

// Select workbook
var fileInfo = new FileInfo(@"yourfile.xlsx");

// Load workbook
using (var package = new ExcelPackage(fileInfo)) {
// Itterate through workbook sheets
    foreach (var sheet in package.Workbook.Worksheets){
// Itterate through each column until final column
        for (int i = 1; i <= sheet.Dimension.End.Column; i++) {
            comboBox1.Items.Add(sheet.Cells[1, i].Text);
        }
    }
}

This runs correctly in a new workbook with two sheets and values in the columns of each sheet.


问:
Fatal error: Call to a member function query() on a non-object in
Connection failed: SQLSTATE[28000] [1045] Access denied for user 'rkcat'@'localhost' (using password: YES)
Fatal error: Call to a member function query() on a non-object in

```<code> <?php
    $servername = "localhost";
    $username = "rkcat";
    $password = "rkcat123!@#";
    enter code here
    try {
      $conn = new PDO("mysql:host=$servername;dbname=shradha_padma", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
    catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

    $sql = "SELECT * FROM slider";
    $result = $conn->query($sql);
    $data = $result->fetchAll(PDO::FETCH_ASSOC);

     ?>
</code>```

答:
You are getting the Fatal error: Call to a member function query() on a non-object in error due to the SQLSTATE[28000] [1045] Access denied for user 'rkcat'@'localhost' error.

Because the connection failed in your try/catch, the PDO object ($conn) was not initialized, and thus the query() method does not exist when you call it via $conn->query($sql).

To solve the problem, find out why access is denied to your user. (Bad password, or incorrect permissions on your DB)

Body:
Connection failed: SQLSTATE[28000] [1045] Access denied for user 'rkcat'@'localhost' (using password: YES)
Fatal error: Call to a member function query() on a non-object in

 <?php
    $servername = "localhost";
    $username = "rkcat";
    $password = "rkcat123!@#";
    enter code here
    try {
      $conn = new PDO("mysql:host=$servername;dbname=shradha_padma", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
    catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

    $sql = "SELECT * FROM slider";
    $result = $conn->query($sql);
    $data = $result->fetchAll(PDO::FETCH_ASSOC);

     ?>


问:
HTML css code copied from code pen giving
https://codepen.io/anon/pen/QgaRpz?editors=1000

I copied the HTML CSS code of this codepen
but it is not giving same output .the division the gray background nothing is coming I am confused how 2 same code can give different output.

MY HTML CODE:

```<code><html>

<style>
h1 {
  color: #DC2827;
  font-size: 40px;
  font-weight: 700;
}

h3 {
  font-size: 30px;
}

h1, h2, h3 {
  font-family: 'Roboto Condensed', sans-serif;
}

.title {
  margin-top: 20px;
}

.main-img {
  width: 100%;
}

ul {
  list-style: none;
}
.time {
  color: #DC2827;
  font-size: 20px;
}

li, p {
  font-size: 18px;
  margin: 10px;
}

.nav-tabs {
   text-align:center;
   float:none;
   display:inline-block;
   margin-bottom: 30px;
}

</style>
<div class="container">
  <div class="well title text-center">
    <h1 class="heading">Ruby On Rails</h1>
    <h2>A  Web Aplication Framework</h2>
    <p>Ruby on Rails, or simply Rails, is a web application framework written in Ruby under MIT License. Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web pages. It encourages and facilitates
  the use of web standards such as JSON or XML for data transfer, and HTML, CSS and JavaScript for display and user interfacing. In addition to MVC, Rails emphasizes the use of other well-known software engineering patterns and paradigms, including convention
  over configuration (CoC), don't repeat yourself (DRY), and the active record pattern.</p>
  </div>

   <div class="well">
    <img src="https://udemy-images.udemy.com/course/750x422/531360_06c4.jpg" alt="Ruby on Rails Image" class="responsive main-img" />
  </div>

  <div class="well text-center">
    <h3>History</h3>
    <hr />

    <ul class="list-group">
      <li class="list-group-item"><span class="time">July 2004 - </span>David Heinemeier Hansson first released Rails as open source.</li>

      <li class="list-group-item"><span class="time">February 2005 - </span>Commit rights to the project has been shared.</li>
      <li class="list-group-item"><span class="time">August 2006 - </span>Apple announced that it would ship Ruby on Rails with Mac OS X v10.5 "Leopard".</li>
      <li class="list-group-item"><span class="time">March 2009 - </span>Rails version 2.3 was released.</li>
      <li class="list-group-item"><span class="time">December 2008 - </span>Ruby on Rails announced it would work with the Merb project to bring "the best ideas of Merb" into Rails 3, ending the "unnecessary duplication" across both communities. Merb was merged with Rails as part
        of the Rails 3.0 release.</li>
      <li class="list-group-item"><span class="time">August 2011 - </span>Rails 3.1 was released featuring Reversible Database Migrations, Asset Pipeline, Streaming, jQuery as default JavaScript library and newly introduced CoffeeScript and Sass into the stack.</li>
      <li class="list-group-item"><span class="time">January 2012 - </span>Rails 3.2 was released with a faster development mode and routing engine (also known as Journey engine), Automatic Query Explain and Tagged Logging. Rails 3.2.x is the last version that supports Ruby 1.8.7.
        Rails 3.2.12 supports Ruby 2.0</li>
      <li class="list-group-item"><span class="time">June 2013 - </span>Rails 4.0 was released introducing Russian Doll Caching, Turbolinks, Live Streaming as well as making Active Resource, Active Record Observer and other components optional by splitting them as gems.</li>
      <li class="list-group-item"><span class="time">April 2014 - </span>Rails 4.1 was released introducing Spring, Variants, Enums, Mailer previews, and secrets.yml.</li>
      <li class="list-group-item"><span class="time">December 2014 - </span>Rails 4.2 was released introducing Active Job, asynchronous emails, Adequate Record, Web Console, and foreign keys.</li>
      <li class="list-group-item"><span class="time">Early 2016 - </span>Rails 5.0 is set to release. Notable additions in Rails 5.0 include an option for an API-only application suitable for use as a backend to JavaScript or mobile applications. Also Action Cable for live features such as chat and notifications. </li>
    </ul>

    </div>

    <div class="well">
    <h3 class="text-center">Links</h3>
    <hr />
    <div class="text-center">

      <!-- Nav tabs -->
      <ul class="nav nav-tabs" role="tablist">
        <li role="presentation" class="active"><a href="#wiki" aria-controls="wiki" role="tab" data-toggle="tab">Wiki</a></li>
        <li role="presentation"><a href="#web" aria-controls="web" role="tab" data-toggle="tab">Web</a></li>
        <li role="presentation"><a href="#api" aria-controls="api" role="tab" data-toggle="tab">API</a></li>
        <li role="presentation"><a href="#github" aria-controls="github" role="tab" data-toggle="tab">Github</a></li>
      </ul>

      <div class="tab-content">
        <div role="tabpanel" class="tab-pane active" id="wiki"><a href="https://en.wikipedia.org/wiki/Ruby_on_Rails" target="_blank">https://en.wikipedia.org/wiki/Ruby_on_Rails</a></div>
        <div role="tabpanel" class="tab-pane" id="web"><a href="http://rubyonrails.org/" target="_blank">http://rubyonrails.org/</a></div>
        <div role="tabpanel" class="tab-pane" id="api"><a href="http://api.rubyonrails.org/" target="_blank">http://api.rubyonrails.org/</a></div>
        <div role="tabpanel" class="tab-pane" id="github"><a href="https://github.com/rails/rails" target="_blank">https://github.com/rails/rails</a></div>
      </div>

    </div>
  </div>

  <div class="well text-center">
    <p> Copyrights © none.</p>
  </div>
</div>
</html>
</code>```

答:
you need to inject bootstrap external library to your code.

add this link to your

```<code>   <link rel="stylesheet"

href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</code>```

and this  to your

```<code>    <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</script>
</code>```

with bootstrap:

https://jsfiddle.net/DTcHh/34298/

without bootstrap:

https://jsfiddle.net/suunyz3e/1437/

and add jquery as well

Body:
https://codepen.io/anon/pen/QgaRpz?editors=1000

I copied the HTML CSS code of this codepen
but it is not giving same output .the division the gray background nothing is coming I am confused how 2 same code can give different output.

MY HTML CODE:

Ruby On Rails

A  Web Aplication Framework

Ruby on Rails, or simply Rails, is a web application framework written in Ruby under MIT License. Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web pages. It encourages and facilitates
  the use of web standards such as JSON or XML for data transfer, and HTML, CSS and JavaScript for display and user interfacing. In addition to MVC, Rails emphasizes the use of other well-known software engineering patterns and paradigms, including convention
  over configuration (CoC), don't repeat yourself (DRY), and the active record pattern.

History

July 2004 - David Heinemeier Hansson first released Rails as open source.

February 2005 - Commit rights to the project has been shared.

August 2006 - Apple announced that it would ship Ruby on Rails with Mac OS X v10.5 "Leopard".

March 2009 - Rails version 2.3 was released.

December 2008 - Ruby on Rails announced it would work with the Merb project to bring "the best ideas of Merb" into Rails 3, ending the "unnecessary duplication" across both communities. Merb was merged with Rails as part
        of the Rails 3.0 release.

August 2011 - Rails 3.1 was released featuring Reversible Database Migrations, Asset Pipeline, Streaming, jQuery as default JavaScript library and newly introduced CoffeeScript and Sass into the stack.

January 2012 - Rails 3.2 was released with a faster development mode and routing engine (also known as Journey engine), Automatic Query Explain and Tagged Logging. Rails 3.2.x is the last version that supports Ruby 1.8.7.
        Rails 3.2.12 supports Ruby 2.0

June 2013 - Rails 4.0 was released introducing Russian Doll Caching, Turbolinks, Live Streaming as well as making Active Resource, Active Record Observer and other components optional by splitting them as gems.

April 2014 - Rails 4.1 was released introducing Spring, Variants, Enums, Mailer previews, and secrets.yml.

December 2014 - Rails 4.2 was released introducing Active Job, asynchronous emails, Adequate Record, Web Console, and foreign keys.

Early 2016 - Rails 5.0 is set to release. Notable additions in Rails 5.0 include an option for an API-only application suitable for use as a backend to JavaScript or mobile applications. Also Action Cable for live features such as chat and notifications.

Links

Wiki

Web

API

Github

https://en.wikipedia.org/wiki/Ruby_on_Rails

http://rubyonrails.org/

http://api.rubyonrails.org/

https://github.com/rails/rails

 Copyrights © none.

Body:
you need to inject bootstrap external library to your code.

add this link to your

   <link rel="stylesheet"

href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

and this  to your

    <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</script>

with bootstrap:

https://jsfiddle.net/DTcHh/34298/

without bootstrap:

https://jsfiddle.net/suunyz3e/1437/

and add jquery as well


问:
How do I insert an element at the correct position into a sorted array in Swift?
NSArray has - (NSUInteger)indexOfObject:(id)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp to determine the insert position of a new object in a sorted array.

What is the best and high-performance way to do this in pure Swift?

Something along the lines of:

```<code>var myArray = ["b", "e", "d", "a"]
myArray.sort { $0 < $1 }

// myArray is now [a, b, d, e]

myArray.append("c")
myArray.sort { $0 < $1 }

// myArray is now [a, b, c, d, e]
</code>```

Instead of appending the new element and then sorting the array, I would like to figure out the correct position and insert the element:

```<code>let index = [... how to calculate this index ??? ...]
myArray.insert("c", atIndex: index)
</code>```

答:
In swift 3 you can use index(where:):

```<code>var myArray = ["a", "b", "d", "e"]
let newElement = "c"
if let index = myArray.index(where: { $0 > newElement }) {
    myArray.insert(newElement, at: index)
}
</code>```

Note that in this case you need to reverse the condition inside the closure (i.e. > instead of < for increasing elements in array), because the index you are interested in is the first element that does NOT match the predicate. Also, this method will return nil if the newly inserted element is going to be the last in the array (newElement = "z" in the example above.

For convenience, this can be wrapped to a separate function that will handle all these issues:

```<code>extension Collection {
    func insertionIndex(of element: Self.Iterator.Element,
                        using areInIncreasingOrder: (Self.Iterator.Element, Self.Iterator.Element) -> Bool) -> Index {
        return index(where: { !areInIncreasingOrder($0, element) }) ?? endIndex
    }
}
</code>```

Usage:

```<code>var myArray = ["a", "b", "d", "e"]
let newElement = "c"
let index = myArray.insertionIndex(of: newElement, using: <)
myArray.insert(newElement, at: index)
</code>```

Body:
NSArray has - (NSUInteger)indexOfObject:(id)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp to determine the insert position of a new object in a sorted array.

What is the best and high-performance way to do this in pure Swift?

Something along the lines of:

var myArray = ["b", "e", "d", "a"]
myArray.sort { $0 < $1 }

// myArray is now [a, b, d, e]

myArray.append("c")
myArray.sort { $0 < $1 }

// myArray is now [a, b, c, d, e]

Instead of appending the new element and then sorting the array, I would like to figure out the correct position and insert the element:

let index = [... how to calculate this index ??? ...]
myArray.insert("c", atIndex: index)

Body:
In swift 3 you can use index(where:):

var myArray = ["a", "b", "d", "e"]
let newElement = "c"
if let index = myArray.index(where: { $0 > newElement }) {
    myArray.insert(newElement, at: index)
}

Note that in this case you need to reverse the condition inside the closure (i.e. > instead of < for increasing elements in array), because the index you are interested in is the first element that does NOT match the predicate. Also, this method will return nil if the newly inserted element is going to be the last in the array (newElement = "z" in the example above.

For convenience, this can be wrapped to a separate function that will handle all these issues:

extension Collection {
    func insertionIndex(of element: Self.Iterator.Element,
                        using areInIncreasingOrder: (Self.Iterator.Element, Self.Iterator.Element) -> Bool) -> Index {
        return index(where: { !areInIncreasingOrder($0, element) }) ?? endIndex
    }
}

Usage:

var myArray = ["a", "b", "d", "e"]
let newElement = "c"
let index = myArray.insertionIndex(of: newElement, using: <)
myArray.insert(newElement, at: index)


问:
Online Shop - Create an order with multiple products MVC .net
So I am building an online shop using Code-First MVC

So I created this model classes for now (don't take the types of the attributes too serious for now):

Products (Produto):

```<code> public Produto()
        {
            ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
        }
        public int ProdutoID { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        [Required]
        public double Preco { get; set; }

        [Required]
        public double Peso { get; set; }

        [Required]
        [StringLength(255)]
        public string Descricao { get; set; }

        [Required]
        public double IVA { get; set; }

        public string Imagem { get; set; }

        public DateTime UltimaAtualizacao { get; set; }

        public int Stock { get; set; }

        public int CategoriaID {get;set;}

        public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }
    }
</code>```

Encomenda (Order):

```<code>public class Encomenda
{
    public Encomenda()
    {
        ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
    }
    [Key]
    public int IDEncomenda { get; set; }

    [Required]
    public DateTime DataSubmissao { get; set; }

    [Required]
    public DateTime DataEnvio { get; set; }

    [Required]
    public int EstadoEnvioID { get; set; }

    [StringLength(50)]
    public string NomeDestino { get; set; }

    [Required]
    public int TipoExpedicaoID { get; set; }

    [Required]
    public int RegiaoDestinoID { get; set; }

    [StringLength(50)]
    public string MoradaDestino { get; set; }

    [StringLength(50)]
    public string CodPostalDestino { get; set; }

    [Required]
    [StringLength(50)]
    public string MoradaFaturacao { get; set; }

    [Required]
    [StringLength(50)]
    public string CodPostalFaturacao { get; set; }

    public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }

}
</code>```

And the connection table between the produtos (Products) and Encomenda (Order)

```<code>   public class Produto_Encomenda
    {

        [Key]
        public int IDProduto_Encomenda { get; set; }

        [Required]
        public string NomeProduto { get; set; }

        [Required]
        public int Quantidade { get; set; }

        [Required]
        public float preco { get; set; }

        [Required]
        public float IVA { get; set; }

        public virtual Encomenda Encomenda { get; set; }

        public virtual Produto Produto { get; set; }

        [ForeignKey("Encomenda")]
        public int IDEncomendaFK { get; set; }

        [ForeignKey("Produto")]
        public int IDProdutoFK { get; set; }

    }
</code>```

So my question is..
Let's pretend that a costumer buys 2 or 3 products or more.
How can I store all this products in a single line of an order?
Cheers and thanks a lot in advance for the time spent reading.

答:
I guess you are looking to make a viewmodel

Create a class that contains Products and Encomenda class as property  -

Model -

```<code>     public class MyViewModel
     {
       public Produto Pinst{get;set;}
       public Encomenda Einst{get;set;}
     }
</code>```

Controller or method-

```<code>    public void SomeMethod()
    {
       List<MyViewModel> lst = new List<MyViewModel>();
       //Now suppose
       foreach(var items in listThatGetCreatedWithBuyerproductInfo)
       {
         MyViewModel obj = new MyViewModel ();
         obj.Pinst = new Produto();
         obj.Einst = new Encomenda();

         //Here goes your properties from item in respected class instances
         obj.Pinst.Nome  = items.Nome;
         obj.Einst.DataSubmissao = items.DataSubmissao;
         //when you are done loading add obj to list
         lst.Add(obj);
       }
    }
</code>```

Hope it Helps if it does not tell me !!

Body:
So I am building an online shop using Code-First MVC

So I created this model classes for now (don't take the types of the attributes too serious for now):

Products (Produto):

 public Produto()
        {
            ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
        }
        public int ProdutoID { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        [Required]
        public double Preco { get; set; }

        [Required]
        public double Peso { get; set; }

        [Required]
        [StringLength(255)]
        public string Descricao { get; set; }

        [Required]
        public double IVA { get; set; }

        public string Imagem { get; set; }

        public DateTime UltimaAtualizacao { get; set; }

        public int Stock { get; set; }

        public int CategoriaID {get;set;}

        public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }
    }

Encomenda (Order):

public class Encomenda
{
    public Encomenda()
    {
        ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
    }
    [Key]
    public int IDEncomenda { get; set; }

    [Required]
    public DateTime DataSubmissao { get; set; }

    [Required]
    public DateTime DataEnvio { get; set; }

    [Required]
    public int EstadoEnvioID { get; set; }

    [StringLength(50)]
    public string NomeDestino { get; set; }

    [Required]
    public int TipoExpedicaoID { get; set; }

    [Required]
    public int RegiaoDestinoID { get; set; }

    [StringLength(50)]
    public string MoradaDestino { get; set; }

    [StringLength(50)]
    public string CodPostalDestino { get; set; }

    [Required]
    [StringLength(50)]
    public string MoradaFaturacao { get; set; }

    [Required]
    [StringLength(50)]
    public string CodPostalFaturacao { get; set; }

    public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }

}

And the connection table between the produtos (Products) and Encomenda (Order)

   public class Produto_Encomenda
    {

        [Key]
        public int IDProduto_Encomenda { get; set; }

        [Required]
        public string NomeProduto { get; set; }

        [Required]
        public int Quantidade { get; set; }

        [Required]
        public float preco { get; set; }

        [Required]
        public float IVA { get; set; }

        public virtual Encomenda Encomenda { get; set; }

        public virtual Produto Produto { get; set; }

        [ForeignKey("Encomenda")]
        public int IDEncomendaFK { get; set; }

        [ForeignKey("Produto")]
        public int IDProdutoFK { get; set; }

    }

So my question is..
Let's pretend that a costumer buys 2 or 3 products or more.
How can I store all this products in a single line of an order?
Cheers and thanks a lot in advance for the time spent reading.

Body:
I guess you are looking to make a viewmodel

Create a class that contains Products and Encomenda class as property  -

Model -

     public class MyViewModel
     {
       public Produto Pinst{get;set;}
       public Encomenda Einst{get;set;}
     }

Controller or method-

    public void SomeMethod()
    {
       List<MyViewModel> lst = new List<MyViewModel>();
       //Now suppose
       foreach(var items in listThatGetCreatedWithBuyerproductInfo)
       {
         MyViewModel obj = new MyViewModel ();
         obj.Pinst = new Produto();
         obj.Einst = new Encomenda();

         //Here goes your properties from item in respected class instances
         obj.Pinst.Nome  = items.Nome;
         obj.Einst.DataSubmissao = items.DataSubmissao;
         //when you are done loading add obj to list
         lst.Add(obj);
       }
    }

Hope it Helps if it does not tell me !!


问:
getString of HttpRequest Being Sent on Android
Is there a way I can take an HttpGet object and see the exact text that will be sent over the wire?

I'm using ThreadSafeClientConnManager when I create my HttpClient.

HttpGet doesn't override toString() and the default headers aren't there when I call HttpGet.getAllHeaders().

答:
Have you tried HttpMethod's headerIterator() method? It returns a HeaderIterator which is described as follows:

Iterator that returns Header objects
  in the sequence they are sent over a
  connection.

The method is contained in the same class as getAllHeaders() (the superclass), but it's worth a shot. Also you may want to take a look at using a traffic monitor such as Fiddler to verify that you're correct in your header assumptions.

ContentLicense: CC BY-SA 2.5


问:
repeated measures bootstrap stats, grouped by multiple factors
I have a data frame that looks like this, but obviously with many more rows etc:

```<code>df <- data.frame(id=c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2),
                 cond=c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'),
                 comm=c('X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y','X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'),
                 measure=c(0.8, 1.1, 0.7, 1.2, 0.9, 2.3, 0.6, 1.1, 0.7, 1.3, 0.6, 1.5, 1.0, 2.1, 0.7, 1.2))
</code>```

So we have 2 factors (each with 2 levels, thus 4 combinations) and one continuous measure. We also have a repeated measures design in that we have multiple measure's within each cell that correspond to the same id.

I've attempted to first solve the groupby issue, then the bootstrap issue, then combine the two, but am pretty much stuck...

Stats, grouped by the 2 factors

I can get multiple summary stats for each of the 4 cells by:

```<code>summary_stats <- aggregate(df$measure,
                           by = list(df$cond, df$comm),
                           function(x) c(mean = mean(x), median = median(x), sd = sd(x)))
print(summary_stats)
</code>```

resulting in

```<code>  Group.1 Group.2     x.mean   x.median       x.sd
1       A       X 0.85000000 0.85000000 0.12909944
2       B       X 0.65000000 0.65000000 0.05773503
3       A       Y 1.70000000 1.70000000 0.58878406
4       B       Y 1.25000000 1.20000000 0.17320508
</code>```

This is great as we are getting multiple stats for each of the 4 cells.

But what I'd really like is the 95% bootstrap CI's, for each stat, for each of the 4 cells. I don't mind if I have to run a final solution once for statistic (e.g. mean, median, etc), but bonus points for doing it all in one go.

Bootstrap for repeated measures

Can't quite make this work, but what I want is 95% bootstrap CI's, done in a way which is appropriate for this repeated measures design. Unless I'm mistaken then I want to select bootstrap samples on the basis of id (not on the basis of rows of the dataframe), then calculate a summary measure (e.g. mean) for each of the 4 cells.

```<code>library(boot)
myfunc <- function(data, indices) {
   # select bootstrap sample to index into `id`
   d <- data[data$id==indicies,]
   return(c(mean=mean(d), median=median(d), sd = sd(d)))
}

bresults <- boot(data = CO2$uptake, statistic = myfunc, R = 1000)
</code>```

Q1: I'm getting errors in selecting the bootstrap sample by id, i.e. the line d <- data[ data$id==indicies, ]

Combining bootstrap and the groupby 2 factors

Q2: I have no intuition of how to gel the two approaches together to achieve the final desired result. My only idea is to put the aggregate call in myfunc, to repeatedly calculate cell stats under each bootstrap replicate, but I'm out of my comfort zone with R here.

答:
With your two questions, you have two issues:

How to bootstrap (resample) your data in such a way that you resample based on id, rather than rows

How to perform separate bootstraps for the four groups in your 2x2 design

One easy way to do this would be by using the following packages (all part of the tidyverse):

dplyr for manipulating your data (in particular, summarising the data you have for each id) and also for the neat %>% forward pipe operator which supplies the result of an expression as the first argument to the next expression so you can chain commands

broom for doing an operation for each group in your dataframe

boot (which you already use) for the bootstrapping

Load the packages:

```<code>library(dplyr)
library(broom)
library(boot)
</code>```

First of all, to make sure when we resample we include a subject or not, I would save the various values each subject has as a list:

```<code>df <- df %>%
    group_by(id, cond, comm) %>%
    summarise(measure=list(measure)) %>%
    ungroup()
</code>```

Now the dataframe has fewer rows (4 per ID), and the variable measure is not numeric anymore (instead, it's a list). This means we can just use the indices that boot provides (solving issue 1), but also that we'll have to "unlist" it when we actually want to do calculations with it, so your function now becomes:

```<code>myfunc <- function(data, indices) {
    data <- data[indices,]
    return(c(mean=mean(unlist(data$measure)),
             median=median(unlist(data$measure)),
             sd = sd(unlist(data$measure))))
}
</code>```

Now that we can simply use boot to resample each row, we can think about how to do it neatly per group. This is where the broom package comes in: you can ask it to do an operation for each group in your data frame, and store it in a tidy dataframe, with one row for each of your groups, and a column for the values that your function produces. So we simply group the dataframe again, and then call do(tidy(...)), with a . instead of the name of our variable. This hopefully solves issue 2 for you!

```<code>bootresults <- df %>%
    group_by(cond, comm) %>%
    do(tidy(boot(data = ., statistic = myfunc, R = 1000)))
</code>```

This produces:

```<code># Groups:   cond, comm [4]
     cond   comm   term  statistic         bias    std.error
   <fctr> <fctr>  <chr>      <dbl>        <dbl>        <dbl>
 1      A      X   mean 0.85000000  0.000000000 5.280581e-17
 2      A      X median 0.85000000  0.000000000 5.652979e-17
 3      A      X     sd 0.12909944 -0.004704999 4.042676e-02
 4      A      Y   mean 1.70000000  0.000000000 1.067735e-16
 5      A      Y median 1.70000000  0.000000000 1.072347e-16
 6      A      Y     sd 0.58878406 -0.005074338 7.888294e-02
 7      B      X   mean 0.65000000  0.000000000 0.000000e+00
 8      B      X median 0.65000000  0.000000000 0.000000e+00
 9      B      X     sd 0.05773503  0.000000000 0.000000e+00
10      B      Y   mean 1.25000000  0.001000000 7.283065e-02
11      B      Y median 1.20000000  0.027500000 7.729634e-02
12      B      Y     sd 0.17320508 -0.030022214 5.067446e-02
</code>```

Hopefully this is what you'd like to see!

If you want to then use the values from this dataframe a bit more, you can use other dplyr functions to select which rows in this table you look at. For example, to look at the bootstrapped standard error of the standard deviation of your measure for condition A / X, you can do the following:

```<code>bootresults %>% filter(cond=='A', comm=='X', term=='sd') %>% pull(std.error)
</code>```

I hope that helps!

Body:
I have a data frame that looks like this, but obviously with many more rows etc:

df <- data.frame(id=c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2),
                 cond=c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'),
                 comm=c('X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y','X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'),
                 measure=c(0.8, 1.1, 0.7, 1.2, 0.9, 2.3, 0.6, 1.1, 0.7, 1.3, 0.6, 1.5, 1.0, 2.1, 0.7, 1.2))

So we have 2 factors (each with 2 levels, thus 4 combinations) and one continuous measure. We also have a repeated measures design in that we have multiple measure's within each cell that correspond to the same id.

I've attempted to first solve the groupby issue, then the bootstrap issue, then combine the two, but am pretty much stuck...

Stats, grouped by the 2 factors

I can get multiple summary stats for each of the 4 cells by:

summary_stats <- aggregate(df$measure,
                           by = list(df$cond, df$comm),
                           function(x) c(mean = mean(x), median = median(x), sd = sd(x)))
print(summary_stats)

resulting in

  Group.1 Group.2     x.mean   x.median       x.sd
1       A       X 0.85000000 0.85000000 0.12909944
2       B       X 0.65000000 0.65000000 0.05773503
3       A       Y 1.70000000 1.70000000 0.58878406
4       B       Y 1.25000000 1.20000000 0.17320508

This is great as we are getting multiple stats for each of the 4 cells.

But what I'd really like is the 95% bootstrap CI's, for each stat, for each of the 4 cells. I don't mind if I have to run a final solution once for statistic (e.g. mean, median, etc), but bonus points for doing it all in one go.

Bootstrap for repeated measures

Can't quite make this work, but what I want is 95% bootstrap CI's, done in a way which is appropriate for this repeated measures design. Unless I'm mistaken then I want to select bootstrap samples on the basis of id (not on the basis of rows of the dataframe), then calculate a summary measure (e.g. mean) for each of the 4 cells.

library(boot)
myfunc <- function(data, indices) {
   # select bootstrap sample to index into `id`
   d <- data[data$id==indicies,]
   return(c(mean=mean(d), median=median(d), sd = sd(d)))
}

bresults <- boot(data = CO2$uptake, statistic = myfunc, R = 1000)

Q1: I'm getting errors in selecting the bootstrap sample by id, i.e. the line d <- data[ data$id==indicies, ]

Combining bootstrap and the groupby 2 factors

Q2: I have no intuition of how to gel the two approaches together to achieve the final desired result. My only idea is to put the aggregate call in myfunc, to repeatedly calculate cell stats under each bootstrap replicate, but I'm out of my comfort zone with R here.

Body:
With your two questions, you have two issues:

How to bootstrap (resample) your data in such a way that you resample based on id, rather than rows

How to perform separate bootstraps for the four groups in your 2x2 design

One easy way to do this would be by using the following packages (all part of the tidyverse):

dplyr for manipulating your data (in particular, summarising the data you have for each id) and also for the neat %>% forward pipe operator which supplies the result of an expression as the first argument to the next expression so you can chain commands

broom for doing an operation for each group in your dataframe

boot (which you already use) for the bootstrapping

Load the packages:

library(dplyr)
library(broom)
library(boot)

First of all, to make sure when we resample we include a subject or not, I would save the various values each subject has as a list:

df <- df %>%
    group_by(id, cond, comm) %>%
    summarise(measure=list(measure)) %>%
    ungroup()

Now the dataframe has fewer rows (4 per ID), and the variable measure is not numeric anymore (instead, it's a list). This means we can just use the indices that boot provides (solving issue 1), but also that we'll have to "unlist" it when we actually want to do calculations with it, so your function now becomes:

myfunc <- function(data, indices) {
    data <- data[indices,]
    return(c(mean=mean(unlist(data$measure)),
             median=median(unlist(data$measure)),
             sd = sd(unlist(data$measure))))
}

Now that we can simply use boot to resample each row, we can think about how to do it neatly per group. This is where the broom package comes in: you can ask it to do an operation for each group in your data frame, and store it in a tidy dataframe, with one row for each of your groups, and a column for the values that your function produces. So we simply group the dataframe again, and then call do(tidy(...)), with a . instead of the name of our variable. This hopefully solves issue 2 for you!

bootresults <- df %>%
    group_by(cond, comm) %>%
    do(tidy(boot(data = ., statistic = myfunc, R = 1000)))

This produces:

# Groups:   cond, comm [4]
     cond   comm   term  statistic         bias    std.error
   <fctr> <fctr>  <chr>      <dbl>        <dbl>        <dbl>
 1      A      X   mean 0.85000000  0.000000000 5.280581e-17
 2      A      X median 0.85000000  0.000000000 5.652979e-17
 3      A      X     sd 0.12909944 -0.004704999 4.042676e-02
 4      A      Y   mean 1.70000000  0.000000000 1.067735e-16
 5      A      Y median 1.70000000  0.000000000 1.072347e-16
 6      A      Y     sd 0.58878406 -0.005074338 7.888294e-02
 7      B      X   mean 0.65000000  0.000000000 0.000000e+00
 8      B      X median 0.65000000  0.000000000 0.000000e+00
 9      B      X     sd 0.05773503  0.000000000 0.000000e+00
10      B      Y   mean 1.25000000  0.001000000 7.283065e-02
11      B      Y median 1.20000000  0.027500000 7.729634e-02
12      B      Y     sd 0.17320508 -0.030022214 5.067446e-02

Hopefully this is what you'd like to see!

If you want to then use the values from this dataframe a bit more, you can use other dplyr functions to select which rows in this table you look at. For example, to look at the bootstrapped standard error of the standard deviation of your measure for condition A / X, you can do the following:

bootresults %>% filter(cond=='A', comm=='X', term=='sd') %>% pull(std.error)

I hope that helps!


问:
Entity Framework - Unable to load the specified metadata resource
I realise that this has been asked a number of times but I just can't seem to get the bottom of my issue. I'm getting the following error stack:

When I reflect out my dll I can see the following

Reading http://blogs.teamb.com/craigstuntz/2010/08/13/38628/ it suggests I'd expect to see the csdl, msl and ssdl files here, but they're not. They do exist here obj\Debug\edmxResourcesToEmbed though.

Never-the-less I tried to explicitly tell the web.config where to look by doing this:

```<code>...connectionString="metadata=res://DllName.dll/PaymentModel.csdl|res://DllName.dll/PaymentModel.ssdl|res://DllName.dll/PaymentModel.msl;provider=System.Data.SqlClient;provider ... />
</code>```

Which just throws an error saying it cannot find the dll:

Unable to resolve assembly 'DllName.dll'.

Very similar to this unresolved SO question Unable to resolve assembly Model.dll

The final thing I tried was to change the metadata line to:

```<code>...connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider ... />
</code>```

This threw a message about sql ce which I'm not using - is there a way to get round this??

Is there anything else I can try? Or can anyone see where I'm going wrong? Some extra detais:

Using EF 6 EDMX set to "Embedded Resource"

Copy to output directory:"Do not copy"

Metadata artifact processing: "Embed in output
assembly"

Finally on this - if I set the EDMX from Embedded Resource to EntityDeploy then this will work locally but not build on the build server as it throws the exact same error as this SO question:

Could not find the Conceptual Schema node to embed as a resource for input file

But the fix doesn't seem to help and I can't install .NET 4.5 on the server unfortunately.

答:
The connection string  "metadata=res" should be same as Edmx name. eg

```<code>metadata=res://*/EmployeeModel.csdl
</code>```

this EDMX name should be EmployeeModel

Body:
I realise that this has been asked a number of times but I just can't seem to get the bottom of my issue. I'm getting the following error stack:

When I reflect out my dll I can see the following

Reading http://blogs.teamb.com/craigstuntz/2010/08/13/38628/ it suggests I'd expect to see the csdl, msl and ssdl files here, but they're not. They do exist here obj\Debug\edmxResourcesToEmbed though.

Never-the-less I tried to explicitly tell the web.config where to look by doing this:

...connectionString="metadata=res://DllName.dll/PaymentModel.csdl|res://DllName.dll/PaymentModel.ssdl|res://DllName.dll/PaymentModel.msl;provider=System.Data.SqlClient;provider ... />

Which just throws an error saying it cannot find the dll:

Unable to resolve assembly 'DllName.dll'.

Very similar to this unresolved SO question Unable to resolve assembly Model.dll

The final thing I tried was to change the metadata line to:

...connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider ... />

This threw a message about sql ce which I'm not using - is there a way to get round this??

Is there anything else I can try? Or can anyone see where I'm going wrong? Some extra detais:

Using EF 6 EDMX set to "Embedded Resource"

Copy to output directory:"Do not copy"

Metadata artifact processing: "Embed in output
assembly"

Finally on this - if I set the EDMX from Embedded Resource to EntityDeploy then this will work locally but not build on the build server as it throws the exact same error as this SO question:

Could not find the Conceptual Schema node to embed as a resource for input file

But the fix doesn't seem to help and I can't install .NET 4.5 on the server unfortunately.

Body:
The connection string  "metadata=res" should be same as Edmx name. eg

metadata=res://*/EmployeeModel.csdl

this EDMX name should be EmployeeModel


问:
jquery fileupload Basic plugin and deleteing files
I'm implement this basic plugin https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin.
and it uploads file.

However for the life of me, I can't add any delete functionailty.
I have looked through the full plugin and googled and looked at other people implementations and am stumpted.

Has anyone managed this?
It would be great for the basic plugin page above to add this as a "How To"

Cheers for any help

答: Check your webhost hasn't disabled the DELETE method.</p>


问:
Serializing uploaded file data Django Rest Framework
I am trying to get a file upload system working in Django Rest Framework.

The files I want to upload are .gpx files which are custom xml files. I don't want to store the files in the database, instead I want to extract information from them and then input this into my model.

I have a function that takes a temp file and then extracts the info and then creates the model elements as needed. What I'm looking to do is perform some checks on the file before it is uploaded and passed to this function.

How should I do this?

The file upload is currently done as in the documentation (see below), which a generic APIView and a put command. This works perfectly, I just want to know what the best way is to check this file's validity before upload.

views.py

```<code>class FileUploadView(views.APIView):
    parser_classes = (FileUploadParser, )

    def put(self, request, filename, format=None):
        up_file = request.data['file']

        SaveGPXtoModel(up_file, request.user)

        return Response(status=204)
</code>```

Should the API do these checks or should it assume the file has already been validated?

In Django these checks would be handled by the form, should I use a serializer to do these checks?

If a serializer is the way to go then does it matter that there is one file as an input and various data points as an output?

答:
You can start by writing a serializer for your file, it doesn't have to be linked to a model:

```<code>class FileSerializer(serializers.Serializer):
    file = serializers.FileField()
</code>```

But fileField doesn't do any specific check. Depending on what you need to check, add a custom validator and use :

```<code>class FileSerializer(serializers.Serializer):
    file = serializers.FileField(validators=[validate_file])
</code>```

There is a nice example of how you could write a class based file validator here

Then use your serializer in your view :

```<code>class FileUploadView(APIView):
    parser_classes = (MultiPartParser, )

    def post(self, request):
        serializer = FileSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                data=serializer.errors,
                status=status.HTTP_400_BAD_REQUEST
            )
        ...
</code>```

Body:
I am trying to get a file upload system working in Django Rest Framework.

The files I want to upload are .gpx files which are custom xml files. I don't want to store the files in the database, instead I want to extract information from them and then input this into my model.

I have a function that takes a temp file and then extracts the info and then creates the model elements as needed. What I'm looking to do is perform some checks on the file before it is uploaded and passed to this function.

How should I do this?

The file upload is currently done as in the documentation (see below), which a generic APIView and a put command. This works perfectly, I just want to know what the best way is to check this file's validity before upload.

views.py

class FileUploadView(views.APIView):
    parser_classes = (FileUploadParser, )

    def put(self, request, filename, format=None):
        up_file = request.data['file']

        SaveGPXtoModel(up_file, request.user)

        return Response(status=204)

Should the API do these checks or should it assume the file has already been validated?

In Django these checks would be handled by the form, should I use a serializer to do these checks?

If a serializer is the way to go then does it matter that there is one file as an input and various data points as an output?

Body:
You can start by writing a serializer for your file, it doesn't have to be linked to a model:

class FileSerializer(serializers.Serializer):
    file = serializers.FileField()

But fileField doesn't do any specific check. Depending on what you need to check, add a custom validator and use :

class FileSerializer(serializers.Serializer):
    file = serializers.FileField(validators=[validate_file])

There is a nice example of how you could write a class based file validator here

Then use your serializer in your view :

class FileUploadView(APIView):
    parser_classes = (MultiPartParser, )

    def post(self, request):
        serializer = FileSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                data=serializer.errors,
                status=status.HTTP_400_BAD_REQUEST
            )
        ...


问:
Angular: Formatting numbers with commas
Title very much sums up my needs.

```<code>123456789 => 123,456,789
12345 => 12,345
</code>```

What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.

答:
Use DecimalPipe like this

{{attr | number}}

Working Plunker

Documentation available at https://angular.io/api/common/DecimalPipe

Title: Angular: Formatting numbers with commas

Body:
Title very much sums up my needs.

123456789 => 123,456,789
12345 => 12,345

What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.


问:
Why should I use fork() to daemonize my process?
According to my purpose, I just want to let my process be running in the background. Then I could write normal program and run it with the following command:
nohup myprogram  1>2 2>/dev/null &

Then this program will be running in the background, just like as a daemon.

With this way, I do not need to call fork() for running in background.
So my question is what is the difference to run program in background with the above command between using fork() function?

答:
TL;DR the fork() call is not needed, it just helps providing a nice UI for the users of the program.

A daemon uses fork() to create a duplicate of it. The child process then keeps running (in the background). The parent process may produce some output (status) then it exits.

Of course you can write only the child part of the program and launch it using the command line you posted:

```<code>$ nohup myprogram 1>2 2>/dev/null &
</code>```

But if you write the daemon and I have to use it, I certainly prefer to use a simpler command line, without all that scaffolding needed to put the program in background and ensure its output doesn't make it stop and so on:

```<code>$ myprogram        # there is no need for anything else
</code>```

Body:
TL;DR the fork() call is not needed, it just helps providing a nice UI for the users of the program.

A daemon uses fork() to create a duplicate of it. The child process then keeps running (in the background). The parent process may produce some output (status) then it exits.

Of course you can write only the child part of the program and launch it using the command line you posted:

$ nohup myprogram 1>2 2>/dev/null &

But if you write the daemon and I have to use it, I certainly prefer to use a simpler command line, without all that scaffolding needed to put the program in background and ensure its output doesn't make it stop and so on:

$ myprogram        # there is no need for anything else


问:
Positioning circle directly behind objects
How would I get the circular arrow behind the 7 items I have created. Similar to what shows in this picture: http://imgur.com/Zz6HqWZ I cant get it to work for some reason. Does anyone have any idea on how to achieve this? Anything helps, cheers.

.container .row {text-align:center; position:relative;}
.center {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left:-35px;
}

.circle {
  display:inline-block;
  background-color:#006850;
  width:85px;
  height:85px;
  border-width:3px;
  border-style:solid;
  border-color:#fefefe;
  border-radius:50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom:-15px;
}

.invisible {
  visibility:hidden;
  display:inline-block;
  background-color:#1f497d;
  width:130px;
  height:65px;
  border-width:3px;
  border-style:solid;
  border-color:#d6d6d6;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  color:#d0d3d8;
  width: 200px;
  height: 200px;
  border: 17px solid;
  border-radius: 50%;
  position: relative;
}
.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}
.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 106px;
  right: -25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="invisible"></div>
    <div class="circle"></div>
    <div class="invisible"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="arrow"></div>
</div></code>```

答:
To do what you want, you have to absolutely positioned your arrow and use z-index to make it above container and below your rows.
Here is the updated snippet:

.container {
  position: relative;
}
.container .row {
  text-align:center;
  position:relative;
}
.row{z-index:2;}
.center {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left:-35px;
}

.circle {
  display:inline-block;
  background-color:#006850;
  width:85px;
  height:85px;
  border-width:3px;
  border-style:solid;
  border-color:#fefefe;
  border-radius:50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom:-15px;
}

.invisible {
  visibility:hidden;
  display:inline-block;
  background-color:#1f497d;
  width:130px;
  height:65px;
  border-width:3px;
  border-style:solid;
  border-color:#d6d6d6;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 1;
  transform: translate(-50%, -50%) rotate(-110deg);
  color:#d0d3d8;
  width: 250px;
  height: 250px;
  border: 17px solid;
  border-radius: 50%;
}
.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}
.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 130px;
  right: -26px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="arrow"></div>
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="invisible"></div>
    <div class="circle"></div>
    <div class="invisible"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row">
    <div class="center"></div>
  </div>
</div></code>```

Hope this helps!

Body:
To do what you want, you have to absolutely positioned your arrow and use z-index to make it above container and below your rows.
Here is the updated snippet:

.container {
  position: relative;
}
.container .row {
  text-align:center;
  position:relative;
}
.row{z-index:2;}
.center {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.left {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.right {
  display:inline-block;
  background-color:#1f497d;
  width:100px;
  height:50px;
  border-width:3px;
  border-style:solid;
  border-color:#ededed;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
  margin-left:-35px;
}

.circle {
  display:inline-block;
  background-color:#006850;
  width:85px;
  height:85px;
  border-width:3px;
  border-style:solid;
  border-color:#fefefe;
  border-radius:50%;
  box-shadow: 0px 1px 5px #888888;
  margin-bottom:-15px;
}

.invisible {
  visibility:hidden;
  display:inline-block;
  background-color:#1f497d;
  width:130px;
  height:65px;
  border-width:3px;
  border-style:solid;
  border-color:#d6d6d6;
  border-radius:7px;
  box-shadow: 0px 1px 5px #888888;
}

.arrow {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 1;
  transform: translate(-50%, -50%) rotate(-110deg);
  color:#d0d3d8;
  width: 250px;
  height: 250px;
  border: 17px solid;
  border-radius: 50%;
}
.arrow:before {
  content: "";
  display: block;
  width: 30px;
  height: 50px;
  background: #fff;
  position: absolute;
  bottom: 0;
  top: 0;
  right: -22px;
  margin: auto;
}
.arrow:after {
  content: "";
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #d0d3d8;
  position: absolute;
  bottom: 130px;
  right: -26px;
}

<div class="container">
  <div class="arrow"></div>
  <div class="row">
    <div class="center"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="invisible"></div>
    <div class="circle"></div>
    <div class="invisible"></div>
  </div>
  <div class="row" style="margin-top:-15px;">
    <div class="left"></div>
    <div class="invisible"></div>
    <div class="right"></div>
  </div>
  <div class="row">
    <div class="center"></div>
  </div>
</div>

Hope this helps!


问:
Why the switch statement and not if-else?
I've been wondering this for some time now.  I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations.  For the real question:  What is the point of the switch statement?  Why can't you just use the if-else statement?

Thanks for your answer and if this has been asked before please point me to the link.

EDIT

S.Lott has pointed out that this may be a duplicate of questions If/Else vs. Switch.  If you want to close then do so.  I'll leave it open for further discussion.

答:
Besides the other mentioned Code readability and optimisation in .NET you also get the ability to switch on enums etc</p>

```<code>enum Color { Red, Green, Blue };

Color c = Color.Red;

switch (c) // Switch on the enum

{

// no casting and no need to understand what int value it is

case Color.Red:    break;
case Color.Green:  break;
case Color.Blue:   break;

}
</code>```

OwnerDisplayName: Casey

LastEditorDisplayName: Casey

Body:
Besides the other mentioned Code readability and optimisation in .NET you also get the ability to switch on enums etc

enum Color { Red, Green, Blue };

Color c = Color.Red;

switch (c) // Switch on the enum

{

// no casting and no need to understand what int value it is

case Color.Red:    break;
case Color.Green:  break;
case Color.Blue:   break;

}

OwnerDisplayName: Justin King


问:
Instagram API: How can I search for hashtags?
From what I'm seeing, I can't search for hashtags unless I have the public_content permission.

And I can't get the public_content permission unless I submit an app for review.

And I can't submit an app for review unless I have a video screencast and a very good reason as to why I need this permission. I just build websites for clients and they want to pull in posts that have one of their own hashtags. I don't see this on the list of approved application types.

Or is there another way to search for hashtags without having to go through all this?

答:
I am working with this right now. In your case, if you are only searching by one hashtag at each time you better use instafeed.js

http://instafeedjs.com

I have done this task with this library like this.

```<code>var feed = new Instafeed({
    get: 'tagged',
    tagName: audi',
    clientId: 'XXXXX',
    accessToken: 'XXXXX',
    template: '<li><a href="{{link}}"><img src="{{image}}" /></a></li>'
});
feed.run();
var feed = new Instafeed({
    get: 'tagged',
    tagName: 'ferrari',
    clientId: 'XXXXX',
    accessToken: 'XXXXX',
    template: '<li><a href="{{link}}"><img src="{{image}}" /></a></li>'
});
feed.run();
var feed = new Instafeed({
    get: 'tagged',
    tagName: 'BMW',
    clientId: 'XXXXX',
    accessToken: 'XXXXX',
    template: '<li><a href="{{link}}"><img src="{{image}}" /></a></li>'
});
feed.run();
</code>```

If anyone know how to search by 2 or more hashtags at each time please contact me.

Hope it helps you!

Body:
I am working with this right now. In your case, if you are only searching by one hashtag at each time you better use instafeed.js

http://instafeedjs.com

I have done this task with this library like this.

var feed = new Instafeed({
    get: 'tagged',
    tagName: audi',
    clientId: 'XXXXX',
    accessToken: 'XXXXX',
    template: '<li><a href="{{link}}"><img src="{{image}}" /></a></li>'
});
feed.run();
var feed = new Instafeed({
    get: 'tagged',
    tagName: 'ferrari',
    clientId: 'XXXXX',
    accessToken: 'XXXXX',
    template: '<li><a href="{{link}}"><img src="{{image}}" /></a></li>'
});
feed.run();
var feed = new Instafeed({
    get: 'tagged',
    tagName: 'BMW',
    clientId: 'XXXXX',
    accessToken: 'XXXXX',
    template: '<li><a href="{{link}}"><img src="{{image}}" /></a></li>'
});
feed.run();

If anyone know how to search by 2 or more hashtags at each time please contact me.

Hope it helps you!


问:
Hiding all elements that doesn't have a particular class nested deep in them
In this very webpage, have about 70 elements, all with the class "card".

Some of the about 70 elements holds another element with the class "pro-content", which is nested deep inside them.

In this image you could see 2 elements. One with the "pro-content" class and an one without, from left to right.

My aim is to hide all elements with this "pro-content" class and keep all others that doesn't have it.

Given the elements with "pro-content" are childNodes, I tried to use the following for...of loop:

```<code>let cardoo = document.querySelectorAll(".card");

for ( const element of cardoo ) {
    if ( !$(element).hasClass('pro-content') ) {
        element.style.display = "none";
    }
}
</code>```

Yet, this code doesn't work properly - It deletes all elements, instead just these without the "pro-content" class.

Note: I would have proffered a pure vanilla ES16 solution, especially to practice more of the ES16-DOMapi relations but if there is no other option, I would use a pure jQuery/ES16-jQuery solution.

答:
This should do the trick.</p>

```<code>$('.card').each((i, el) => {
    if ($(el).find('.pro-content').length) {
        $(el).hide();
    }
})
</code>```

Body:
In this very webpage, have about 70 elements, all with the class "card".

Some of the about 70 elements holds another element with the class "pro-content", which is nested deep inside them.

In this image you could see 2 elements. One with the "pro-content" class and an one without, from left to right.

My aim is to hide all elements with this "pro-content" class and keep all others that doesn't have it.

Given the elements with "pro-content" are childNodes, I tried to use the following for...of loop:

let cardoo = document.querySelectorAll(".card");

for ( const element of cardoo ) {
    if ( !$(element).hasClass('pro-content') ) {
        element.style.display = "none";
    }
}

Yet, this code doesn't work properly - It deletes all elements, instead just these without the "pro-content" class.

Note: I would have proffered a pure vanilla ES16 solution, especially to practice more of the ES16-DOMapi relations but if there is no other option, I would use a pure jQuery/ES16-jQuery solution.

Body:
This should do the trick.

$('.card').each((i, el) => {
    if ($(el).find('.pro-content').length) {
        $(el).hide();
    }
})


问:
MySQL query to return most used tags via pivot table
I have 3 tables:

```<code>threads (thread_id and thread_title)
tags (tag_id and tag_name)
tag_thread (pivot only with thread_id and tag_id)
</code>```

How can I formulate a query that gives me the names of the 5 tags that occur the most times in the latest 100 entries?

答:
This will give you the top 5 tags of the latest 100 threads</p>

```<code>select ta.tag_name
from tags ta
join tag_thread tt on tt.tag_id = ta.tag_id
join
(
   select * from threads order by thread_id desc limit 100
) th on tt.thread_id = th.thread_id
group by ta.tag_name
order by count(tt.thread_id) desc
limit 5
</code>```

Body:
I have 3 tables:

threads (thread_id and thread_title)
tags (tag_id and tag_name)
tag_thread (pivot only with thread_id and tag_id)

How can I formulate a query that gives me the names of the 5 tags that occur the most times in the latest 100 entries?

Body:
This will give you the top 5 tags of the latest 100 threads

select ta.tag_name
from tags ta
join tag_thread tt on tt.tag_id = ta.tag_id
join
(
   select * from threads order by thread_id desc limit 100
) th on tt.thread_id = th.thread_id
group by ta.tag_name
order by count(tt.thread_id) desc
limit 5


问:
Then is not a function promise error
I'm new to promises and I use the bluebird docs to get data from async code

what I tried is the following:

the error is:

getToken.then is not a function

How can I avoid it?

This file connection.js

```<code>return connection.getToken.then(function(connToken){

   console.log(connToken);

}).catch({

})
</code>```

This the code of getToken in moduleB

```<code>const request = require("request-promise");
const Promise = require("bluebird");
module.exports = {

    getToken: function () {

        return new Promise((resolve, reject) => {
            let options = {
                method: 'POST',
                url: 'https://authentication.arc.com/oauth/token',
                headers: {
                    grant_type: 'client_credentials',
                    authorization: 'Q0MDdmMCFiMTc0fGNvlQVRDWThDNDFsdkhibGNTbz0=',
                    accept: 'application/json;charset=utf-8',
                    'content-type': 'application/x-www-form-urlencoded'
                },
                form: {
                    grant_type: 'client_credentials',
                    token_format: 'opaque&response_type=token'
                }
            };

            request(options)
                .then(function (body) {

                    return body;
                })
                .catch(function (err) {
                    return err;
                });
        })

    }
}
</code>```

答:
You need to actually call the function.

connection.js

```<code>return connection.getToken() // note the parentheses ()
  .then(function(connToken){
    console.log(connToken);
  })
  .catch(function(error){
    console.error(error);
  });
</code>```

Title: Then is not a function promise error

Body:
I'm new to promises and I use the bluebird docs to get data from async code

what I tried is the following:

the error is:

getToken.then is not a function

How can I avoid it?

This file connection.js

return connection.getToken.then(function(connToken){

   console.log(connToken);

}).catch({

})

This the code of getToken in moduleB

const request = require("request-promise");
const Promise = require("bluebird");
module.exports = {

    getToken: function () {

        return new Promise((resolve, reject) => {
            let options = {
                method: 'POST',
                url: 'https://authentication.arc.com/oauth/token',
                headers: {
                    grant_type: 'client_credentials',
                    authorization: 'Q0MDdmMCFiMTc0fGNvlQVRDWThDNDFsdkhibGNTbz0=',
                    accept: 'application/json;charset=utf-8',
                    'content-type': 'application/x-www-form-urlencoded'
                },
                form: {
                    grant_type: 'client_credentials',
                    token_format: 'opaque&response_type=token'
                }
            };

            request(options)
                .then(function (body) {

                    return body;
                })
                .catch(function (err) {
                    return err;
                });
        })

    }
}

Body:
You need to actually call the function.

connection.js

return connection.getToken() // note the parentheses ()
  .then(function(connToken){
    console.log(connToken);
  })
  .catch(function(error){
    console.error(error);
  });


问:
Generate meaningful image description based on image labels
Currently me and three of my friends are working on a project to generate an image description based on the objects in that particular image (When an image is given to the system novel description has to be generated based on the objects and relationship among them). So simply one person is planning to identify objects in the image and label them using a Fast Regional based CNN (FRCNN). In my part I have to implement a meaningful description based on those image labels (Output of the FRCNN is planning to take as the input to my RNN) by considering the relationship among them.

Currently I'm planning to implement a Recurrent neural network (RNN) to generate the description. but however I have a doubt that whether is it possible to generate a description using an RNN when it is just given set of words (Image label names) as an input. since RNNs are mainly used for use cases which have sequences and if I just give label names will it be able to generate a description by considering the relationship among them ?

If not can anyone please tell me what would be the best way to implement this ?

PS: I'm very new to machine learning and hope to get a clear idea to come to a better solution.

答:
Actually I am also learning RNN right now. And I believe from one single image, it is possible to generate one sentence to describe it, if the image is meaningful.

I will share you some material that I think it is helpful

https://www.google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&ved=0ahUKEwjf_pKusPLUAhUTrRQKHQjMAlcQFgg2MAI&url=https%3A%2F%2Fcs224d.stanford.edu%2Freports%2Fmsoh.pdf&usg=AFQjCNHqAkpk6haw87Cx3X23TDjRBFN6aA


问:
How do I serialize data with Sequel and Ruby?
I have a table which should store an id, a name and a hash. How do I serialize the Hash? (I'm using Ruby and Sequel as ORM.)</p>

答:
You may give YAML a try:

```<code>require 'yaml'

# encode
my_hash = { :first => "John", :age => 23 }
encoded = YAML.dump(my_hash)

# decode
my_hash = YAML.load(encoded)
</code>```

You can store it in a Sequel String, it works with complex objects, and it is readable in the DB. I read about it here.

Body:
You may give YAML a try:

require 'yaml'

# encode
my_hash = { :first => "John", :age => 23 }
encoded = YAML.dump(my_hash)

# decode
my_hash = YAML.load(encoded)

You can store it in a Sequel String, it works with complex objects, and it is readable in the DB. I read about it here.


问:
iPhone testing on device
With my iPhone connected to my mac via 30-pin connector (standard apple/iphone cable) I of course test and run my app with Xcode building it to run on the device.

For some reason though, when I build and run, it installs on my device but doesn't go further than the loading screen of the app with Default.png showing.

Then if I stop the build in Xcode it quit the application, then I run in manually on my device and the new build is there for me to test, but I just don't know why I have to do that and it doesn't just run past the loading screen when building?

答: This happened to me once after I added some certificates. I removed the build directory (MyApp/build/) and then did a clean and then build again, and everything miraculously worked. You might try that.</p>

Title: iPhone testing on device