问:
Set proxy in Guzzle
I have a problem with set proxy in guzzle that a blank page was shown while with curl everything works perfect. The code that I used in guzzle and curl came below.
What is wrong with this code:
Guzzle:

```<code>use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

require_once "vendor/autoload.php";

try {
  $client = new Client();
  $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
  $response = $client->send($request, [
      'timeout'  => 30,
      'curl'  => [
          'CURLOPT_PROXY' => '*.*.*.*',
          'CURLOPT_PROXYPORT' => *,
          'CURLOPT_PROXYUSERPWD' => '*:*',
      ],

  ]);
  echo '```';
  echo($response->getBody());
  exit;
} catch (RequestException $e) {
  echo $e->getRequest();
  if ($e->hasResponse()) {
      echo $e->getResponse();
  }
}
```

<p>And The code with CURL:</p>

```$url = 'http://httpbin.org';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_PROXY, '*.*.*.*');
curl_setopt($ch, CURLOPT_PROXYPORT, *);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, '*:*');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$page = curl_exec($ch);
echo $page;
```

Thanks.

答:
For Guzzle6, I think the best way is to implement a middleware for setting proxy.

From Guzzle6 docs:

request-options.proxy

handlers-and-middleware

We can set proxy as below:

```<code>use Psr\Http\Message\RequestInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
use Util\Api;
function add_proxy_callback($proxy_callback) {
    return function (callable $handler) use ($proxy_callback) {
        return function (RequestInterface $request,$options) use ($handler,$proxy_callback) {
            $ip = $proxy_callback();
            $options['proxy'] = $ip;
            return $handler($request,$options);
        };
    };
}
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(add_proxy_callback(function() {
    return Api::getIp(); //function return a ip
}));
$client = new Client(['handler'=>$stack]);
$response = $client->request('GET','http://httpbin.org/ip');
var_dump((string)$response->getBody());
</code>```

Title: Set proxy in Guzzle

Body:
I have a problem with set proxy in guzzle that a blank page was shown while with curl everything works perfect. The code that I used in guzzle and curl came below.
What is wrong with this code:
Guzzle:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

require_once "vendor/autoload.php";

try {
  $client = new Client();
  $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
  $response = $client->send($request, [
      'timeout'  => 30,
      'curl'  => [
          'CURLOPT_PROXY' => '*.*.*.*',
          'CURLOPT_PROXYPORT' => *,
          'CURLOPT_PROXYUSERPWD' => '*:*',
      ],

  ]);
  echo '
';
  echo($response->getBody());
  exit;
} catch (RequestException $e) {
  echo $e->getRequest();
  if ($e->hasResponse()) {
      echo $e->getResponse();
  }
}

And The code with CURL:

$url = 'http://httpbin.org';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_PROXY, '*.*.*.*');
curl_setopt($ch, CURLOPT_PROXYPORT, *);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, '*:*');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$page = curl_exec($ch);
echo $page;

Thanks.

Body:
For Guzzle6, I think the best way is to implement a middleware for setting proxy.

From Guzzle6 docs:

request-options.proxy

handlers-and-middleware

We can set proxy as below:

use Psr\Http\Message\RequestInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
use Util\Api;
function add_proxy_callback($proxy_callback) {
    return function (callable $handler) use ($proxy_callback) {
        return function (RequestInterface $request,$options) use ($handler,$proxy_callback) {
            $ip = $proxy_callback();
            $options['proxy'] = $ip;
            return $handler($request,$options);
        };
    };
}
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(add_proxy_callback(function() {
    return Api::getIp(); //function return a ip
}));
$client = new Client(['handler'=>$stack]);
$response = $client->request('GET','http://httpbin.org/ip');
var_dump((string)$response->getBody());


来源: stackexchange

问:
How to create queryset expression containing different types
I have two models like:

```<code>class Category(models.Model):
    title = models.CharField(max_length=100)
    expires_in_days = models.PositiveIntegerField(default=20)

class Item(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100)
    description = models.TextField()
    category = models.ForeignKey(Category)
</code>```

And I need to determine which items I should set expired:

```<code>items_to_cancel = Item.objects.annotate(expires_date=F('created') + F('category__expires_in_days'))\
                             .filter(expires_date__lte=timezone.now().date())
</code>```

Running this query raises an exception:

```<code>FieldError: Expression contains mixed types. You must set output_field.
</code>```

UPDATE

After I updated the query to

```<code>items_to_cancel = Item.objects.annotate(expires_date=ExpressionWrapper(F('created') + F('category__expires_in_days'), output_field=DateField()))\
                             .filter(expires_date__lte=timezone.now().date())
</code>```

I got this exception:

```<code>ProgrammingError: operator does not exist: timestamp with time zone + integer.
</code>```

So now I can't figure out how I can get date from timestamp.

答:
Thanks to Daniel Roseman for his comment about ExpressionWrapper. But I had to make one more update to make it work, I had to apply TruncDate function to the timestamp:

```<code>from django.db.models.functions import TruncDate

items_to_cancel = Item.objects.annotate(
        expires_date=ExpressionWrapper(
            TruncDate('created') + F('category__expires_in_days'),
            output_field=DateField()
        )
    ).filter(expires_date__lte=timezone.now().date())
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two models like:

class Category(models.Model):
    title = models.CharField(max_length=100)
    expires_in_days = models.PositiveIntegerField(default=20)

class Item(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100)
    description = models.TextField()
    category = models.ForeignKey(Category)

And I need to determine which items I should set expired:

items_to_cancel = Item.objects.annotate(expires_date=F('created') + F('category__expires_in_days'))\
                             .filter(expires_date__lte=timezone.now().date())

Running this query raises an exception:

FieldError: Expression contains mixed types. You must set output_field.

UPDATE

After I updated the query to

items_to_cancel = Item.objects.annotate(expires_date=ExpressionWrapper(F('created') + F('category__expires_in_days'), output_field=DateField()))\
                             .filter(expires_date__lte=timezone.now().date())

I got this exception:

ProgrammingError: operator does not exist: timestamp with time zone + integer.

So now I can't figure out how I can get date from timestamp.

Body:
Thanks to Daniel Roseman for his comment about ExpressionWrapper. But I had to make one more update to make it work, I had to apply TruncDate function to the timestamp:

from django.db.models.functions import TruncDate

items_to_cancel = Item.objects.annotate(
        expires_date=ExpressionWrapper(
            TruncDate('created') + F('category__expires_in_days'),
            output_field=DateField()
        )
    ).filter(expires_date__lte=timezone.now().date())


问:
Error in finding user id from chatbox name
I am currently doing a project on online chatbox. However, i was stuck when I need to get the id of friends of the user by getting the name of the friend(eg. when i have Ivan in my friendList, I can get his id in the database) when logging in the server. I can get the name of the friend, say, Ivan, but i tried many times and still dont know how to use the name i found to find the id of Ivan in the server. I am using mongodb and node.js to do this project. Here is my current code:

```<code>router.get('/load', function(req, res)
var db = req.db;
var collection = db.get('userList')
if(req.session.userId)
{
 var id = req.session.userId;
 collection.find({"_id": id},{fields:{"_id":0, "friends.name":1}}, function(err, docs)
 res.json(docs);
 )}
 }
</code>```

And here's what the database structure kind of looks like:

```<code>{
 "_id": ObjectId(5a23e06aa11f6589e02d8fcf),
 "name": "Ken",
 "password": "12345678",
 "friends":[
   {
     "name" : "Andy",
     "lastmsg": "0"
    },
    {
     "name" : "Ivan",
      "lastmsg" : "1"
     }
    ]
 }
</code>```

答:
Did you try</p>

```<code>collection.findOne({"friends.name": "Ivan"}, function(err, docs)
 res.json(docs);
)}
</code>```

Body:
I am currently doing a project on online chatbox. However, i was stuck when I need to get the id of friends of the user by getting the name of the friend(eg. when i have Ivan in my friendList, I can get his id in the database) when logging in the server. I can get the name of the friend, say, Ivan, but i tried many times and still dont know how to use the name i found to find the id of Ivan in the server. I am using mongodb and node.js to do this project. Here is my current code:

router.get('/load', function(req, res)
var db = req.db;
var collection = db.get('userList')
if(req.session.userId)
{
 var id = req.session.userId;
 collection.find({"_id": id},{fields:{"_id":0, "friends.name":1}}, function(err, docs)
 res.json(docs);
 )}
 }

And here's what the database structure kind of looks like:

{
 "_id": ObjectId(5a23e06aa11f6589e02d8fcf),
 "name": "Ken",
 "password": "12345678",
 "friends":[
   {
     "name" : "Andy",
     "lastmsg": "0"
    },
    {
     "name" : "Ivan",
      "lastmsg" : "1"
     }
    ]
 }

Body:
Did you try

collection.findOne({"friends.name": "Ivan"}, function(err, docs)
 res.json(docs);
)}


问:
Consequences of Java 32bit on Win(any) 64bit?
I am trying to install JAI (Java Advanced Imaging) 1.1.3 in my Vista 64 and it says that in order for it to be installed JDK 1.3 and up must be installed. The problem is that I have already installed the latest JDK for Win64 and it seems that it is not willing to work with it.

I would like to know if there are any severe consequences if I install JDK 32bit instead of the 64bit in Vista 64.

Thanks in advance for any advice on the subject!

John

答:
I have the 32-bit JDK (1.6.0_11) installed on Vista x64 and can report no ill effects so far (after 3 months of use).

Just remember it goes in Program File (x86) rather than in plain old Program Files.

OwnerDisplayName: imoschak

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Leonard H Martin


问:
CSS - jpg image repeating
I am re-writing a website and i have inserted a background.
The background image is repeating.
I've tried various ways on setting the repeat = n without any luck.

Here is the current html section:

```<code><html xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Site down | Maintenance</title>
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
    <style type='text/css'>
        html,
        body {
            padding: 0;
            border: 0
        }

        .Header_image {
            padding- left: 20px
        }

        h1 {
            font-family: "verdana";
            padding: 0px;
            margin: 0px;
            font- size: 16pt;
            color: #D5261e
        }

        h3 {
            font-family: "verdana";
            padding: 0px;
            margin: 1px;
            font-size: 11pt;
        }

        p {
            font-family: "verdana";
            font-size: 13;
        }

        div.wide_rhn {
            padding-bottom: 17px
        }

        div.pg_three_col_border {
            BORDER-right: #e8e8e8 1px solid;
            BORDER-left: #e8e8e8 1px solid;
            background-color: #FFFFFF;
            PADDING-TOP: 11px;
            PADDING- LEFT: 17px;
            padding-bottom: 11px;
            font-family: arial;
            font-size: 75%;
            width: 763px;
            ^width: 782px
        }

        table.HP_table_header {
            position: relative;
            z-index: 200;
            padding- bottom: 10px;
            padding-top: 10px;
            *padding-bottom: 12px
        }

        td.HP_mainmenu {
            border: #878787 1px solid
        }

        table.HP_Image_table {
            MARGIN-LEFT: 124px;
            MARGIN-TOP: 1000px
        }
    </style>
</head>

<body background="man-with-no-shoes.jpg">

    <table class='HP_table_header' width='960' align='center' border='0' cellpadding='0' cellspacing='0'>
        <tbody>
            <tr>
                <td class='Header_image' width='189' align='left' height='74'>
                    <img src='images/test_logo.jpg' border='0' />
                </td>
            </tr>
        </tbody>
    </table>
    <table class='bg_body' width='1006' align='center' border='0' cellpadding='0' cellspacing='0' style='height: 500px;'>
        <tbody>
            <tr>
                <td valign='top'>
                    <table width='960' align='center' border='0' cellpadding='0' cellspacing='0'>
                        <tbody>
                            <tr>
                                <td valign='top' width='782' align='left'>
                                    <div id='WiderhPagetitlemain'>
</code>```

答:
Try using background-repeat:

https://www.w3schools.com/cssref/pr_background-repeat.asp

You can then use:

```<code>background-repeat: no-repeat;
</code>```

If you have your background on body, you simply do:

```<code>body {
    background-repeat: no-repeat;
}
</code>```

That means - in your code in

Title: CSS - jpg image repeating

Body:
I am re-writing a website and i have inserted a background.
The background image is repeating.
I've tried various ways on setting the repeat = n without any luck.

Here is the current html section:

    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Site down | Maintenance</title>
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">

Body:
Try using background-repeat:

https://www.w3schools.com/cssref/pr_background-repeat.asp

You can then use:

background-repeat: no-repeat;

If you have your background on body, you simply do:

body {
    background-repeat: no-repeat;
}

That means - in your code in <style type='text/css'> you simply add following:

    body {
        background-repeat: no-repeat;
    }

Also, please note it is usually better to set your background image in CSS rather than in HTML as you have better separation of concerns:

Html is responsible for content and structure

Css is responsible for visuals

You can set background image in CSS using background-image property:

body {
   background-image: url("background.jpg");
}

Having said that, it is also a good idea to move your CSS to a separate file rather than having everything in your HTML - again, the separation is better.

You can then link your new file like this:

<link rel="stylesheet" type="text/css" href="my-new-stylesheet.css">


问:
Delete mongo recored by the timestamp in its id
This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its _id. I do not have any date, createdAt fields as I see that mongo uses its _id for the createdAt timestamp.

How do I delete a recored, say created 30 days ago, using this gist?

```<code>const date = new Date();
const daysToDeletion = 30;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

const db = <your-database>

db.messages.remove({_id : {$lt : deletionDate}});
</code>```

The above returns a CastError

What would work, and as Ive said, I do not have a createdAt field:

```<code>db.messages.remove({createdAt : {$lt : deletionDate}});
</code>```

答:
var id = new ObjectId(  Math.floor(deletionDate .getTime() / 1000).toString(16) + "0000000000000000")

db.messages.remove({createdAt : {$lt : id}});

Body:
This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its _id. I do not have any date, createdAt fields as I see that mongo uses its _id for the createdAt timestamp.

How do I delete a recored, say created 30 days ago, using this gist?

const date = new Date();
const daysToDeletion = 30;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

const db = <your-database>

db.messages.remove({_id : {$lt : deletionDate}});

The above returns a CastError

What would work, and as Ive said, I do not have a createdAt field:

db.messages.remove({createdAt : {$lt : deletionDate}});


问:
Ternary operator is not working scala
I'm trying to make a ternary operator in scala but actually it seems that the '?' character cannot be resolved

here is the completed method

```<code>object Credit {
  def getMaximumWeek(orderId: Int, locale: String): Int = {
    val orderCompletedHistoryCount = Order.getOrderCompletedHistoryCount(orderId, locale);
   orderCompletedHistoryCount == 0 ? 0: Order.getMaximumAllowedWeeks(orderId, locale)
  }
}
</code>```

referenced to this link
,I'm getting an error connot resolve symbol '?' even both method are returning integers

答:
Scala does not have a ternary operator, like the ? operator C++ has for example, so the error is expected, regardless of what the two operadans return.

Use an if-else expression instead, like this:

```<code>if(orderCompletedHistoryCount == 0)
    0
else
    Order.getMaximumAllowedWeeks(orderId, locale)
</code>```

Title: Ternary operator is not working scala

Body:
I'm trying to make a ternary operator in scala but actually it seems that the '?' character cannot be resolved

here is the completed method

object Credit {
  def getMaximumWeek(orderId: Int, locale: String): Int = {
    val orderCompletedHistoryCount = Order.getOrderCompletedHistoryCount(orderId, locale);
   orderCompletedHistoryCount == 0 ? 0: Order.getMaximumAllowedWeeks(orderId, locale)
  }
}

referenced to this link
,I'm getting an error connot resolve symbol '?' even both method are returning integers

Body:
Scala does not have a ternary operator, like the ? operator C++ has for example, so the error is expected, regardless of what the two operadans return.

Use an if-else expression instead, like this:

if(orderCompletedHistoryCount == 0)
    0
else
    Order.getMaximumAllowedWeeks(orderId, locale)


问:
Hyperlink combined with pseudo code
In the code below, how can I have the same font color for the hyperlinks as for the other text? It now seems to morph with the color as defined in the pseudo code.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav>ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav>ul>li {
  margin-right: 2em;
}

nav>ul>li.header-button {
  position: relative;
  padding: 1em;
}

nav>ul>li.header-button::before {
  content: '';
  width: 100%;
  height: 70%;
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="header-logo">
    <img src="http://via.placeholder.com/50x50" alt="" />
  </div>
  <ul>
    <li>Option1</li>
    <li>Option2</li>
    <li class="header-button">Option3</li>
    <li class="header-button">Option4</li>
  </ul>
</nav></code>```

答:
Your :before is overdone and its semitransparent „back“ground overlaps the actual link color (since it's positioned absolute...).

You don't need that. You could fix by z-index, but better do that background directly and way more natural on your links. (Which you want to be clickable, right?). And probably you want to have an inner span for your non-links, to ensure same padding and space:

```<code><nav>
  <div class="header-logo">
    <a href="#"><img src="http://via.placeholder.com/50x50" alt="" /></a>
  </div>
  <ul>
    <li><span>Option1</span></li>
    <li><span>Option2</span></li>
    <li class="header-button"><a href="#">Option3</a></li>
    <li class="header-button"><a href="#">Option4</a></li>
  </ul>
</nav>
</code>```

css:

```<code>ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav ul li {
  margin-right: 2em;
}

nav ul li a, nav ul li span {
  padding: 10px;
}
nav ul li a {
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
}

nav ul li.header-button {
  position: relative;
  padding: 1em;
}
</code>```

Looks like this:

Btw, almost certainly you will be better of with display:table for your
, display: table-cell for your li. Using flex is most certainly overdone...

Title: Hyperlink combined with pseudo code

Body:
In the code below, how can I have the same font color for the hyperlinks as for the other text? It now seems to morph with the color as defined in the pseudo code.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav>ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav>ul>li {
  margin-right: 2em;
}

nav>ul>li.header-button {
  position: relative;
  padding: 1em;
}

nav>ul>li.header-button::before {
  content: '';
  width: 100%;
  height: 70%;
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}

Option1

Option2

Option3

Option4

Body:
Your :before is overdone and its semitransparent „back“ground overlaps the actual link color (since it's positioned absolute...).

You don't need that. You could fix by z-index, but better do that background directly and way more natural on your links. (Which you want to be clickable, right?). And probably you want to have an inner span for your non-links, to ensure same padding and space:

<nav>
  <div class="header-logo">
    <a href="#"><img src="http://via.placeholder.com/50x50" alt="" /></a>
  </div>
  <ul>
    <li><span>Option1</span></li>
    <li><span>Option2</span></li>
    <li class="header-button"><a href="#">Option3</a></li>
    <li class="header-button"><a href="#">Option4</a></li>
  </ul>
</nav>

css:

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav ul li {
  margin-right: 2em;
}

nav ul li a, nav ul li span {
  padding: 10px;
}
nav ul li a {
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
}

nav ul li.header-button {
  position: relative;
  padding: 1em;
}

Looks like this:

Btw, almost certainly you will be better of with display:table for your <ul>, display: table-cell for your li. Using flex is most certainly overdone...


问:
Why doesn't git fetch update local branch?
I have the following scenario:

I have my remote branch equal to my local branch. Then I made some changes in the remote branch and some different changes in my local branch.

My idea is to run git fetch, to sync my local branch, then check the differences, and then push everything, but it simply doesn't work! (git fetch seems to not get the changes made in the remote branch before)
I know running git pull "fixes" this, or git push -f but I want to review the changes before commit.

Why doesn't git fetch work as expected? Or how can I otherwise review the differences before commit?

答:
To view the differences between your local branch and the remote branch before merging them, you can use git diff, as outlined in this question, after executing git fetch.

If you want to execute the merge of your remote branch with your local branch without committing it immediately to allow you to review the result, you can use git pull --no-commit (as described on git-scm.com). The --no-commit option prevents Git from automatically committing a merge that may be part of the pull, which would allow you to review the merge result before committing it.


问:
Is babel-cli plus presets all I need to compile ES6 to ES5?
Is it sufficient to only install the so-called 'babel-cli' locally plus presets (es2015, react etc.) in the project-folder to compile ES6-code?

That's all?

I can remember that there is another model 'babel' which has to be installed globally.

答:
You can install Babel (i.e. babel-cli) locally or globally, it's your choice. The Babel authors recommend local installation, quote from the documentation:

While you can install Babel CLI globally on your machine, it’s much
  better to install it locally project by project.

There are two primary reasons for this.

Different projects on the same machine can depend on different
  versions of Babel allowing you to update one at a time.

It means you
  do not have an implicit dependency on the environment you are working
  in. Making your project far more portable and easier to setup.

So the answer to your question would be: Yes, that's all.


问:
Get Device info through pymodbus
I need to get device information (device name, etc) through pymodbus.
Does anyone know how to accomplish that?

Thanks

答:
If you are communicating through a serial port (usb-/comport) you can get a list of serial devices on Comports using list_ports from serial:

64bit python:

```<code>import serial.tools.list_ports as portlist
for port in portlist.comports():
    print(port)
    print(port.device)
</code>```

Outputs:

COM10 - Serial USB-device (COM10)

USB VID:PID=15A2:0300 SER=6 LOCATION=1-4.3

For my Modbus device on Comport 10

32-bit python:

```<code>import serial.tools.list_ports as portlist
for port in portlist.comports():
    print(port)
</code>```

Outputs a tuple including device name, vendor id, product id etc.

Title: Get Device info through pymodbus

Body:
If you are communicating through a serial port (usb-/comport) you can get a list of serial devices on Comports using list_ports from serial:

64bit python:

import serial.tools.list_ports as portlist
for port in portlist.comports():
    print(port)
    print(port.device)

Outputs:

COM10 - Serial USB-device (COM10)

USB VID:PID=15A2:0300 SER=6 LOCATION=1-4.3

For my Modbus device on Comport 10

32-bit python:

import serial.tools.list_ports as portlist
for port in portlist.comports():
    print(port)

Outputs a tuple including device name, vendor id, product id etc.


问:
dataframe + pandas + select specific rows
I'm new in using pandas and one of my functions does not behave as expected. I have this dataframe:

```<code>     title_year        gross
0          2009  7.60506e+08
1          2007  3.09404e+08
2          2015  2.00074e+08
3          2012  4.48131e+08
5          2012  7.30587e+07
6          2007   3.3653e+08
7          2010  2.00807e+08
8          2015  4.58992e+08
9          2009  3.01957e+08
</code>```

The function is:

```<code>def analysis_gross_per_year(year1, year2):
    year_df = data[['title_year', 'gross']]
    check = True
    year_df.title_year = year_df.title_year.fillna('Not Given')
    year_df.gross = year_df.gross.fillna('Not Given')
    year_df = year_df[year_df.gross != 'Not Given']
    gross_year = year_df[year_df.title_year.str.contains(year1, na=True)]
    number = int(year1)
    while check :
        if str(number) == year2:
            check = False
        else:
            number = number + 1
            df1 = year_df[year_df.title_year.str.contains(str(number), na=False)]
            gross_year = pd.concat([gross_year, df1])
            print (df1)
</code>```

I give the function 2 parameters year 1 and year 2 and it should display a line graph for average, min, max based on gross earning for the years provided.

E.g if 2013 and 2015. It should display a line graph for 2013, 2014, 2015. However when I run str.contains(year1, na=True) it returns an empty dataframe. Can you tell me why ?

答:
Provided your title_year column is cast to an int, you could do something like the following.

```<code>import matplotlib.pyplot as plt
%matplotlib inline

def range_plot(year1, year2, agg):
    for a in agg: # iterate through aggregate methods
        _ = df[df['title_year'].between(year1, year2)] # subset DataFrame to contain only the year ranges specified
        _ = _.groupby('title_year').agg(a) # groupby title_year, compute summary statistic
        plt.plot(_.index.values, _['gross'], label=a) # plot

    plt.legend() # display legend
    plt.xlabel('Year')
    plt.ylabel('Gross')
    plt.title("{} - {}".format(year1, year2))
</code>```

year1 and year2 are ints, and agg is a list of those aggregate functions you want to plot.

```<code>range_plot(2009, 2015, ['mean', 'sum', 'min', 'max'])
</code>```

Body:
I'm new in using pandas and one of my functions does not behave as expected. I have this dataframe:

     title_year        gross
0          2009  7.60506e+08
1          2007  3.09404e+08
2          2015  2.00074e+08
3          2012  4.48131e+08
5          2012  7.30587e+07
6          2007   3.3653e+08
7          2010  2.00807e+08
8          2015  4.58992e+08
9          2009  3.01957e+08

The function is:

def analysis_gross_per_year(year1, year2):
    year_df = data[['title_year', 'gross']]
    check = True
    year_df.title_year = year_df.title_year.fillna('Not Given')
    year_df.gross = year_df.gross.fillna('Not Given')
    year_df = year_df[year_df.gross != 'Not Given']
    gross_year = year_df[year_df.title_year.str.contains(year1, na=True)]
    number = int(year1)
    while check :
        if str(number) == year2:
            check = False
        else:
            number = number + 1
            df1 = year_df[year_df.title_year.str.contains(str(number), na=False)]
            gross_year = pd.concat([gross_year, df1])
            print (df1)

I give the function 2 parameters year 1 and year 2 and it should display a line graph for average, min, max based on gross earning for the years provided.

E.g if 2013 and 2015. It should display a line graph for 2013, 2014, 2015. However when I run str.contains(year1, na=True) it returns an empty dataframe. Can you tell me why ?

Body:
Provided your title_year column is cast to an int, you could do something like the following.

import matplotlib.pyplot as plt
%matplotlib inline

def range_plot(year1, year2, agg):
    for a in agg: # iterate through aggregate methods
        _ = df[df['title_year'].between(year1, year2)] # subset DataFrame to contain only the year ranges specified
        _ = _.groupby('title_year').agg(a) # groupby title_year, compute summary statistic
        plt.plot(_.index.values, _['gross'], label=a) # plot

    plt.legend() # display legend
    plt.xlabel('Year')
    plt.ylabel('Gross')
    plt.title("{} - {}".format(year1, year2))

year1 and year2 are ints, and agg is a list of those aggregate functions you want to plot.

range_plot(2009, 2015, ['mean', 'sum', 'min', 'max'])


问:
BitPay API gateway payment Bitcoin - pairing
I am struggling with bitpay API.
So far i generated public,priate and sin keys.
I stored them and now i want to pair with special key from bitpay.com
Here is my error and below its my whole code.
Anyone can help ?</p>

```<code>Public Key: 0309f03bc0d566c411aeb55b8be57b0485d28706ace9b1a198d053212bde06d718 Private Key: 77cec96ea11e3d35ec2817db6951167755095f8a45c508028ca22734fe7e9962 Sin Key: Tf2XSANqca54VHQG31RXjAY5EKdyaysHtct
Fatal error: Uncaught Bitpay\Client\ArgumentException: pairing code is not legal in /var/www/dev.simplemining.net/vendor/bitpay/php-client/src/Bitpay/Client/Client.php:494 Stack trace: #0 /var/www/dev.simplemining.net/controller/account.php(65): Bitpay\Client\Client->createToken(Array) #1 /var/www/dev.simplemining.net/index.php(20): require('/var/www/dev.si...') #2 {main} thrown in /var/www/dev.simplemining.net/vendor/bitpay/php-client/src/Bitpay/Client/Client.php on line 494

require __DIR__ . '/../vendor/autoload.php';
$private = new \Bitpay\PrivateKey('/tmp/private.key');
$public  = new \Bitpay\PublicKey('/tmp/public.key');
$sin     = new \Bitpay\SinKey('/tmp/sin.key');
// Generate Private Key values
$private->generate();
// Generate Public Key values
$public->setPrivateKey($private);
$public->generate();
// Generate Sin Key values
$sin->setPublicKey($public);
$sin->generate();
printf("Public Key:  %s\n", $public);
printf("Private Key: %s\n", $private);
printf("Sin Key:     %s\n\n", $sin);
$manager = new \Bitpay\KeyManager(new \Bitpay\Storage\EncryptedFilesystemStorage('fdgkjnfdERTPWIEFMVwe'));
$manager->persist($private);
$manager->persist($public);
$manager->persist($sin);

$bitpay = new \Bitpay\Bitpay(
    array(
        'bitpay' => array(
            'network'     => 'testnet', // testnet or livenet, default is livenet
            'public_key'  => '/tmp/public.key', //see tutorial/001.php and 002.php
            'private_key' => '/tmp/private.key',
            'key_storage' => 'Bitpay\Storage\EncryptedFilesystemStorage',
            'key_storage_password' => 'fdgkjnfdERTPWIEFMVwe'
        )
    )
);
/**
 * Create the client that will be used to send requests to BitPay's API
 */
$client = $bitpay->get('client');

// @var \Bitpay\KeyManager
$manager   = $bitpay->get('key_manager');
$publicKey = $manager->load($bitpay->getContainer()->getParameter('bitpay.public_key'));
$sin = new \Bitpay\SinKey();
$sin->setPublicKey($publicKey);
$sin->generate();

// @var \Bitpay\TokenInterface
$token = $client->createToken(
    array(
        'id'          => (string) $sin,
        'pairingCode' => 'fees',
        'label'       => 'y1FdbaA',
    )
);
</code>```

答:
I was faced this problem. Then I used properly this "https://github.com/bitpay/php-bitpay-client" library and follow the steps.

So first of all download latest bitpay library and configure properly as per document read me file.

You can integrate with tutorial from https://github.com/bitpay/php-bitpay-client/tree/master/examples/tutorial.

Body:
I am struggling with bitpay API.
So far i generated public,priate and sin keys.
I stored them and now i want to pair with special key from bitpay.com
Here is my error and below its my whole code.
Anyone can help ?

Public Key: 0309f03bc0d566c411aeb55b8be57b0485d28706ace9b1a198d053212bde06d718 Private Key: 77cec96ea11e3d35ec2817db6951167755095f8a45c508028ca22734fe7e9962 Sin Key: Tf2XSANqca54VHQG31RXjAY5EKdyaysHtct
Fatal error: Uncaught Bitpay\Client\ArgumentException: pairing code is not legal in /var/www/dev.simplemining.net/vendor/bitpay/php-client/src/Bitpay/Client/Client.php:494 Stack trace: #0 /var/www/dev.simplemining.net/controller/account.php(65): Bitpay\Client\Client->createToken(Array) #1 /var/www/dev.simplemining.net/index.php(20): require('/var/www/dev.si...') #2 {main} thrown in /var/www/dev.simplemining.net/vendor/bitpay/php-client/src/Bitpay/Client/Client.php on line 494

require __DIR__ . '/../vendor/autoload.php';
$private = new \Bitpay\PrivateKey('/tmp/private.key');
$public  = new \Bitpay\PublicKey('/tmp/public.key');
$sin     = new \Bitpay\SinKey('/tmp/sin.key');
// Generate Private Key values
$private->generate();
// Generate Public Key values
$public->setPrivateKey($private);
$public->generate();
// Generate Sin Key values
$sin->setPublicKey($public);
$sin->generate();
printf("Public Key:  %s\n", $public);
printf("Private Key: %s\n", $private);
printf("Sin Key:     %s\n\n", $sin);
$manager = new \Bitpay\KeyManager(new \Bitpay\Storage\EncryptedFilesystemStorage('fdgkjnfdERTPWIEFMVwe'));
$manager->persist($private);
$manager->persist($public);
$manager->persist($sin);

$bitpay = new \Bitpay\Bitpay(
    array(
        'bitpay' => array(
            'network'     => 'testnet', // testnet or livenet, default is livenet
            'public_key'  => '/tmp/public.key', //see tutorial/001.php and 002.php
            'private_key' => '/tmp/private.key',
            'key_storage' => 'Bitpay\Storage\EncryptedFilesystemStorage',
            'key_storage_password' => 'fdgkjnfdERTPWIEFMVwe'
        )
    )
);
/**
 * Create the client that will be used to send requests to BitPay's API
 */
$client = $bitpay->get('client');

// @var \Bitpay\KeyManager
$manager   = $bitpay->get('key_manager');
$publicKey = $manager->load($bitpay->getContainer()->getParameter('bitpay.public_key'));
$sin = new \Bitpay\SinKey();
$sin->setPublicKey($publicKey);
$sin->generate();

// @var \Bitpay\TokenInterface
$token = $client->createToken(
    array(
        'id'          => (string) $sin,
        'pairingCode' => 'fees',
        'label'       => 'y1FdbaA',
    )
);


问:
Can we call .net(2.0) dll from Delphi 5 application
Can we call a dll built in .Net2.0 from Delphi 5 windows application. If yes, how.</p>

答: Have a look at CrossTalk.</p>

Body: Have a look at CrossTalk.


问:
Connecting to cassandra running in Docker
I'm trying to run Cassandra in a docker container and connect to it from my Mac (the host) but I keep getting Connection refused errors.

The docker command:

```<code>=> docker run --rm --name cassandra -d cassandra:3.11 -p 9042:9042

=> docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                    NAMES
4ecc9dcd8647        cassandra:3.11      "/docker-entrypoin..."   33 minutes ago      Up 33 minutes       7000-7001/tcp, 7199/tcp, 9042/tcp, 9160/tcp   cassandra

=> cqlsh
Connection error: ('Unable to connect to any servers', {'127.0.0.1':
error(61, "Tried connecting to [('127.0.0.1', 9042)]. Last error:
Connection refused")})
</code>```

If I'm executing bash shell in the instance:

```<code>=> docker exec -it cassandra bash
</code>```

I can run the cqlsh and connect to cassandra locally.

What am I missing?

答:
Port is still not exposed outside
Try this

docker run -p 9042:9042 --rm --name cassandra -d cassandra:3.11

Do docker ps you should see something like this

0.0.0.0:9042->9042/tcp

For more info : https://docs.docker.com/engine/reference/commandline/run/

Body:
I'm trying to run Cassandra in a docker container and connect to it from my Mac (the host) but I keep getting Connection refused errors.

The docker command:

=> docker run --rm --name cassandra -d cassandra:3.11 -p 9042:9042

=> docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                    NAMES
4ecc9dcd8647        cassandra:3.11      "/docker-entrypoin..."   33 minutes ago      Up 33 minutes       7000-7001/tcp, 7199/tcp, 9042/tcp, 9160/tcp   cassandra

=> cqlsh
Connection error: ('Unable to connect to any servers', {'127.0.0.1':
error(61, "Tried connecting to [('127.0.0.1', 9042)]. Last error:
Connection refused")})

If I'm executing bash shell in the instance:

=> docker exec -it cassandra bash

I can run the cqlsh and connect to cassandra locally.

What am I missing?


问:
AVAssetReader and Audio Queue streaming problem
I have a problem with the AVAssetReader here to get samples from the iPod library and stream it via Audio Queue. I have not been able to find any such example so I try to implement my own but it seems that somehow the AssetReader is "screwed up" at the callback function of audio queue. Specifically it fails when it does the copyNextSampleBuffer ie it returns null when it is not finished yet. I have made sure the pointer exists and such so it will be great if anyone can help.

Below is the callback function code that I have used. This callback function 'works' when it is not called by the AudioQueue callback.

```<code>    static void HandleOutputBuffer (
        void                *playerStateH,
        AudioQueueRef       inAQ,
        AudioQueueBufferRef inBuffer
        ) {

 AQPlayerState *pplayerState = (AQPlayerState *) playerStateH;
 //if (pplayerState->mIsRunning == 0) return;

 UInt32 bytesToRead = pplayerState->bufferByteSize;
 [[NSNotificationCenter defaultCenter] postNotificationName:NOTIF_callsample object:nil];

 float * inData =(float *) inBuffer->mAudioData;
 int offsetSample = 0;
 //Loop until finish reading from the music data
 while (bytesToRead) {

  /*THIS IS THE PROBLEMATIC LINE*/
  CMSampleBufferRef sampBuffer = [pplayerState->assetWrapper getNextSampleBuffer]; //the assetreader getting nextsample with copyNextSampleBuffer

  if (sampBuffer == nil) {
   NSLog(@"No more data to read from");
 //  NSLog(@"aro status after null %d",[pplayerState->ar status]);
   AudioQueueStop (
       pplayerState->mQueue,
       false
       );
   pplayerState->mIsRunning = NO;

   return;
  }

  AudioBufferList  audioBufferList;
  CMBlockBufferRef blockBuffer;
  CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampBuffer, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &blockBuffer);
  AudioBuffer audioBuffer = audioBufferList.mBuffers[0];
  memcpy(inData + (2*offsetSample),audioBuffer.mData,audioBuffer.mDataByteSize);
  bytesToRead = bytesToRead - audioBuffer.mDataByteSize;
  offsetSample = offsetSample + audioBuffer.mDataByteSize/8;

 }
 inBuffer->mAudioDataByteSize = offsetSample*8;

 AudioQueueEnqueueBuffer (
        pplayerState->mQueue,
        inBuffer,
        0,
        0
        );

}
</code>```

答: Ok I have somehow solved this weird error... Apparently it is because of the audio session not properly set. Talk about lack of documentation on this one...</p>

Body:
I have a problem with the AVAssetReader here to get samples from the iPod library and stream it via Audio Queue. I have not been able to find any such example so I try to implement my own but it seems that somehow the AssetReader is "screwed up" at the callback function of audio queue. Specifically it fails when it does the copyNextSampleBuffer ie it returns null when it is not finished yet. I have made sure the pointer exists and such so it will be great if anyone can help.

Below is the callback function code that I have used. This callback function 'works' when it is not called by the AudioQueue callback.

    static void HandleOutputBuffer (
        void                *playerStateH,
        AudioQueueRef       inAQ,
        AudioQueueBufferRef inBuffer
        ) {

 AQPlayerState *pplayerState = (AQPlayerState *) playerStateH;
 //if (pplayerState->mIsRunning == 0) return;

 UInt32 bytesToRead = pplayerState->bufferByteSize;
 [[NSNotificationCenter defaultCenter] postNotificationName:NOTIF_callsample object:nil];

 float * inData =(float *) inBuffer->mAudioData;
 int offsetSample = 0;
 //Loop until finish reading from the music data
 while (bytesToRead) {

  /*THIS IS THE PROBLEMATIC LINE*/
  CMSampleBufferRef sampBuffer = [pplayerState->assetWrapper getNextSampleBuffer]; //the assetreader getting nextsample with copyNextSampleBuffer

  if (sampBuffer == nil) {
   NSLog(@"No more data to read from");
 //  NSLog(@"aro status after null %d",[pplayerState->ar status]);
   AudioQueueStop (
       pplayerState->mQueue,
       false
       );
   pplayerState->mIsRunning = NO;

   return;
  }

  AudioBufferList  audioBufferList;
  CMBlockBufferRef blockBuffer;
  CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampBuffer, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &blockBuffer);
  AudioBuffer audioBuffer = audioBufferList.mBuffers[0];
  memcpy(inData + (2*offsetSample),audioBuffer.mData,audioBuffer.mDataByteSize);
  bytesToRead = bytesToRead - audioBuffer.mDataByteSize;
  offsetSample = offsetSample + audioBuffer.mDataByteSize/8;

 }
 inBuffer->mAudioDataByteSize = offsetSample*8;

 AudioQueueEnqueueBuffer (
        pplayerState->mQueue,
        inBuffer,
        0,
        0
        );

}


问:
ModifyAsync Not Working
I'm attempting to edit an embedded message after it is posted. I was attempting to use this example from the documentation but it just does not work. https://discord.foxbot.me/docs/api/Discord.MessageProperties.html

```<code>var message = await ReplyAsync("abc");
await message.ModifyAsync(x =>
{
    x.Content = "";
    x.Embed = new EmbedBuilder()
        .WithColor(new Color(40, 40, 120))
        .WithAuthor(a => a.Name = "foxbot")
        .WithTitle("Embed!")
        .WithDescription("This is an embed.");
});
</code>```

Putting the code into one of my working commands will give a

cannot implicitly convert type Discord.EmbedBuilder to Discord.Optional<Discord.Embed>"

Really confused...

答:
You are missing a .Build() after WithDescription. Usually when using the builder pattern you usually need to build the desired type.

```<code>var message = await ReplyAsync("abc");
await message.ModifyAsync(x =>
{
    x.Content = "";
    x.Embed = new EmbedBuilder()
        .WithColor(new Color(40, 40, 120))
        .WithAuthor(a => a.Name = "foxbot")
        .WithTitle("Embed!")
        .WithDescription("This is an embed.")
        .Build(); //<-- The is what was omitted.
});
</code>```

Calling Build() would return a Embed which can then be implicitly converted to Optional<Embed>"

Title: ModifyAsync Not Working

Body:
I'm attempting to edit an embedded message after it is posted. I was attempting to use this example from the documentation but it just does not work. https://discord.foxbot.me/docs/api/Discord.MessageProperties.html

var message = await ReplyAsync("abc");
await message.ModifyAsync(x =>
{
    x.Content = "";
    x.Embed = new EmbedBuilder()
        .WithColor(new Color(40, 40, 120))
        .WithAuthor(a => a.Name = "foxbot")
        .WithTitle("Embed!")
        .WithDescription("This is an embed.");
});

Putting the code into one of my working commands will give a

cannot implicitly convert type Discord.EmbedBuilder to Discord.Optional<Discord.Embed>"

Really confused...

Body:
You are missing a .Build() after WithDescription. Usually when using the builder pattern you usually need to build the desired type.

var message = await ReplyAsync("abc");
await message.ModifyAsync(x =>
{
    x.Content = "";
    x.Embed = new EmbedBuilder()
        .WithColor(new Color(40, 40, 120))
        .WithAuthor(a => a.Name = "foxbot")
        .WithTitle("Embed!")
        .WithDescription("This is an embed.")
        .Build(); //<-- The is what was omitted.
});

Calling Build() would return a Embed which can then be implicitly converted to Optional<Embed>"


问:
VBA: How to change default selection on a Userform & restrict user from texting values under a dropdown column
I created a userform with a textbox and dropdown options,

Textbox  (User)

Dropdown (Place)

Dropdown (Language)

I am facing 2 issues here,

Issue 1. When I open the the userform the default selection will be under the 2nd option (Place). How I can get the default selection on the 1st option which is a Textbox (User). So that user can give there value and go down and select values from drop down.

Issue 2. User able to type values under the drop down option, how to prevent them from doing so.

```<code>Private Sub UserForm_Initialize()
    Dim cPlace As Range
    Dim cLanguage As Range
    Dim ws As Worksheet
    Set ws As Worksheets

    With Me.cboPlace
        .AddItem "Eng"
        .AddItem "Aus"
        .AddItem "USA"
    End With

    With Me.cboLanguage
        .AddItem "English"
        .AddItem "Spanish"
        .AddItem "French"
    End With
    Me.cboLanguage.Setfocus

End Sub
</code>```

答:
If I understand your requirements correctly then

the default cursor position on opening a form is the control whose TABINDEX property is the lowest (usually 1).

To prevent a user from entering free text into a combo or list box set the property MATCHREQUIRED to True

Body:
I created a userform with a textbox and dropdown options,

Textbox  (User)

Dropdown (Place)

Dropdown (Language)

I am facing 2 issues here,

Issue 1. When I open the the userform the default selection will be under the 2nd option (Place). How I can get the default selection on the 1st option which is a Textbox (User). So that user can give there value and go down and select values from drop down.

Issue 2. User able to type values under the drop down option, how to prevent them from doing so.

Private Sub UserForm_Initialize()
    Dim cPlace As Range
    Dim cLanguage As Range
    Dim ws As Worksheet
    Set ws As Worksheets

    With Me.cboPlace
        .AddItem "Eng"
        .AddItem "Aus"
        .AddItem "USA"
    End With

    With Me.cboLanguage
        .AddItem "English"
        .AddItem "Spanish"
        .AddItem "French"
    End With
    Me.cboLanguage.Setfocus

End Sub


问:
Div won't close
```<code><div style="margin: 8px auto;text-align: center; clear: both;">
<img src="https://storage.googleapis.com/support-kms-
prod/SNP_3094702_en_v0" style="max-width: 100%; />
</div>

^ // THIS IS THE DIV THAT WON'T CLOSE //
  // IT INSTEAD INCLUDES THE CONTENT BELOW //

<article class=">
<div class="category">
</div>
</code>```

Hello! I own a wordpress blog and I'm trying to implement ads between posts, but I've run into a weird problem. This div won't close, no matter how many
's I put after the img tag ends. It instead includes the whole rest of the page.

Is there something I am missing here?

答:
```<code><div style="margin: 8px auto;text-align: center; clear: both;" id="ads">
<span id="close" style="float:right;">×  </span>
<img src="https://storage.googleapis.com/support-kms-
prod/SNP_3094702_en_v0" style="max-width: 100%;">
</div>
<article class=">
<div class="category">
</div>
<script>
var close=document.GetElementById("close");
var ads=document.GetElementById("ads") ;
close.onclick = function() {
    ads.style.display = "none";
}
</script>
</code>```

by click the close button it  hides the ads
 .
i hope it will solve your problem.

Title: Div won't close

Body:
^ // THIS IS THE DIV THAT WON'T CLOSE //
  // IT INSTEAD INCLUDES THE CONTENT BELOW //

Hello! I own a wordpress blog and I'm trying to implement ads between posts, but I've run into a weird problem. This div won't close, no matter how many
's I put after the img tag ends. It instead includes the whole rest of the page.

Is there something I am missing here?

Body:
<div style="margin: 8px auto;text-align: center; clear: both;" id="ads">
<span id="close" style="float:right;">&times;  </span>
<img src="https://storage.googleapis.com/support-kms-
prod/SNP_3094702_en_v0" style="max-width: 100%;">
</div>
<article class=">
<div class="category">
</div>
<script>
var close=document.GetElementById("close");
var ads=document.GetElementById("ads") ;
close.onclick = function() {
    ads.style.display = "none";
}
</script>

by click the close button it  hides the ads <div> .
i hope it will solve your problem.


问:
When to use getContextClassLoader().getResourceAsStream in java?
I have a web application I came accross

```<code>InputStream iStream= Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.Properties");
</code>```

I am trying to understand what difference will it make if I write

```<code>Properties p = new Properties();
p.load(new BufferedReader(new FileReader("Test.properties")))
</code>```

Can any one let me know how these two approaches are different?

答:
If I understand you correctly then the difference is that the method getResourceAsStream() will look ok your classspath for the properties file.

The Filereader can  read a file from anywhere in your file system, as long as you have the right to the path obviously.

Edit: It will use the Thread’s own class loader however as long as you don’t share any resources among other threads you’ll be fine either way.

I personally like the getResourceAsStream method because it allows me to simply throw files into a folder in my maven project e.g. /src/main/resources and I can simply retrieve no matter how my application is going to be packaged.

Body:
I have a web application I came accross

InputStream iStream= Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.Properties");

I am trying to understand what difference will it make if I write

Properties p = new Properties();
p.load(new BufferedReader(new FileReader("Test.properties")))

Can any one let me know how these two approaches are different?


问:
Using Cloud Firestore with AppEngine Go Standard Environment returns rpc error when running on AppEngline
I'm trying to use Firestore in my AppEngine (standard environment) app written in Go. I've been following the "Getting Started with Cloud Firestore" guide and have been using the firestore package documentation to implement a simple example that works fine when running it on my local dev server.

However when I deploy the app and try the deployed version the call to DocumentRef.Set() fails with the error

rpc error: code = Unavailable desc = all SubConns are in TransientFailure
```

<p>This is my code that reproduces the issue:</p>

<pre class="lang-default prettyprint-override"><code>func init() {
    http.HandleFunc("/test", testHandler)
}

type testData struct {
    TestData string `firestore:"myKey,omitempty"`
}

func testHandler(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)

    var firestoreClient *firestore.Client
    var firebaseApp *firebase.App
    var err error

    conf := &firebase.Config{ProjectID: "my-project"}
    firebaseApp, err = firebase.NewApp(ctx, conf)

    if err != nil {
        fmt.Fprintf(w, "Failed to create a new firestore app: %v", err)
        return
    }

    firestoreClient, err = firebaseApp.Firestore(ctx)
    if err != nil {
        fmt.Fprintf(w, "Failed to create a new firestore client: %v", err)
        return
    }

    data := testData{"my value"}
    _, err = firestoreClient.Collection("testCollection").Doc("testDoc").Set(ctx, data)
    if err != nil {
        fmt.Fprintf(w, "Failed to create a firestore document: %v", err)
        return
    }
    firestoreClient.Close()
    fmt.Fprint(w, "Data stored in Firestore successfully")
}
</code>```

As mentioned before, on the dev server this works fine. So there the returned page contains the text Data stored in Firestore successfully.

When running the deployed code I get Failed to create a firestore document: rpc error: code = Unavailable desc = all SubConns are in TransientFailure instead. Why do I get this error and how can I avoid it?

答:
On AppEngine you need to create a client that uses Http client provided by urlfetch service.

The firestore.NewClient() function accepts ClientOptions parameters that you can create using WithHTTPCLient() function.

Here is an article on issuing HTTP requests from AppEngine Go.

That should help.

Body:
I'm trying to use Firestore in my AppEngine (standard environment) app written in Go. I've been following the "Getting Started with Cloud Firestore" guide and have been using the firestore package documentation to implement a simple example that works fine when running it on my local dev server.

However when I deploy the app and try the deployed version the call to DocumentRef.Set() fails with the error

rpc error: code = Unavailable desc = all SubConns are in TransientFailure

This is my code that reproduces the issue:

func init() {
    http.HandleFunc("/test", testHandler)
}

type testData struct {
    TestData string `firestore:"myKey,omitempty"`
}

func testHandler(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)

    var firestoreClient *firestore.Client
    var firebaseApp *firebase.App
    var err error

    conf := &firebase.Config{ProjectID: "my-project"}
    firebaseApp, err = firebase.NewApp(ctx, conf)

    if err != nil {
        fmt.Fprintf(w, "Failed to create a new firestore app: %v", err)
        return
    }

    firestoreClient, err = firebaseApp.Firestore(ctx)
    if err != nil {
        fmt.Fprintf(w, "Failed to create a new firestore client: %v", err)
        return
    }

    data := testData{"my value"}
    _, err = firestoreClient.Collection("testCollection").Doc("testDoc").Set(ctx, data)
    if err != nil {
        fmt.Fprintf(w, "Failed to create a firestore document: %v", err)
        return
    }
    firestoreClient.Close()
    fmt.Fprint(w, "Data stored in Firestore successfully")
}

As mentioned before, on the dev server this works fine. So there the returned page contains the text Data stored in Firestore successfully.

When running the deployed code I get Failed to create a firestore document: rpc error: code = Unavailable desc = all SubConns are in TransientFailure instead. Why do I get this error and how can I avoid it?


问:
How to Implement Search with Pagination using Ajax codigniter
Controller

```<code> function view_product()
    {
        $config = [
            'base_url'          =>  base_url('admin/view_product'),
            'per_page'          =>  10,
            'total_rows'        =>  $this->AdminModel->num_rows(NULL),
            'full_tag_open'     =>  "<ul class='pagination'>",
            'full_tag_close'    =>  "</ul>",
            'first_tag_open'    =>  '<li>',
            'first_tag_close'   =>  '</li>',
            'last_tag_open'     =>  '<li>',
            'last_tag_close'    =>  '</li>',
            'next_tag_open'     =>  '<li>',
            'next_tag_close'    =>  '</li>',
            'prev_tag_open'     =>  '<li>',
            'prev_tag_close'    =>  '</li>',
            'num_tag_open'      =>  '<li>',
            'num_tag_close'     =>  '</li>',
            'cur_tag_open'      =>  "<li class='active'><a>",
            'cur_tag_close'     =>  '</a></li>',
        ];

        $this->pagination->initialize($config);
        $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['product'] =$this->AdminModel->view_product(NULL,$config['per_page'],$data['page']);
        $data['pagination'] = $this->pagination->create_links();
        $this->load->view('admin/view_product',$data);

    }

 public function ajaxsearch()
     {
          $query = $this->input->post('query');
          print_r($this->AdminModel->num_rows($query));

          $config = [
            'base_url'          =>  base_url('admin/ajaxsearch'),
            'per_page'          =>  10,
            'total_rows'        =>  $this->AdminModel->num_rows($query),
            'full_tag_open'     =>  "<ul class='pagination'>",
            'full_tag_close'    =>  "</ul>",
            'first_tag_open'    =>  '<li>',
            'first_tag_close'   =>  '</li>',
            'last_tag_open'     =>  '<li>',
            'last_tag_close'    =>  '</li>',
            'next_tag_open'     =>  '<li>',
            'next_tag_close'    =>  '</li>',
            'prev_tag_open'     =>  '<li>',
            'prev_tag_close'    =>  '</li>',
            'num_tag_open'      =>  '<li>',
            'num_tag_close'     =>  '</li>',
            'cur_tag_open'      =>  "<li class='active'><a>",
            'cur_tag_close'     =>  '</a></li>',

        ];

        $this->pagination->initialize($config);
        $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['product'] =$this->AdminModel->view_product($query,$config['per_page'],$data['page']);
        $data['pagination'] = $this->pagination->create_links();
        $this->load->view('admin/product_search_result',$data,false);

     }
</code>```

Model

```<code>public function num_rows($searchKeyword=NULL)
    {
        if ($searchKeyword == "NULL") $searchKeyword = "";

        $query = $this->db
                      ->select('*')
                      ->from('product')
                      ->like('p_name',$searchKeyword)
                      ->get();

        return $query->num_rows();

    }

 function view_product($searchKeyword=NULL,$limit,$offset)
    {
            if ($searchKeyword == "NULL") $searchKeyword = "";

            $query = $this->db->select("*")
                              ->from('product')
                              ->limit($limit, $offset )
                              ->join('product_category', 'product.p_cid = product_category.p_cid')
                              ->join('company','product.c_id = company.c_id')
                              ->order_by('p_id')
                              ->like('p_name',$searchKeyword)
                              ->get();
            return $query->result();
    }
</code>```

View

```<code>function load_data(query)
      {
            $.ajax({
                      url:"<?php echo base_url();?>admin/view_product",
                      method:"POST",
                      data:{query:query},
                      success:function(data)
                      {
                          $('#showData').html(data);
                          $('#product_list').html(data);
                      }
                    });
      }

  $('#product_name').keyup(function()
      {
          var search = $(this).val();
          if(search != '')
          {
             load_data(search);
          }
        /*  else
          {
             load_data();
          }*/
      });
</code>```

I am new to C.I, I am creating a Search Filter, The filter is working properly until i moved to the next Pagination link. When i am on First link the data is showing according to the filter/search keyword, but as i move to the next link everything goes off (All the data shows on page) how to solve this problem ?

答:
I will suggest you to have one function for both searching & pagination in CONTROLLER and have two separate function in MODEL

```<code>function view_product()
{
    $config = [
        'base_url'          =>  base_url('admin/view_product'),
        'per_page'          =>  10,
        'total_rows'        =>  $this->AdminModel->num_rows(NULL),
        'full_tag_open'     =>  "<ul class='pagination'>",
        'full_tag_close'    =>  "</ul>",
        'first_tag_open'    =>  '<li>',
        'first_tag_close'   =>  '</li>',
        'last_tag_open'     =>  '<li>',
        'last_tag_close'    =>  '</li>',
        'next_tag_open'     =>  '<li>',
        'next_tag_close'    =>  '</li>',
        'prev_tag_open'     =>  '<li>',
        'prev_tag_close'    =>  '</li>',
        'num_tag_open'      =>  '<li>',
        'num_tag_close'     =>  '</li>',
        'cur_tag_open'      =>  "<li class='active'><a>",
        'cur_tag_close'     =>  '</a></li>',
    ];

    $this->pagination->initialize($config);
    $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
    if(@$this->input->post('searchKeyword')==null)
    {
    $results=$this->AdminModel->view_product($config["per_page"],$page);
    }
    else
    {
    $searchKeyword=$this->input->post('searchKeyword');
    $results=$this->AdminModel->view_product_withKey($config["per_page"],$page,$searchKeyword);
    }
    $data['product']=$results;
    $data['pagination'] = $this->pagination->create_links();
    $this->load->view('admin/view_product',$data);

}
</code>```

MODEL

```<code>public function view_product($limit,$start)
{
    $this->db->from($this->table);
    $this->db->where('status',TRUE);
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    return $query->result();
}

public function view_product_withKey($limit,$start,$searchKeyword)
{
    $this->db->from($this->table);
    $this->db->like('field1', $searchKeyword);
    $this->db->or_like('fiel2', $searchKeyword);
    $this->db->or_like('field3', $searchKeyword);
    $this->db->or_like('field4', $searchKeyword);
    $this->db->where('status',TRUE);
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    return $query->result();
}
</code>```

Please test the code . AND do considered the variable name . please use your variable respectively.

Body:
Controller

 function view_product()
    {
        $config = [
            'base_url'          =>  base_url('admin/view_product'),
            'per_page'          =>  10,
            'total_rows'        =>  $this->AdminModel->num_rows(NULL),
            'full_tag_open'     =>  "
",
            'full_tag_close'    =>  "
",
            'first_tag_open'    =>  '
',
            'first_tag_close'   =>  '
',
            'last_tag_open'     =>  '
',
            'last_tag_close'    =>  '
',
            'next_tag_open'     =>  '
',
            'next_tag_close'    =>  '
',
            'prev_tag_open'     =>  '
',
            'prev_tag_close'    =>  '
',
            'num_tag_open'      =>  '
',
            'num_tag_close'     =>  '
',
            'cur_tag_open'      =>  "
",
            'cur_tag_close'     =>  '
',
        ];

        $this->pagination->initialize($config);
        $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['product'] =$this->AdminModel->view_product(NULL,$config['per_page'],$data['page']);
        $data['pagination'] = $this->pagination->create_links();
        $this->load->view('admin/view_product',$data);

    }

 public function ajaxsearch()
     {
          $query = $this->input->post('query');
          print_r($this->AdminModel->num_rows($query));

          $config = [
            'base_url'          =>  base_url('admin/ajaxsearch'),
            'per_page'          =>  10,
            'total_rows'        =>  $this->AdminModel->num_rows($query),
            'full_tag_open'     =>  "
",
            'full_tag_close'    =>  "
",
            'first_tag_open'    =>  '
',
            'first_tag_close'   =>  '
',
            'last_tag_open'     =>  '
',
            'last_tag_close'    =>  '
',
            'next_tag_open'     =>  '
',
            'next_tag_close'    =>  '
',
            'prev_tag_open'     =>  '
',
            'prev_tag_close'    =>  '
',
            'num_tag_open'      =>  '
',
            'num_tag_close'     =>  '
',
            'cur_tag_open'      =>  "
",
            'cur_tag_close'     =>  '
',

        ];

        $this->pagination->initialize($config);
        $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['product'] =$this->AdminModel->view_product($query,$config['per_page'],$data['page']);
        $data['pagination'] = $this->pagination->create_links();
        $this->load->view('admin/product_search_result',$data,false);

     }

Model

public function num_rows($searchKeyword=NULL)
    {
        if ($searchKeyword == "NULL") $searchKeyword = "";

        $query = $this->db
                      ->select('*')
                      ->from('product')
                      ->like('p_name',$searchKeyword)
                      ->get();

        return $query->num_rows();

    }

 function view_product($searchKeyword=NULL,$limit,$offset)
    {
            if ($searchKeyword == "NULL") $searchKeyword = "";

            $query = $this->db->select("*")
                              ->from('product')
                              ->limit($limit, $offset )
                              ->join('product_category', 'product.p_cid = product_category.p_cid')
                              ->join('company','product.c_id = company.c_id')
                              ->order_by('p_id')
                              ->like('p_name',$searchKeyword)
                              ->get();
            return $query->result();
    }

View

function load_data(query)
      {
            $.ajax({
                      url:"<?php echo base_url();?>admin/view_product",
                      method:"POST",
                      data:{query:query},
                      success:function(data)
                      {
                          $('#showData').html(data);
                          $('#product_list').html(data);
                      }
                    });
      }

  $('#product_name').keyup(function()
      {
          var search = $(this).val();
          if(search != '')
          {
             load_data(search);
          }
        /*  else
          {
             load_data();
          }*/
      });

I am new to C.I, I am creating a Search Filter, The filter is working properly until i moved to the next Pagination link. When i am on First link the data is showing according to the filter/search keyword, but as i move to the next link everything goes off (All the data shows on page) how to solve this problem ?

Body:
I will suggest you to have one function for both searching & pagination in CONTROLLER and have two separate function in MODEL

function view_product()
{
    $config = [
        'base_url'          =>  base_url('admin/view_product'),
        'per_page'          =>  10,
        'total_rows'        =>  $this->AdminModel->num_rows(NULL),
        'full_tag_open'     =>  "<ul class='pagination'>",
        'full_tag_close'    =>  "</ul>",
        'first_tag_open'    =>  '<li>',
        'first_tag_close'   =>  '</li>',
        'last_tag_open'     =>  '<li>',
        'last_tag_close'    =>  '</li>',
        'next_tag_open'     =>  '<li>',
        'next_tag_close'    =>  '</li>',
        'prev_tag_open'     =>  '<li>',
        'prev_tag_close'    =>  '</li>',
        'num_tag_open'      =>  '<li>',
        'num_tag_close'     =>  '</li>',
        'cur_tag_open'      =>  "<li class='active'><a>",
        'cur_tag_close'     =>  '</a></li>',
    ];

    $this->pagination->initialize($config);
    $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
    if(@$this->input->post('searchKeyword')==null)
    {
    $results=$this->AdminModel->view_product($config["per_page"],$page);
    }
    else
    {
    $searchKeyword=$this->input->post('searchKeyword');
    $results=$this->AdminModel->view_product_withKey($config["per_page"],$page,$searchKeyword);
    }
    $data['product']=$results;
    $data['pagination'] = $this->pagination->create_links();
    $this->load->view('admin/view_product',$data);

}

MODEL

public function view_product($limit,$start)
{
    $this->db->from($this->table);
    $this->db->where('status',TRUE);
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    return $query->result();
}

public function view_product_withKey($limit,$start,$searchKeyword)
{
    $this->db->from($this->table);
    $this->db->like('field1', $searchKeyword);
    $this->db->or_like('fiel2', $searchKeyword);
    $this->db->or_like('field3', $searchKeyword);
    $this->db->or_like('field4', $searchKeyword);
    $this->db->where('status',TRUE);
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    return $query->result();
}

Please test the code . AND do considered the variable name . please use your variable respectively.


问:
SSL key exchange encryption techniques
what are the differences between the three key exchange algortihms namely Anonymous DH, Ephermal DH and fixed DH?</p>

答:
From Cisco's docs:

Fixed Diffie-Hellman:
  This a Diffie-Hellman key exchange in which
  the server's certificate contains the
  Diffie-Hellman public parameters
  signed by the certificate authority
  (CA). That is, the public-key
  certificate contains the
  Diffie-Hellman public-key parameters.
  The client provides its Diffie-Hellman
  public key parameters either in a
  certificate, if client authentication
  is required, or in a key exchange
  message. This method results in a
  fixed secret key between two peers,
  based on the Diffie-Hellman
  calculation using the fixed public
  keys.

Ephemeral Diffie-Hellman:
  This technique is used to create ephemeral
  (temporary, one-time) secret keys. In
  this case, the Diffie-Hellman public
  keys are exchanged, and signed using
  the sender's private RSA or DSS key.
  The receiver can use the corresponding
  public key to verify the signature.
  Certificates are used to authenticate
  the public keys. This option appears
  to be the most secure of the three
  Diffie-Hellman options because it
  results in a temporary, authenticated
  key.

Anonymous Diffie-Hellman:
  The base Diffie-Hellman algorithm is used, with
  no authentication. That is, each side
  sends its public Diffie-Hellman
  parameters to the other, with no
  authentication. This approach is
  vulnerable to man-in-the-middle
  attacks, in which the attacker
  conducts anonymous Diffie-Hellman
  exchanges with both parties.

Title: SSL key exchange encryption techniques


问:
IN Linux Distinct SQL is not working with UNNEST
When i run this query in window system behave correctly UNNSET
but when i run this query Linux behave different.unnset duplicate record list on different row</p>

```<code>SELECT DISTINCT
         "billing_billmanagement"."creation_date",
         "billing_billmanagement"."bill_number",
         unnest(array_agg(DISTINCT "inventory_product"."product_name")) AS "product",
         unnest(array_agg(DISTINCT "services_service"."name")) AS "service"
FROM "billing_billmanagement"
  INNER JOIN "users_staffuser" ON ("billing_billmanagement"."staff_id" = "users_staffuser"."id")
  INNER JOIN "auth_user" ON ("users_staffuser"."user_id" = "auth_user"."id")
  LEFT OUTER JOIN "billing_customerproductbill" ON ("billing_billmanagement"."id" = "billing_customerproductbill"."bill_id")
  LEFT OUTER JOIN "inventory_product" ON ("billing_customerproductbill"."product_id" = "inventory_product"."id")
  LEFT OUTER JOIN "billing_customerservicebill" ON ("billing_billmanagement"."id" = "billing_customerservicebill"."bill_id")
  LEFT OUTER JOIN "services_service" ON ("billing_customerservicebill"."service_id" = "services_service"."id")

WHERE "billing_billmanagement"."creation_date" BETWEEN '2017-12-04' AND '2017-12-06'
GROUP BY billing_billmanagement.creation_date,
         billing_billmanagement.bill_number
ORDER BY "billing_billmanagement"."creation_date" ASC
</code>```

答:
If getting duplicate rows is the problem, try this </p>

```<code> SELECT billing_billmanagement.creation_date,
           billing_billmanagement.bill_number,
           inventory_product.product_name AS product,
           services_service.name AS service
    FROM billing_billmanagement
      INNER JOIN users_staffuser ON (billing_billmanagement.staff_id = users_staffuser.id)
      INNER JOIN auth_user ON (users_staffuser.user_id = auth_user.id)
      LEFT OUTER JOIN billing_customerproductbill ON (billing_billmanagement.id = billing_customerproductbill.bill_id)
      LEFT OUTER JOIN inventory_product ON (billing_customerproductbill.product_id = inventory_product.id)
      LEFT OUTER JOIN billing_customerservicebill ON (billing_billmanagement.id = billing_customerservicebill.bill_id)
      LEFT OUTER JOIN services_service ON (billing_customerservicebill.service_id = services_service.id)
    WHERE billing_billmanagement.creation_date BETWEEN '2017-12-04' AND '2017-12-06'
    GROUP BY 1,
             2,
             3,
             4
    ORDER BY 1 ASC;
</code>```

Body:
When i run this query in window system behave correctly UNNSET
but when i run this query Linux behave different.unnset duplicate record list on different row

SELECT DISTINCT
         "billing_billmanagement"."creation_date",
         "billing_billmanagement"."bill_number",
         unnest(array_agg(DISTINCT "inventory_product"."product_name")) AS "product",
         unnest(array_agg(DISTINCT "services_service"."name")) AS "service"
FROM "billing_billmanagement"
  INNER JOIN "users_staffuser" ON ("billing_billmanagement"."staff_id" = "users_staffuser"."id")
  INNER JOIN "auth_user" ON ("users_staffuser"."user_id" = "auth_user"."id")
  LEFT OUTER JOIN "billing_customerproductbill" ON ("billing_billmanagement"."id" = "billing_customerproductbill"."bill_id")
  LEFT OUTER JOIN "inventory_product" ON ("billing_customerproductbill"."product_id" = "inventory_product"."id")
  LEFT OUTER JOIN "billing_customerservicebill" ON ("billing_billmanagement"."id" = "billing_customerservicebill"."bill_id")
  LEFT OUTER JOIN "services_service" ON ("billing_customerservicebill"."service_id" = "services_service"."id")

WHERE "billing_billmanagement"."creation_date" BETWEEN '2017-12-04' AND '2017-12-06'
GROUP BY billing_billmanagement.creation_date,
         billing_billmanagement.bill_number
ORDER BY "billing_billmanagement"."creation_date" ASC

Body:
If getting duplicate rows is the problem, try this

 SELECT billing_billmanagement.creation_date,
           billing_billmanagement.bill_number,
           inventory_product.product_name AS product,
           services_service.name AS service
    FROM billing_billmanagement
      INNER JOIN users_staffuser ON (billing_billmanagement.staff_id = users_staffuser.id)
      INNER JOIN auth_user ON (users_staffuser.user_id = auth_user.id)
      LEFT OUTER JOIN billing_customerproductbill ON (billing_billmanagement.id = billing_customerproductbill.bill_id)
      LEFT OUTER JOIN inventory_product ON (billing_customerproductbill.product_id = inventory_product.id)
      LEFT OUTER JOIN billing_customerservicebill ON (billing_billmanagement.id = billing_customerservicebill.bill_id)
      LEFT OUTER JOIN services_service ON (billing_customerservicebill.service_id = services_service.id)
    WHERE billing_billmanagement.creation_date BETWEEN '2017-12-04' AND '2017-12-06'
    GROUP BY 1,
             2,
             3,
             4
    ORDER BY 1 ASC;


问:
Data Transfer From Controller To Html in angularjs 1
I am new to angularjs. I am working on a project in which I have three html files index.html for ng-view, home.html for displaying various products, these products are coming from the database. I am able to get products from the database and able to display these products on home.html. Each product in home.html will be a link for the product.html page.  Product.html page is for displaying details of a single product.

My problem is when I click first time on the product in home.html, product.html page is displaying blank. In next click on any product in home.html, product.html page showing previous click data. This pattern is happening on every click, showing just previous click data.

home.html is -

```<code><div ng-controller="productController" class="homeMainDiv">

    <!-- Product DIV Start -->
    <div data-ng-init="onloadFun()">
        <div>
        <!--
        <div id="product" ng-repeat="product in products">

            <table>
                <tr>
                    <td>
                        <a target="_blank" href={{product.product_Url}}>
                            <img src="{{product.product_Url}}" style="width:150px">
                        </a>
                    </td>
                </tr>
            </table>
            -->
            <table style="width:100%">
                <tr ng-repeat="product in products" ng-switch on="$index % 3">
                  <td ng-switch-when="0">

                    <a target="_blank" href={{products[$index].product_Url}}>
                            <img src="{{products[$index].product_Url}}" style="width:150px">
                    </a>
                    <a href="#product" style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index].product_Url)">View Product Details and Buy Options</a>
                  </td>
                  <td ng-switch-when="0">
                    <span ng-show="products[$index+1]">

                      <a target="_blank" href={{products[$index+1].product_Url}}>
                            <img src="{{products[$index+1].product_Url}}" style="width:150px">
                     </a>
                     <a href="#product" style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index+1].product_Url)">View Product Details and Buy Options</a>

                    </span>
                  </td>
                  <td ng-switch-when="0">
                    <span ng-show="products[$index+2]">
                      <a target="_blank" href={{products[$index+2].product_Url}}>
                            <img src="{{products[$index+2].product_Url}}" style="width:150px">
                      </a>
                      <a href="#product" style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index+2].product_Url)">View Product Details and Buy Options</a>

                    </span>
                  </td>
                </tr>
            </table>

        </div>
    </div>
</div>
</code>```

product.html is -

```<code><div ng-controller="productController">
    <div style="margin-top: 307px;">
        <h1>Hello Product</h1>
        <img src="{{productById.product_Url}}" style="width:150px">
        <br>
        <a href="#">View Product Details and Buy Options</a>
    </div>
    </div>
</code>```

script.js is -

```<code>var gelovenIndia = angular.module('apparel', ['ngRoute']);

    gelovenIndia.config(function ($routeProvider,$locationProvider) {
        console.log("In config");
        $locationProvider.hashPrefix('');
        $routeProvider

     // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'productController'
        })

        // route for the your story page
        .when('/product', {
            templateUrl : 'pages/product.html',
            controller  : 'productController'
        });

    });

    gelovenIndia.controller('productController', function($scope, $http, $location, productService) {
         console.log("In productController");
         $scope.product = {};

         //console.log("$scope.products", $scope.products);

          $scope.productById = productService.getProduct();
          console.log('Product in productController', $scope.productById);

          $scope.onloadFun = function() {
                alert(1);
                console.log("In Onload Function");
                $http({
                    method : 'GET',
                    url : 'productData',
                    data : angular.toJson($scope.userform),
                    headers : {
                        'Content-Type' : 'application/json'
                    }
                }).then(function(response) {
                    alert("Got response for Product Data");
                    console.log("Got response for Product Data:", response.data);
                    $scope.products = response.data;
                    console.log("onloadFun - $scope.products", $scope.products);
                });
            };

            $scope.getProductById = function(URL) {
                alert("Product URL is :"+URL);
                //$scope.productById = productService.getProduct();
                console.log('In getProductById');
                $scope.product.product_Url = URL;
                console.log($scope.product);
                $http({
                    method : 'POST',
                    url : 'productData',
                    data : angular.toJson($scope.product),
                    headers : {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).then(function(response) {
                    alert("Got response for Product");
                    console.log("response in getProductById", response.data);
                    $scope.productById = response.data;
                    productService.addProduct(response.data);
                    $location.path('/product');
                    //$window.location.href = '/product';
                    console.log("10");

                });
            };

        });

    gelovenIndia.service('productService', function() {
        console.log("2");
          var product;

          var addProduct = function(newObj) {
              console.log("3");
              console.log("adding product to service", newObj);
              product = newObj;
          };

          var getProduct = function(){
              console.log("4");
              console.log("getting product from service", product);
              return product;
          };

          return {
              addProduct: addProduct,
              getProduct: getProduct
          };

        });
</code>```

Please let me know, What could be the solution.

答:
You don't have to use both ng-click and href for redirection to a new page. Stick to one. I will suggest you to remove the href and redirect via a function call and $location.

```<code><a style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index].product_Url)">View Product Details and Buy Options</a>
</code>```

Body:
I am new to angularjs. I am working on a project in which I have three html files index.html for ng-view, home.html for displaying various products, these products are coming from the database. I am able to get products from the database and able to display these products on home.html. Each product in home.html will be a link for the product.html page.  Product.html page is for displaying details of a single product.

My problem is when I click first time on the product in home.html, product.html page is displaying blank. In next click on any product in home.html, product.html page showing previous click data. This pattern is happening on every click, showing just previous click data.

home.html is -

                    View Product Details and Buy Options

                     View Product Details and Buy Options

                      View Product Details and Buy Options

product.html is -

Hello Product

        View Product Details and Buy Options

script.js is -

var gelovenIndia = angular.module('apparel', ['ngRoute']);

    gelovenIndia.config(function ($routeProvider,$locationProvider) {
        console.log("In config");
        $locationProvider.hashPrefix('');
        $routeProvider

     // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'productController'
        })

        // route for the your story page
        .when('/product', {
            templateUrl : 'pages/product.html',
            controller  : 'productController'
        });

    });

    gelovenIndia.controller('productController', function($scope, $http, $location, productService) {
         console.log("In productController");
         $scope.product = {};

         //console.log("$scope.products", $scope.products);

          $scope.productById = productService.getProduct();
          console.log('Product in productController', $scope.productById);

          $scope.onloadFun = function() {
                alert(1);
                console.log("In Onload Function");
                $http({
                    method : 'GET',
                    url : 'productData',
                    data : angular.toJson($scope.userform),
                    headers : {
                        'Content-Type' : 'application/json'
                    }
                }).then(function(response) {
                    alert("Got response for Product Data");
                    console.log("Got response for Product Data:", response.data);
                    $scope.products = response.data;
                    console.log("onloadFun - $scope.products", $scope.products);
                });
            };

            $scope.getProductById = function(URL) {
                alert("Product URL is :"+URL);
                //$scope.productById = productService.getProduct();
                console.log('In getProductById');
                $scope.product.product_Url = URL;
                console.log($scope.product);
                $http({
                    method : 'POST',
                    url : 'productData',
                    data : angular.toJson($scope.product),
                    headers : {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).then(function(response) {
                    alert("Got response for Product");
                    console.log("response in getProductById", response.data);
                    $scope.productById = response.data;
                    productService.addProduct(response.data);
                    $location.path('/product');
                    //$window.location.href = '/product';
                    console.log("10");

                });
            };

        });

    gelovenIndia.service('productService', function() {
        console.log("2");
          var product;

          var addProduct = function(newObj) {
              console.log("3");
              console.log("adding product to service", newObj);
              product = newObj;
          };

          var getProduct = function(){
              console.log("4");
              console.log("getting product from service", product);
              return product;
          };

          return {
              addProduct: addProduct,
              getProduct: getProduct
          };

        });

Please let me know, What could be the solution.

Body:
You don't have to use both ng-click and href for redirection to a new page. Stick to one. I will suggest you to remove the href and redirect via a function call and $location.

<a style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index].product_Url)">View Product Details and Buy Options</a>


问:
CSS - jpg image repeating
I am re-writing a website and i have inserted a background.
The background image is repeating.
I've tried various ways on setting the repeat = n without any luck.

Here is the current html section:

```<code><html xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Site down | Maintenance</title>
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
    <style type='text/css'>
        html,
        body {
            padding: 0;
            border: 0
        }

        .Header_image {
            padding- left: 20px
        }

        h1 {
            font-family: "verdana";
            padding: 0px;
            margin: 0px;
            font- size: 16pt;
            color: #D5261e
        }

        h3 {
            font-family: "verdana";
            padding: 0px;
            margin: 1px;
            font-size: 11pt;
        }

        p {
            font-family: "verdana";
            font-size: 13;
        }

        div.wide_rhn {
            padding-bottom: 17px
        }

        div.pg_three_col_border {
            BORDER-right: #e8e8e8 1px solid;
            BORDER-left: #e8e8e8 1px solid;
            background-color: #FFFFFF;
            PADDING-TOP: 11px;
            PADDING- LEFT: 17px;
            padding-bottom: 11px;
            font-family: arial;
            font-size: 75%;
            width: 763px;
            ^width: 782px
        }

        table.HP_table_header {
            position: relative;
            z-index: 200;
            padding- bottom: 10px;
            padding-top: 10px;
            *padding-bottom: 12px
        }

        td.HP_mainmenu {
            border: #878787 1px solid
        }

        table.HP_Image_table {
            MARGIN-LEFT: 124px;
            MARGIN-TOP: 1000px
        }
    </style>
</head>

<body background="man-with-no-shoes.jpg">

    <table class='HP_table_header' width='960' align='center' border='0' cellpadding='0' cellspacing='0'>
        <tbody>
            <tr>
                <td class='Header_image' width='189' align='left' height='74'>
                    <img src='images/test_logo.jpg' border='0' />
                </td>
            </tr>
        </tbody>
    </table>
    <table class='bg_body' width='1006' align='center' border='0' cellpadding='0' cellspacing='0' style='height: 500px;'>
        <tbody>
            <tr>
                <td valign='top'>
                    <table width='960' align='center' border='0' cellpadding='0' cellspacing='0'>
                        <tbody>
                            <tr>
                                <td valign='top' width='782' align='left'>
                                    <div id='WiderhPagetitlemain'>
</code>```

答:
```<code>.someCssSelector{
    background-repeat: no-repeat;
}
</code>```

Add your background using css.And then set attribute to no-repeat.

Title: CSS - jpg image repeating

Body:
I am re-writing a website and i have inserted a background.
The background image is repeating.
I've tried various ways on setting the repeat = n without any luck.

Here is the current html section:

    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Site down | Maintenance</title>
    <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">

Body:
.someCssSelector{
    background-repeat: no-repeat;
}

Add your background using css.And then set attribute to no-repeat.


问:
How we save image in gallery of emulator
How we put any image in gallery of emulator. I tried that one     in many ways , but i still failed to put a image in gallery of emulator. I am using       eclipse and ubuntu. When i goes in ~/.android/avd/ and tried to make dir of image      , but i really failed to do so.</p>

答: one of the easy way.Simply sync google photos and you will get image in emulator</p>


问:
Table of means and sds using dply
Is there a way to print out grouped means, and sds using dplyr in R(i.e. what one would observe in many randomised controlled trial reports where baseline demographics are reported for the placebo and drug arms). At the moment I have:

```<code>group_summary<- df %>%
  group_by(group) %>%
  summarise_at( vars(age, iq), c(mean, sd), na.rm=TRUE)

t(group_summary)
</code>```

which places the sds under the means:

```<code>                                [,1]       [,2]       [,3]
group                           "drug1"     "drug2"       "placebo"
age (x, ...) ...             "22.72436" "25.06164" "23.54394"
weight (x, ...) ...           "57.97143" NA         "64.66667"
age (x, na.rm = FALSE) ...   "3.793276" "3.930634" "4.623405"
weight (x, na.rm = FALSE) ... "16.03617" NA         "15.44099"
</code>```

when ideally what I would like is something more along the lines of:

```<code>                            [,1]       [,2]       [,3]
group                           "drug1"     "drug2"       "placebo"
age (x, ...) ...             "22.7(3.8)" "25.1(3.9)" "23.5(4.6)"
weight (x, ...) ...           "56.0(16.0)" NA         "64.7(15.4)"
</code>```

Grateful for any advice, although a tidyverse method would be ideal if possible

答:
I use this:</p>

```<code>df1 <- df %>%
    group_by(grouping.variable) %>%
    summarise(#x = variable, y = number of decimal places
    mean.sd.x = paste0(format(round(mean(x), y),
        nsmall = y),"(",format(round(sd(x), y), nsmall = y) ,")"))
</code>```

Title: Table of means and sds using dply

Body:
Is there a way to print out grouped means, and sds using dplyr in R(i.e. what one would observe in many randomised controlled trial reports where baseline demographics are reported for the placebo and drug arms). At the moment I have:

group_summary<- df %>%
  group_by(group) %>%
  summarise_at( vars(age, iq), c(mean, sd), na.rm=TRUE)

t(group_summary)

which places the sds under the means:

                                [,1]       [,2]       [,3]
group                           "drug1"     "drug2"       "placebo"
age (x, ...) ...             "22.72436" "25.06164" "23.54394"
weight (x, ...) ...           "57.97143" NA         "64.66667"
age (x, na.rm = FALSE) ...   "3.793276" "3.930634" "4.623405"
weight (x, na.rm = FALSE) ... "16.03617" NA         "15.44099"

when ideally what I would like is something more along the lines of:

                            [,1]       [,2]       [,3]
group                           "drug1"     "drug2"       "placebo"
age (x, ...) ...             "22.7(3.8)" "25.1(3.9)" "23.5(4.6)"
weight (x, ...) ...           "56.0(16.0)" NA         "64.7(15.4)"

Grateful for any advice, although a tidyverse method would be ideal if possible

Body:
I use this:

df1 <- df %>%
    group_by(grouping.variable) %>%
    summarise(#x = variable, y = number of decimal places
    mean.sd.x = paste0(format(round(mean(x), y),
        nsmall = y),"(",format(round(sd(x), y), nsmall = y) ,")"))