问:
Socket.io wont emit events
I started to learning socket.io.
I begin the tutorial with the socket.io website example
I installed all things correctly but I think socket cant emit the event in the index.html
any one can help

here is my code
index.js

```<code>    var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(Socket){
    Socket.on('chat message', function(msg){
    consloe.log('hi');
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});
</code>```

index.html

```<code><!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io();
    $('form').submit(function(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      console.log('sample');
      return false;
    });
    socket.on('chat message', function(msg){
        console.log('sample');
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>
  </body>
</html>
</code>```

答:
please check this as reference  ---
https://socket.io/docs/emit-cheatsheet/#

io.to(room).emit('msg'msg), or elase socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

Title: Socket.io wont emit events

Body:
I started to learning socket.io.
I begin the tutorial with the socket.io website example
I installed all things correctly but I think socket cant emit the event in the index.html
any one can help

here is my code
index.js

    var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(Socket){
    Socket.on('chat message', function(msg){
    consloe.log('hi');
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});

index.html

<!doctype html>

    <title>Socket.IO chat</title>

    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>


来源: stackexchange

问:
why do we even need VPTR?
And why don't we use the same method for non virtual functions?

I mean, why do we use virtual functions in that way? Can't we just use them as non-virtaul ones and override them?

And if this method is saving us time/space or what ever, why don't we use the same method for non-virtual functions? I mean it would make sense that there would be one table of functions for a specific class.

Anyway, thanks in advance, I am just a bit confused.

答: Using vptr allows method resolution based on object type rather than variable type. Not using vptr makes method calls faster. The C++ designers decided to allow the convenience of virtual functions but not require the performance penalty for other functions.</p>

ContentLicense: CC BY-SA 2.5

Title: why do we even need VPTR?


问:
Compile and build lp_solve from source code, ubuntu
I am using ubuntu machine and I've downloaded lp_solve source (lp_solve_5.5.2.5_source.tar.gz) and unpack it. Then I cd my command prompt into the path, lp_solve_5.5/lpsolve55.
Then I run command

```<code>./ccc
</code>```

Then I got this error and created empty bin folder.

```<code>In file included from ../lp_SOS.c:3:0:
../shared/commonlib.h:88:24: error: expected identifier or ‘(’ before numeric constant
   #define FALSE        0
                        ^
In file included from ../lp_utils.c:4:0:
../shared/commonlib.h:88:24: error: expected identifier or ‘(’ before numeric constant
   #define FALSE        0
                        ^
cc: error: lp_MDO.o: No such file or directory
cc: error: lp_crash.o: No such file or directory
cc: error: lp_wlp.o: No such file or directory
cc: error: lp_matrix.o: No such file or directory
cc: error: lp_mipbb.o: No such file or directory
cc: error: lp_MPS.o: No such file or directory
cc: error: lp_params.o: No such file or directory
cc: error: lp_presolve.o: No such file or directory
cc: error: lp_price.o: No such file or directory
cc: error: lp_pricePSE.o: No such file or directory
cc: error: lp_scale.o: No such file or directory
cc: error: lp_simplex.o: No such file or directory
cc: error: lp_SOS.o: No such file or directory
</code>```

I am not familiar with Ubuntu. I'll be grateful to you, If any one can help me to solve this problem. I want to use CFM-ID algorithm for my project. To use it I have to install lp_solve correctly. Thank you

答:
I had the same problem and this post helped me: https://groups.google.com/forum/#!topic/prismmodelchecker/gtVatHAir90

Download the patch https://groups.google.com/group/prismmodelchecker/attach/3586984674e863/fix-lpsolve-compilation.patch?part=0.1&authuser=0&view=1

Apply the patch with patch < yourpath/fix-lpsolve-compilation.patch inside the directory with the ccc file.

However this will not find the right files to patch, since the patch was intended for some PRISM version - you have to specify the corresponding file. For example

```<code>can't find file to patch at input line 57
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|Index: prism/ext/lpsolve55/src/lp_solve_5.5/lpsolve55/ccc
|===================================================================
|--- prism/ext/lpsolve55/src/lp_solve_5.5/lpsolve55/ccc (revision 11215)
|+++ prism/ext/lpsolve55/src/lp_solve_5.5/lpsolve55/ccc (revision 11216)
--------------------------
File to patch:
</code>```

There you enter ccc. You don't need to get all of them right (the ccc.osx etcetera), so you can just skip all except for the "right" ccc.

ContentLicense: CC BY-SA 3.0

Body:
I am using ubuntu machine and I've downloaded lp_solve source (lp_solve_5.5.2.5_source.tar.gz) and unpack it. Then I cd my command prompt into the path, lp_solve_5.5/lpsolve55.
Then I run command

./ccc

Then I got this error and created empty bin folder.

In file included from ../lp_SOS.c:3:0:
../shared/commonlib.h:88:24: error: expected identifier or ‘(’ before numeric constant
   #define FALSE        0
                        ^
In file included from ../lp_utils.c:4:0:
../shared/commonlib.h:88:24: error: expected identifier or ‘(’ before numeric constant
   #define FALSE        0
                        ^
cc: error: lp_MDO.o: No such file or directory
cc: error: lp_crash.o: No such file or directory
cc: error: lp_wlp.o: No such file or directory
cc: error: lp_matrix.o: No such file or directory
cc: error: lp_mipbb.o: No such file or directory
cc: error: lp_MPS.o: No such file or directory
cc: error: lp_params.o: No such file or directory
cc: error: lp_presolve.o: No such file or directory
cc: error: lp_price.o: No such file or directory
cc: error: lp_pricePSE.o: No such file or directory
cc: error: lp_scale.o: No such file or directory
cc: error: lp_simplex.o: No such file or directory
cc: error: lp_SOS.o: No such file or directory

I am not familiar with Ubuntu. I'll be grateful to you, If any one can help me to solve this problem. I want to use CFM-ID algorithm for my project. To use it I have to install lp_solve correctly. Thank you

Body:
I had the same problem and this post helped me: https://groups.google.com/forum/#!topic/prismmodelchecker/gtVatHAir90

Download the patch https://groups.google.com/group/prismmodelchecker/attach/3586984674e863/fix-lpsolve-compilation.patch?part=0.1&authuser=0&view=1

Apply the patch with patch < yourpath/fix-lpsolve-compilation.patch inside the directory with the ccc file.

However this will not find the right files to patch, since the patch was intended for some PRISM version - you have to specify the corresponding file. For example

can't find file to patch at input line 57
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|Index: prism/ext/lpsolve55/src/lp_solve_5.5/lpsolve55/ccc
|===================================================================
|--- prism/ext/lpsolve55/src/lp_solve_5.5/lpsolve55/ccc (revision 11215)
|+++ prism/ext/lpsolve55/src/lp_solve_5.5/lpsolve55/ccc (revision 11216)
--------------------------
File to patch:

There you enter ccc. You don't need to get all of them right (the ccc.osx etcetera), so you can just skip all except for the "right" ccc.


问:
Difference between /.../ and m/.../ in Perl
What is difference between /.../ and m/.../?

```<code>use strict;
use warnings;

my $str = "This is a testing for modifier";

if ($str =~ /This/i) { print "Modifier...\n";  }
if ($str =~ m/This/i) { print "W/O Modifier...\n";  }
</code>```

However, I checked with this site for Reference not clearly understand with the theory

答:
Perl has a number of quote-like operators where you can choose the delimiter to suit the data you're passing to the operator.

q(...) creates a single-quoted string

qq(...) creates a double-quoted string

qw(...) creates a list by splitting its arguments on white-space

qx(...) executes a command and returns the output

qr(...) compiles a regular expression

m(...) matches its argument as a regular expression

(There's also s(...)(...) but I've left that off the list as it has two arguments)

For some of these, you can omit the letter at the start of the operator if you choose the default delimiter.

You can omit q if you use single quote characters ('...').

You can omit qq if you use double quote characters ("...").

You can omit qx if you use backticks (`...`).

You can omit m if you use slashes (/.../).

So, to answer your original question, m/.../ and /.../ are the same, but because slashes are the default delimitor for the match operator, you can omit the m.

Body:
What is difference between /.../ and m/.../?

use strict;
use warnings;

my $str = "This is a testing for modifier";

if ($str =~ /This/i) { print "Modifier...\n";  }
if ($str =~ m/This/i) { print "W/O Modifier...\n";  }

However, I checked with this site for Reference not clearly understand with the theory


问:
How to transfer file to Android Device without drive letter using WPD
Excuse me for my bad english, please help me solve this problem. I able to retrieve file from Android Device using WPD but failed to transfer back to Android Device. I followed the tutorial in https://dzone.com/articles/windows-portable-devices-0 but that method only applies to devices with drive letter. Thank you.</p>

答: Sorry for the question, I already found a solution. The method used in the article is actually meant for PortableDeviceFolder.Id for its second parameter string parentObjectId, not a directory path in my Android Device.


问:
How to color table rows on the basis of column 'value' or 'text' in javascript?
I am having column name as 'Status'. If status is 'Pass' i need to show that row  in green color. If 'fail' then red. How to do it in javascript?

```<code>for (i=0; i < rows.length; i++) {
    var value = rows[i].getElementsByTagName("td")[0].firstChild.nodeValue;
    if (value == 'Pass') {
        rows[i].style.backgroundColor = "red";
    }
}
</code>```

I tried this but it is not supported by browser. Kindly help. Thanks.

答:
Styles can only be implemented on HTML elements e.g. text box, select, text etc. In your case you are trying to style a value of 'rows', which is not correct. You need to select the HTML element and then style it.

Something like this might help:

```<code>for (i=0; i < rows.length; i++) {
    var value = rows[i].getElementsByTagName("td")[0].firstChild.nodeValue;
    if (value == 'Pass') {
        rows[i].getElementsByTagName("td")[0].firstChild.style.backgroundColor = "red";
    }
}
</code>```

Body:
I am having column name as 'Status'. If status is 'Pass' i need to show that row  in green color. If 'fail' then red. How to do it in javascript?

for (i=0; i < rows.length; i++) {
    var value = rows[i].getElementsByTagName("td")[0].firstChild.nodeValue;
    if (value == 'Pass') {
        rows[i].style.backgroundColor = "red";
    }
}

I tried this but it is not supported by browser. Kindly help. Thanks.

Body:
Styles can only be implemented on HTML elements e.g. text box, select, text etc. In your case you are trying to style a value of 'rows', which is not correct. You need to select the HTML element and then style it.

Something like this might help:

for (i=0; i < rows.length; i++) {
    var value = rows[i].getElementsByTagName("td")[0].firstChild.nodeValue;
    if (value == 'Pass') {
        rows[i].getElementsByTagName("td")[0].firstChild.style.backgroundColor = "red";
    }
}


问:
regex pattern expressions
I have a expression for a field with the pattern as [0-9]* which takes a numeric value followed by a * ex. 0123*****. But I want to also include the pattern of *****0123 in the same expression. How can I do it in java. Right now it is as follows

```<code> String numericPattern = "[*0-9]";
</code>```

答:
I think this is what you want:

```<code>(\*+\d+)|(\d+\*+)
</code>```

Breaking it down:

```<code>(\*+\d+)
</code>```

A literal asterisk \* one or more times + followed by a digit \d one or more times +.

```<code>|
</code>```

or

```<code>(\d+\*+)
</code>```

A digit \d one or more times + followed by a literal asterisk \* one or more times +.

As ClasG said, you'll need to escape the slashes in Java, so your pattern would look like:

```<code>String numericPattern = "(\\*+\\d+)|(\\d+\\*+)";
</code>```

Title: regex pattern expressions

Body:
I have a expression for a field with the pattern as [0-9]* which takes a numeric value followed by a * ex. 0123*****. But I want to also include the pattern of *****0123 in the same expression. How can I do it in java. Right now it is as follows

 String numericPattern = "[*0-9]";

Body:
I think this is what you want:

(\*+\d+)|(\d+\*+)

Breaking it down:

(\*+\d+)

A literal asterisk \* one or more times + followed by a digit \d one or more times +.

|

or

(\d+\*+)

A digit \d one or more times + followed by a literal asterisk \* one or more times +.

As ClasG said, you'll need to escape the slashes in Java, so your pattern would look like:

String numericPattern = "(\\*+\\d+)|(\\d+\\*+)";


问:
UIView's are not positioning correctly
I have a nib with a 2 UIViews and 2 UILabels with IBOutlet's in my controller.

I am increasing and decreasing the height of these UIViews to look like a bar to indicate when something is 100% or less - like a bar chart almost.

I am using the following method for both bars (reuse) however the first UIView (bar) positions correctly but the second is too low down - the Y axis is wrong. However the height of both is correct.

Anyone have any ideas?  I have positioned them in interface builder already all I am actually doing in this method is changing the height (basically)

```<code>//Position the point, size and label of a rating bar
- (void)configureRatingBar:(UIView *)vRatingBar
            andRatingLabel:(UILabel *)lRatingLabel
               usingRating:(NSDecimalNumber *)rating
{
    //NSDecimalNumber *foodRating = [self calculateRating:self.currentHotel.foodAndBeverageRating];
    NSString *formattedRating = [self formatRating:rating];
    lRatingLabel.text = formattedRating;

    float newHeight = [rating floatValue]; //The height will be based on the rating 100 max
    CGRect currentFrame = vRatingBar.frame; //Current frame of the rating view

    //CGPoint currentPoint =
    //  [vRatingBar convertPoint:vRatingBar.frame.origin toView:vReviews];

    CGPoint currentPoint = vRatingBar.frame.origin; //Current point of the rating view
    float newYaxis = currentPoint.x + (100 - newHeight); //Y axis must move down with the decreasing rating from 0 (100 %) down

    [vRatingBar setFrame:CGRectMake(currentPoint.x, newYaxis, currentFrame.size.width, newHeight)];
    [lRatingLabel setFrame:CGRectMake(currentFrame.size.width / 34, newHeight - 20, 34, 21)];

}
</code>```

答:
I see you have this line:

```<code>float newYaxis = currentPoint.x + (100 - newHeight); //Y axis must move down with the decreasing rating from 0 (100 %) down
</code>```

Where you are using currentPoint.x for the calculation.  Should this be currentPoint.y?

Title: UIView's are not positioning correctly

Body:
I have a nib with a 2 UIViews and 2 UILabels with IBOutlet's in my controller.

I am increasing and decreasing the height of these UIViews to look like a bar to indicate when something is 100% or less - like a bar chart almost.

I am using the following method for both bars (reuse) however the first UIView (bar) positions correctly but the second is too low down - the Y axis is wrong. However the height of both is correct.

Anyone have any ideas?  I have positioned them in interface builder already all I am actually doing in this method is changing the height (basically)

//Position the point, size and label of a rating bar
- (void)configureRatingBar:(UIView *)vRatingBar
            andRatingLabel:(UILabel *)lRatingLabel
               usingRating:(NSDecimalNumber *)rating
{
    //NSDecimalNumber *foodRating = [self calculateRating:self.currentHotel.foodAndBeverageRating];
    NSString *formattedRating = [self formatRating:rating];
    lRatingLabel.text = formattedRating;

    float newHeight = [rating floatValue]; //The height will be based on the rating 100 max
    CGRect currentFrame = vRatingBar.frame; //Current frame of the rating view

    //CGPoint currentPoint =
    //  [vRatingBar convertPoint:vRatingBar.frame.origin toView:vReviews];

    CGPoint currentPoint = vRatingBar.frame.origin; //Current point of the rating view
    float newYaxis = currentPoint.x + (100 - newHeight); //Y axis must move down with the decreasing rating from 0 (100 %) down

    [vRatingBar setFrame:CGRectMake(currentPoint.x, newYaxis, currentFrame.size.width, newHeight)];
    [lRatingLabel setFrame:CGRectMake(currentFrame.size.width / 34, newHeight - 20, 34, 21)];

}

Body:
I see you have this line:

float newYaxis = currentPoint.x + (100 - newHeight); //Y axis must move down with the decreasing rating from 0 (100 %) down

Where you are using currentPoint.x for the calculation.  Should this be currentPoint.y?


问:
Opencart calculation when applying coupon value?
I am using opencart version 2.3.0.2 ..

where i m getting all values  except when i coupon value the tax values getting wrong and displaying values also getting wrong.

I want each product unit tax before applying coupon and
unit-discount after applying coupon value.

I have coded something below but not able to get correct values with unit discount..
by using below code  i m getting total discount amount , i want individual discount tax and discount amount when applying coupon value

```<code>$this->load->model('extension/total/coupon');

            $coupon_info = $this->model_extension_total_coupon->getCoupon($this->session->data['coupon']);
            if(isset($coupon_info) && !empty($coupon_info))
            {
            foreach($product as $taxpro) {

                if($coupon_info['type'] == 'F')
                        {
                            $discount = $coupon_info['discount'] * ($taxpro['total'] / $sub_total);
                        } else
                        if ($coupon_info['type'] == 'P')
                        {
                            $discount = $taxpro['total'] / 100 * $coupon_info['discount'];
                        }

            $tax_rates = $this->tax->getRates($taxpro['total'] - ($taxpro['total'] - $discount), $taxpro['tax_class_id']);
            foreach ($tax_rates as $tax_rate)
                            {
                                echo "```"; print_r($total_data['taxes'][$tax_rate['tax_rate_id']]);echo "```";
                                if ($tax_rate['type'] == 'P')
                                {

                                    $total_data['taxes'][$tax_rate['tax_rate_id']] -= $tax_rate['amount'];
                                }

                                 echo "```"; print_r($total_data['taxes'][$tax_rate['tax_rate_id']]);
                            }

             foreach($tax_rates as $tax_coupon)
             {
                 $protax = $tax_coupon['amount'];

                 $protax_unit = round($protax*$taxpro['quantity'],2);
                 $total_unit_tax += $protax_unit;

                 $coupon_tax += $tax_coupon['amount'];
             }
            }

           }
```

答:
You will need to save all products with taxes. I have omitted a lot of code to make it more clear on how to think

Example:

```<code><?php
$prepareDiscount = array();
foreach ($products as $product){
$prepareDiscount[$taxRateForProduct] = $productTotal;

}
</code>```

Then you will need to iterate over the prepareDiscounts array:

```<code>$total = $totalfromOrder;
$coupon_info = $this->model_extension_total_coupon->getCoupon($this->session->data['coupon']);

foreach($prepareDiscount as $taxRate => $value){
$discountPercentForRate = $value/$total;
$discountForRate = $discountPercentForRate * $coupon_info['discount'];
// Now you have the taxRate And the part of the discount which have that rate
}
</code>```

This is an example code. If you are interested in more in depth just check how payment gateways did it. The key to get all this working is just to prepare the discounts when iterating over the products.

Body:
I am using opencart version 2.3.0.2 ..

where i m getting all values  except when i coupon value the tax values getting wrong and displaying values also getting wrong.

I want each product unit tax before applying coupon and
unit-discount after applying coupon value.

I have coded something below but not able to get correct values with unit discount..
by using below code  i m getting total discount amount , i want individual discount tax and discount amount when applying coupon value

$this->load->model('extension/total/coupon');

            $coupon_info = $this->model_extension_total_coupon->getCoupon($this->session->data['coupon']);
            if(isset($coupon_info) && !empty($coupon_info))
            {
            foreach($product as $taxpro) {

                if($coupon_info['type'] == 'F')
                        {
                            $discount = $coupon_info['discount'] * ($taxpro['total'] / $sub_total);
                        } else
                        if ($coupon_info['type'] == 'P')
                        {
                            $discount = $taxpro['total'] / 100 * $coupon_info['discount'];
                        }

            $tax_rates = $this->tax->getRates($taxpro['total'] - ($taxpro['total'] - $discount), $taxpro['tax_class_id']);
            foreach ($tax_rates as $tax_rate)
                            {
                                echo "
"; print_r($total_data['taxes'][$tax_rate['tax_rate_id']]);echo "
";
                                if ($tax_rate['type'] == 'P')
                                {

                                    $total_data['taxes'][$tax_rate['tax_rate_id']] -= $tax_rate['amount'];
                                }

                                 echo "
"; print_r($total_data['taxes'][$tax_rate['tax_rate_id']]);
                            }

             foreach($tax_rates as $tax_coupon)
             {
                 $protax = $tax_coupon['amount'];

                 $protax_unit = round($protax*$taxpro['quantity'],2);
                 $total_unit_tax += $protax_unit;

                 $coupon_tax += $tax_coupon['amount'];
             }
            }

           }

Body:
You will need to save all products with taxes. I have omitted a lot of code to make it more clear on how to think

Example:

<?php
$prepareDiscount = array();
foreach ($products as $product){
$prepareDiscount[$taxRateForProduct] = $productTotal;

}

Then you will need to iterate over the prepareDiscounts array:

$total = $totalfromOrder;
$coupon_info = $this->model_extension_total_coupon->getCoupon($this->session->data['coupon']);

foreach($prepareDiscount as $taxRate => $value){
$discountPercentForRate = $value/$total;
$discountForRate = $discountPercentForRate * $coupon_info['discount'];
// Now you have the taxRate And the part of the discount which have that rate
}

This is an example code. If you are interested in more in depth just check how payment gateways did it. The key to get all this working is just to prepare the discounts when iterating over the products.


问:
Twilio send sms from python errors
I am trying to follow the tutorial in Twilio to send an SMS message from Python.  I have followed their code, but am getting this error:

```<code>[root@helios03 ~]# python sms.py
Traceback (most recent call last):
  File "sms.py", line 10, in <module>
    message = client.api.account.messages.create(to="+12316851234",
  File "/usr/lib/python2.6/site-packages/twilio/rest/__init__.py", line 138, in api
    from twilio.rest.api import Api
  File "/usr/lib/python2.6/site-packages/twilio/rest/api/__init__.py", line 10, in <module>
    from twilio.rest.api.v2010 import V2010
  File "/usr/lib/python2.6/site-packages/twilio/rest/api/v2010/__init__.py", line 9, in <module>
    from twilio.base.version import Version
  File "/usr/lib/python2.6/site-packages/twilio/base/version.py", line 4, in <module>
    from twilio.base import values
  File "/usr/lib/python2.6/site-packages/twilio/base/values.py", line 12
    return {k: v for k, v in iteritems(d) if v != unset}
                   ^
SyntaxError: invalid syntax
</code>```

Thoughts?  I did a "pip install twilio" to install the helper..

Their example code is:

```<code># /usr/bin/env python
# Download the twilio-python library from http://twilio.com/docs/libraries
from twilio.rest import Client

# Find these values at https://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXX"
auth_token = "YYYYYYYYYYYYYYYYYY"
client = Client(account_sid, auth_token)

message = client.api.account.messages.create(to="+12316851234",
                                             from_="+15555555555",
                                             body="Hello there!")
</code>```

I have replaced the to/from numbers and account sid/token to match my info...

答:
PEP 274 -- Dict Comprehensions states: All implementation details were resolved in the Python 2.7 and 3.0 time-frame.

You are using python2.6.

Title: Twilio send sms from python errors

Body:
I am trying to follow the tutorial in Twilio to send an SMS message from Python.  I have followed their code, but am getting this error:

[root@helios03 ~]# python sms.py
Traceback (most recent call last):
  File "sms.py", line 10, in <module>
    message = client.api.account.messages.create(to="+12316851234",
  File "/usr/lib/python2.6/site-packages/twilio/rest/__init__.py", line 138, in api
    from twilio.rest.api import Api
  File "/usr/lib/python2.6/site-packages/twilio/rest/api/__init__.py", line 10, in <module>
    from twilio.rest.api.v2010 import V2010
  File "/usr/lib/python2.6/site-packages/twilio/rest/api/v2010/__init__.py", line 9, in <module>
    from twilio.base.version import Version
  File "/usr/lib/python2.6/site-packages/twilio/base/version.py", line 4, in <module>
    from twilio.base import values
  File "/usr/lib/python2.6/site-packages/twilio/base/values.py", line 12
    return {k: v for k, v in iteritems(d) if v != unset}
                   ^
SyntaxError: invalid syntax

Thoughts?  I did a "pip install twilio" to install the helper..

Their example code is:

# /usr/bin/env python
# Download the twilio-python library from http://twilio.com/docs/libraries
from twilio.rest import Client

# Find these values at https://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXX"
auth_token = "YYYYYYYYYYYYYYYYYY"
client = Client(account_sid, auth_token)

message = client.api.account.messages.create(to="+12316851234",
                                             from_="+15555555555",
                                             body="Hello there!")

I have replaced the to/from numbers and account sid/token to match my info...


答:
The star character is a quantifier in a regular expression. If you literally mean the star character you have to escape it. The following expression allows one or more stars followed by one or more ciphers or one or more ciphers followed by one or more stars.</p>

```<code>Pattern p = Pattern.compile("(\\*+[0-9]+)|([0-9]+\\*+)");
</code>```

Title: regex pattern expressions

Body:
The star character is a quantifier in a regular expression. If you literally mean the star character you have to escape it. The following expression allows one or more stars followed by one or more ciphers or one or more ciphers followed by one or more stars.

Pattern p = Pattern.compile("(\\*+[0-9]+)|([0-9]+\\*+)");


问:
How to get or see xgboost's gradient statistics value?
I'm studying xgboost and novice for gradient boost.
In gradient tree boosting, loss function is derived by second order approximation calculating gi, hi. You can see it on https://xgboost.readthedocs.io/en/latest/model.html#the-structure-score .
Given a dataset, how can I see the value gi, hi such as g1, h1, g2, h2,..?

I saw _train_internal and several functions in training.py and sklean.py. But I didn't find it. By understanding how it calculated and got efficiently, it could be possible to apply further algorithm used in xgboost such as quantile percentile sketch.

Thanks.

答:
To keep track of the gradient updates in each iteration, you would need to expose the training loop in python (rather than have it execute internally in the C++ implementation), and provide custom gradient and hessian implementations. For many of the standard loss functions, e.g., squared loss, logistic loss, this is quite simple and not hard to find in standard references. Here's an example showing how to expose the training loop for logistic regression.</p>

```<code>import numpy as np
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.metrics import confusion_matrix

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def logregobj(preds, dtrain):
    """log likelihood loss"""
    labels = dtrain.get_label()
    preds = sigmoid(preds)
    grad = preds - labels
    hess = preds * (1.0-preds)
    return grad, hess

# Build a toy dataset.
X, Y = make_classification(n_samples=1000, n_features=5, n_redundant=0, n_informative=3,
                           random_state=1, n_clusters_per_class=1)

# Instantiate a Booster object to do the heavy lifting
dtrain = xgb.DMatrix(X, label=Y)
params = {'max_depth': 2, 'eta': 1, 'silent': 1}
num_round = 2
model = xgb.Booster(params, [dtrain])

# Run 10 boosting iterations
# g and h can be monitored for gradient statistics
for _ in range(10):
    pred = model.predict(dtrain)
    g, h = logregobj(pred, dtrain)
    model.boost(dtrain, g, h)

# Evaluate predictions
yhat = model.predict(dtrain)
yhat = 1.0 / (1.0 + np.exp(-yhat))
yhat_labels = np.round(yhat)
confusion_matrix(Y, yhat_labels)
</code>```

Body:
To keep track of the gradient updates in each iteration, you would need to expose the training loop in python (rather than have it execute internally in the C++ implementation), and provide custom gradient and hessian implementations. For many of the standard loss functions, e.g., squared loss, logistic loss, this is quite simple and not hard to find in standard references. Here's an example showing how to expose the training loop for logistic regression.

import numpy as np
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.metrics import confusion_matrix

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def logregobj(preds, dtrain):
    """log likelihood loss"""
    labels = dtrain.get_label()
    preds = sigmoid(preds)
    grad = preds - labels
    hess = preds * (1.0-preds)
    return grad, hess

# Build a toy dataset.
X, Y = make_classification(n_samples=1000, n_features=5, n_redundant=0, n_informative=3,
                           random_state=1, n_clusters_per_class=1)

# Instantiate a Booster object to do the heavy lifting
dtrain = xgb.DMatrix(X, label=Y)
params = {'max_depth': 2, 'eta': 1, 'silent': 1}
num_round = 2
model = xgb.Booster(params, [dtrain])

# Run 10 boosting iterations
# g and h can be monitored for gradient statistics
for _ in range(10):
    pred = model.predict(dtrain)
    g, h = logregobj(pred, dtrain)
    model.boost(dtrain, g, h)

# Evaluate predictions
yhat = model.predict(dtrain)
yhat = 1.0 / (1.0 + np.exp(-yhat))
yhat_labels = np.round(yhat)
confusion_matrix(Y, yhat_labels)


问:
How to send JSONObject request in retrofit?
I was trying to send JSONObject request (POST method) using retrofit and get the  results as JSONObject, how can i achieve that.? my content type is (application/json)
Could you share some of your best methods ?

retrofit Interface class

```<code>public interface RequestClient {
@Headers("Content-Type: application/json")
@POST("TripmakersLowFareShopping")
Call<FlightResponse>pushRequest(@Body FlightRequest request);  }
</code>```

Request Model Class

```<code>public class FlightRequest {

@SerializedName("AgencyID")
@Expose
private String agencyID;
@SerializedName("BranchID")
@Expose
private String branchID;
@SerializedName("OriginDestinationInformations")
@Expose
private ArrayList<OriginDestinationInformation> originDestinationInformations = null;
@SerializedName("PassengerTypeQuantities")
@Expose
private ArrayList<PassengerTypeQuantity> passengerTypeQuantities = null;
@SerializedName("Password")
@Expose
private String password;
@SerializedName("PricingSourceType")
@Expose
private Integer pricingSourceType;
@SerializedName("RequestOptions")
@Expose
private Integer requestOptions;
@SerializedName("SessionId")
@Expose
private Object sessionId;
@SerializedName("SupplierParameterList")
@Expose
private ArrayList<SupplierParameterList> supplierParameterList = null;
@SerializedName("Target")
@Expose
private Integer target;
@SerializedName("TravelPreferences")
@Expose
private TravelPreferences travelPreferences;
@SerializedName("UserName")
@Expose
private String userName;

/**
 * No args constructor for use in serialization
 *
 */

public FlightRequest() {
    super();
    this.agencyID = "20083";
    this.branchID = "10161";
    this.password = "Tj9%2f30XvS59GOBsjHuMd%2bg%3d%3d";
    this.pricingSourceType = 0;
    this.requestOptions = 0;
    this.sessionId = null;
    this.target = 0;
    this.userName = "qc@*****.com";
}

public String getAgencyID() {
    return agencyID;
}

public void setAgencyID(String agencyID) {
    this.agencyID = agencyID;
}

public String getBranchID() {
    return branchID;
}

public void setBranchID(String branchID) {
    this.branchID = branchID;
}

public List<OriginDestinationInformation> getOriginDestinationInformations() {
    return originDestinationInformations;
}

public void setOriginDestinationInformations(ArrayList<OriginDestinationInformation> originDestinationInformations) {
    this.originDestinationInformations = originDestinationInformations;
}

public List<PassengerTypeQuantity> getPassengerTypeQuantities() {
    return passengerTypeQuantities;
}

public void setPassengerTypeQuantities(ArrayList<PassengerTypeQuantity> passengerTypeQuantities) {
    this.passengerTypeQuantities = passengerTypeQuantities;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Integer getPricingSourceType() {
    return pricingSourceType;
}

public void setPricingSourceType(Integer pricingSourceType) {
    this.pricingSourceType = pricingSourceType;
}

public Integer getRequestOptions() {
    return requestOptions;
}

public void setRequestOptions(Integer requestOptions) {
    this.requestOptions = requestOptions;
}

public Object getSessionId() {
    return sessionId;
}

public void setSessionId(Object sessionId) {
    this.sessionId = sessionId;
}

public List<SupplierParameterList> getSupplierParameterList() {
    return supplierParameterList;
}

public void setSupplierParameterList(ArrayList<SupplierParameterList> supplierParameterList) {
    this.supplierParameterList = supplierParameterList;
}

public Integer getTarget() {
    return target;
}

public void setTarget(Integer target) {
    this.target = target;
}

public TravelPreferences getTravelPreferences() {
    return travelPreferences;
}

public void setTravelPreferences(TravelPreferences travelPreferences) {
    this.travelPreferences = travelPreferences;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}
</code>```

}
Response model class

```<code>public class FlightResponse {

private JSONObject responceData;

public JSONObject getResponceData() {
    return responceData;
}

public void setResponceData(JSONObject responceData) {
    this.responceData = responceData;
}
</code>```

}

Retrofit declaration and functional part

```<code>   rqbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ArrayList<OriginDestinationInformation> originlist = new ArrayList<>();
            originlist.add(new OriginDestinationInformation(null,"/Date(1503599400000)/",null,"COK","DXB"));
            ArrayList<PassengerTypeQuantity> typeQuantities = new ArrayList<>();
            ArrayList<SupplierParameterList>supplierParameterLists = new ArrayList<SupplierParameterList>();
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserIPAddress","61.0.250.97"));
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserBrowserAgent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"));
            supplierParameterLists.add(new SupplierParameterList(false,null,null));
            supplierParameterLists.add(new SupplierParameterList(false,"UserData","qc@tripmakers.com,971_527564545,Fateh"));
            supplierParameterLists.add(new SupplierParameterList(false,"RequestOrigin","US-localhost"));

            typeQuantities.add(new PassengerTypeQuantity(1,1));
            TravelPreferences travelPreferences = new TravelPreferences(1,1);
            FlightRequest request = new FlightRequest();
            request.setOriginDestinationInformations(originlist);
            request.setPassengerTypeQuantities(typeQuantities);
            request.setTravelPreferences(travelPreferences);
            request.setSupplierParameterList(supplierParameterLists);

            requestCall(request);
        }
    });
}

private void requestCall(FlightRequest request) {
     OkHttpClient.Builder httpClient ;

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://192.168.1.125:8013/flight/").addConverterFactory(GsonConverterFactory.create());
    Retrofit retrofit = builder.build();
    RequestClient client = retrofit.create(RequestClient.class);

    Call<FlightResponse> requestCall = client.pushRequest(request);
    requestCall.enqueue(new Callback<FlightResponse>() {
        @Override
        public void onResponse(Call<FlightResponse> call, Response<FlightResponse> response) {
            Toast.makeText(RetrofitResults.this, "Sucess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<FlightResponse> call, Throwable t) {
            Toast.makeText(RetrofitResults.this, "Something went wrong", Toast.LENGTH_SHORT).show();
        }
    });
}
</code>```

答:
In your Activity or fragment you can implements ServiceCallBack for result onSuccess or onFail and can call a method like:

```<code>//service call
public void callRoadTrafficIncident(JSONObject jsonObject) {
    try {

        BaseRequest baseRequest = new BaseRequest(this);
        baseRequest.setServiceCallBack(this);
        baseRequest.setRequestTag(UrlFactory.SAVERTI);
        Api api = (Api) baseRequest.execute(Api.class);
        if (api != null) {
            TypedInput requestBody = new TypedByteArray(
                    "application/json", jsonObject.toString().getBytes(Charset.forName("UTF-8")));
            api.saveRTI(requestBody, baseRequest.requestCallback());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

For Api interface you can create like:

```<code>public interface Api {

    @Headers({"Content-Type:application/json"})
    @POST("/saveRTI")
    public void saveRTI(@Body TypedInput jsonObject, Callback<String> callback);}
</code>```

For baseRequest class :

```<code>public class BaseRequest {

    private int requestTag;
    private boolean progressShow = true;
    private ServiceCallBack serviceCallBack;
    private RestClient restClient;
    private Context context;
    private Callback<Object> callback;

    public BaseRequest(Context context){
        this.context = context;
        setProgressShow(progressShow);
    }

    public Object execute(Class classes){
        if(Utils.getConnectivityStatus(context)){
            restClient=  new RestClient(context,this);
            return restClient.execute(classes);
        }else{

            //Utils.showToast(context, "Network is not available.");
            return null;
        }
    }

    public Callback<String> requestCallback(){

        return restClient.callback;
    }
    public Callback<Object> getCallback() {
        return callback;
    }

    public void setCallback(Callback<Object> callback) {
        this.callback = callback;
    }

    public RestClient getRestClient() {
        return restClient;
    }

    public void setRestClient(RestClient restClient) {
        this.restClient = restClient;
    }

    public ServiceCallBack getServiceCallBack() {
        return serviceCallBack;
    }

    public void setServiceCallBack(ServiceCallBack serviceCallBack) {
        this.serviceCallBack = serviceCallBack;
    }

    public int getRequestTag() {
        return requestTag;
    }

    public void setRequestTag(int requestType) {
        this.requestTag = requestType;
    }

    public boolean isProgressShow() {
        return progressShow;
    }

    public void setProgressShow(boolean progressShow) {
        this.progressShow = progressShow;
    }

}
</code>```

For RestClient call class:

```<code>public class RestClient {

    private BaseRequest baseRequest;
    private ProgressDialog pDialog = null;
    private Context context;

    public RestClient(Context context, BaseRequest _baseRequest) {
        this.baseRequest = _baseRequest;
        this.context = context;
    }

    public Object execute(Class classes) {
        if (baseRequest.isProgressShow())
            showProgressDialog(context);
        return setUpRestClient(classes);
    }

    private Object setUpRestClient(Class apiClasses) {

        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(120, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(120, TimeUnit.SECONDS);

        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(UrlFactory.BASE_URL)
                .setRequestInterceptor(new SessionRequestInterceptor(context))
                .setClient(new OkClient(okHttpClient));

        builder.setConverter(new StringConverter());
        RestAdapter restAdapter = builder.build();
        return restAdapter.create(apiClasses);
    }

    public Callback<String> callback = new Callback<String>() {

        @Override
        public void success(String o, Response response) {
            if (o != null && !o.isEmpty())
            baseRequest.getServiceCallBack().onSuccess(baseRequest.getRequestTag(), o);
            dismissProgressDialog();

        }

        @Override
        public void failure(RetrofitError error) {
            baseRequest.getServiceCallBack().onFail(error);
            dismissProgressDialog();
        }

    };

    public void showProgressDialog(Context context) {
        try {
            if (((Activity) context).isFinishing()) {
                return;
            }
            pDialog = new ProgressDialog(context);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissProgressDialog() {
        try {
            if (pDialog != null)
                pDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class StringConverter implements Converter {

        @Override
        public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
            String text = null;
            try {

                text = fromStream(typedInput.in());
            } catch (IOException ignored) {
                ignored.printStackTrace();
            }
            return text;
        }

        @Override
        public TypedOutput toBody(Object o) {

            return null;
        }

        private String fromStream(InputStream in) throws IOException {

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder out = new StringBuilder();
            String newLine = System.getProperty("line.separator");
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
                out.append(newLine);
            }
            return out.toString();
        }
    }

}
</code>```

For Service callback interface

```<code>public interface ServiceCallBack
{
    public void onSuccess(int tag, String baseResponse);
    public void onFail(RetrofitError error);
}
</code>```

For SessionRequest  Intercepter

```<code>public class SessionRequestInterceptor implements RequestInterceptor {
    private Context context;

    public  SessionRequestInterceptor(Context context){
        this.context = context;
    }
    @Override
    public void intercept(RequestFacade request) {
    request.addHeader("Content-Type", "application/json");
    request.addHeader("accept", "application/json");
    }
}
</code>```

Body:
I was trying to send JSONObject request (POST method) using retrofit and get the  results as JSONObject, how can i achieve that.? my content type is (application/json)
Could you share some of your best methods ?

retrofit Interface class

public interface RequestClient {
@Headers("Content-Type: application/json")
@POST("TripmakersLowFareShopping")
Call<FlightResponse>pushRequest(@Body FlightRequest request);  }

Request Model Class

public class FlightRequest {

@SerializedName("AgencyID")
@Expose
private String agencyID;
@SerializedName("BranchID")
@Expose
private String branchID;
@SerializedName("OriginDestinationInformations")
@Expose
private ArrayList<OriginDestinationInformation> originDestinationInformations = null;
@SerializedName("PassengerTypeQuantities")
@Expose
private ArrayList<PassengerTypeQuantity> passengerTypeQuantities = null;
@SerializedName("Password")
@Expose
private String password;
@SerializedName("PricingSourceType")
@Expose
private Integer pricingSourceType;
@SerializedName("RequestOptions")
@Expose
private Integer requestOptions;
@SerializedName("SessionId")
@Expose
private Object sessionId;
@SerializedName("SupplierParameterList")
@Expose
private ArrayList<SupplierParameterList> supplierParameterList = null;
@SerializedName("Target")
@Expose
private Integer target;
@SerializedName("TravelPreferences")
@Expose
private TravelPreferences travelPreferences;
@SerializedName("UserName")
@Expose
private String userName;

/**
 * No args constructor for use in serialization
 *
 */

public FlightRequest() {
    super();
    this.agencyID = "20083";
    this.branchID = "10161";
    this.password = "Tj9%2f30XvS59GOBsjHuMd%2bg%3d%3d";
    this.pricingSourceType = 0;
    this.requestOptions = 0;
    this.sessionId = null;
    this.target = 0;
    this.userName = "qc@*****.com";
}

public String getAgencyID() {
    return agencyID;
}

public void setAgencyID(String agencyID) {
    this.agencyID = agencyID;
}

public String getBranchID() {
    return branchID;
}

public void setBranchID(String branchID) {
    this.branchID = branchID;
}

public List<OriginDestinationInformation> getOriginDestinationInformations() {
    return originDestinationInformations;
}

public void setOriginDestinationInformations(ArrayList<OriginDestinationInformation> originDestinationInformations) {
    this.originDestinationInformations = originDestinationInformations;
}

public List<PassengerTypeQuantity> getPassengerTypeQuantities() {
    return passengerTypeQuantities;
}

public void setPassengerTypeQuantities(ArrayList<PassengerTypeQuantity> passengerTypeQuantities) {
    this.passengerTypeQuantities = passengerTypeQuantities;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Integer getPricingSourceType() {
    return pricingSourceType;
}

public void setPricingSourceType(Integer pricingSourceType) {
    this.pricingSourceType = pricingSourceType;
}

public Integer getRequestOptions() {
    return requestOptions;
}

public void setRequestOptions(Integer requestOptions) {
    this.requestOptions = requestOptions;
}

public Object getSessionId() {
    return sessionId;
}

public void setSessionId(Object sessionId) {
    this.sessionId = sessionId;
}

public List<SupplierParameterList> getSupplierParameterList() {
    return supplierParameterList;
}

public void setSupplierParameterList(ArrayList<SupplierParameterList> supplierParameterList) {
    this.supplierParameterList = supplierParameterList;
}

public Integer getTarget() {
    return target;
}

public void setTarget(Integer target) {
    this.target = target;
}

public TravelPreferences getTravelPreferences() {
    return travelPreferences;
}

public void setTravelPreferences(TravelPreferences travelPreferences) {
    this.travelPreferences = travelPreferences;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

}
Response model class

public class FlightResponse {

private JSONObject responceData;

public JSONObject getResponceData() {
    return responceData;
}

public void setResponceData(JSONObject responceData) {
    this.responceData = responceData;
}

}

Retrofit declaration and functional part

   rqbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ArrayList<OriginDestinationInformation> originlist = new ArrayList<>();
            originlist.add(new OriginDestinationInformation(null,"/Date(1503599400000)/",null,"COK","DXB"));
            ArrayList<PassengerTypeQuantity> typeQuantities = new ArrayList<>();
            ArrayList<SupplierParameterList>supplierParameterLists = new ArrayList<SupplierParameterList>();
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserIPAddress","61.0.250.97"));
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserBrowserAgent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"));
            supplierParameterLists.add(new SupplierParameterList(false,null,null));
            supplierParameterLists.add(new SupplierParameterList(false,"UserData","qc@tripmakers.com,971_527564545,Fateh"));
            supplierParameterLists.add(new SupplierParameterList(false,"RequestOrigin","US-localhost"));

            typeQuantities.add(new PassengerTypeQuantity(1,1));
            TravelPreferences travelPreferences = new TravelPreferences(1,1);
            FlightRequest request = new FlightRequest();
            request.setOriginDestinationInformations(originlist);
            request.setPassengerTypeQuantities(typeQuantities);
            request.setTravelPreferences(travelPreferences);
            request.setSupplierParameterList(supplierParameterLists);

            requestCall(request);
        }
    });
}

private void requestCall(FlightRequest request) {
     OkHttpClient.Builder httpClient ;

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://192.168.1.125:8013/flight/").addConverterFactory(GsonConverterFactory.create());
    Retrofit retrofit = builder.build();
    RequestClient client = retrofit.create(RequestClient.class);

    Call<FlightResponse> requestCall = client.pushRequest(request);
    requestCall.enqueue(new Callback<FlightResponse>() {
        @Override
        public void onResponse(Call<FlightResponse> call, Response<FlightResponse> response) {
            Toast.makeText(RetrofitResults.this, "Sucess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<FlightResponse> call, Throwable t) {
            Toast.makeText(RetrofitResults.this, "Something went wrong", Toast.LENGTH_SHORT).show();
        }
    });
}

Body:
In your Activity or fragment you can implements ServiceCallBack for result onSuccess or onFail and can call a method like:

//service call
public void callRoadTrafficIncident(JSONObject jsonObject) {
    try {

        BaseRequest baseRequest = new BaseRequest(this);
        baseRequest.setServiceCallBack(this);
        baseRequest.setRequestTag(UrlFactory.SAVERTI);
        Api api = (Api) baseRequest.execute(Api.class);
        if (api != null) {
            TypedInput requestBody = new TypedByteArray(
                    "application/json", jsonObject.toString().getBytes(Charset.forName("UTF-8")));
            api.saveRTI(requestBody, baseRequest.requestCallback());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

For Api interface you can create like:

public interface Api {

    @Headers({"Content-Type:application/json"})
    @POST("/saveRTI")
    public void saveRTI(@Body TypedInput jsonObject, Callback<String> callback);}

For baseRequest class :

public class BaseRequest {

    private int requestTag;
    private boolean progressShow = true;
    private ServiceCallBack serviceCallBack;
    private RestClient restClient;
    private Context context;
    private Callback<Object> callback;

    public BaseRequest(Context context){
        this.context = context;
        setProgressShow(progressShow);
    }

    public Object execute(Class classes){
        if(Utils.getConnectivityStatus(context)){
            restClient=  new RestClient(context,this);
            return restClient.execute(classes);
        }else{

            //Utils.showToast(context, "Network is not available.");
            return null;
        }
    }

    public Callback<String> requestCallback(){

        return restClient.callback;
    }
    public Callback<Object> getCallback() {
        return callback;
    }

    public void setCallback(Callback<Object> callback) {
        this.callback = callback;
    }

    public RestClient getRestClient() {
        return restClient;
    }

    public void setRestClient(RestClient restClient) {
        this.restClient = restClient;
    }

    public ServiceCallBack getServiceCallBack() {
        return serviceCallBack;
    }

    public void setServiceCallBack(ServiceCallBack serviceCallBack) {
        this.serviceCallBack = serviceCallBack;
    }

    public int getRequestTag() {
        return requestTag;
    }

    public void setRequestTag(int requestType) {
        this.requestTag = requestType;
    }

    public boolean isProgressShow() {
        return progressShow;
    }

    public void setProgressShow(boolean progressShow) {
        this.progressShow = progressShow;
    }

}

For RestClient call class:

public class RestClient {

    private BaseRequest baseRequest;
    private ProgressDialog pDialog = null;
    private Context context;

    public RestClient(Context context, BaseRequest _baseRequest) {
        this.baseRequest = _baseRequest;
        this.context = context;
    }

    public Object execute(Class classes) {
        if (baseRequest.isProgressShow())
            showProgressDialog(context);
        return setUpRestClient(classes);
    }

    private Object setUpRestClient(Class apiClasses) {

        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(120, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(120, TimeUnit.SECONDS);

        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(UrlFactory.BASE_URL)
                .setRequestInterceptor(new SessionRequestInterceptor(context))
                .setClient(new OkClient(okHttpClient));

        builder.setConverter(new StringConverter());
        RestAdapter restAdapter = builder.build();
        return restAdapter.create(apiClasses);
    }

    public Callback<String> callback = new Callback<String>() {

        @Override
        public void success(String o, Response response) {
            if (o != null && !o.isEmpty())
            baseRequest.getServiceCallBack().onSuccess(baseRequest.getRequestTag(), o);
            dismissProgressDialog();

        }

        @Override
        public void failure(RetrofitError error) {
            baseRequest.getServiceCallBack().onFail(error);
            dismissProgressDialog();
        }

    };

    public void showProgressDialog(Context context) {
        try {
            if (((Activity) context).isFinishing()) {
                return;
            }
            pDialog = new ProgressDialog(context);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissProgressDialog() {
        try {
            if (pDialog != null)
                pDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class StringConverter implements Converter {

        @Override
        public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
            String text = null;
            try {

                text = fromStream(typedInput.in());
            } catch (IOException ignored) {
                ignored.printStackTrace();
            }
            return text;
        }

        @Override
        public TypedOutput toBody(Object o) {

            return null;
        }

        private String fromStream(InputStream in) throws IOException {

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder out = new StringBuilder();
            String newLine = System.getProperty("line.separator");
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
                out.append(newLine);
            }
            return out.toString();
        }
    }

}

For Service callback interface

public interface ServiceCallBack
{
    public void onSuccess(int tag, String baseResponse);
    public void onFail(RetrofitError error);
}

For SessionRequest  Intercepter

public class SessionRequestInterceptor implements RequestInterceptor {
    private Context context;

    public  SessionRequestInterceptor(Context context){
        this.context = context;
    }
    @Override
    public void intercept(RequestFacade request) {
    request.addHeader("Content-Type", "application/json");
    request.addHeader("accept", "application/json");
    }
}


问:
textbox isReadonly to change with combobox selecteditem
I have datatemplate and list of 5 rows. So in every row, there is combobox with two comboboxitems "yes" and "no". So when the window is loaded, textboxes inside ListBox rows are set to readonly="True" inside the Datatemplate. But when I select "no" from combobox items in individual row, then textbox should become editable and isReadonly="False" for each individual row in the List. My ListBox items are 5. How to do this?</p>

```<code>//xaml
 <ListBox x:Name="wbListDataTemplate"
                                  ItemsSource="{Binding wbVisibleItems}"
                                  DataContext="{DynamicResource wbItem}"
                                  Background="{x:Null}"
                                 SelectedItem="{Binding wbSelectedItem, Mode=TwoWay, UpdateSourceTrigger=Default}"
                                 IsSynchronizedWithCurrentItem="True" Canvas.Top="33"  Height="152" Width="628" LostFocus="wbListDataTemplate_LostFocus" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Initialized="wbListDataTemplate_Initialized_1">

                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <Grid Grid.ColumnSpan="1" Grid.RowSpan="1" Height="39" Width="642" Margin="0,0,0,-14" >
                                        <Grid x:Name="Grid1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="697"  Margin="10,0,0,0" Height="54" >

                                            <Label Margin="0,3,0,5" Grid.Row="0" Grid.Column="0" Grid.RowSpan="2"/>

                                            <ComboBox x:Name="wbselect" Margin="0,0,60,1" Grid.Column="0"  Grid.ColumnSpan="2" Grid.Row="0" Loaded="wbselect_Loaded" >
                                                <ComboBoxItem x:Name="wbyes" IsSelected="True" Content="yes"></ComboBoxItem>
                                                <ComboBoxItem x:Name="wbno" Content="no"></ComboBoxItem>
                                            </ComboBox>
                                            <TextBox x:Name="wbdepth" Text="" MaxLength="20" Margin="217,0,230,1" LostKeyboardFocus="wbdepth_LostKeyboardFocus" Grid.ColumnSpan="2" IsReadOnly="True"/>

                                        </Grid>
                                    </Grid>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
</code>```

答:
I would use an IValueConverter which could look like this.

```<code>public class ReadonlyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var content = ((ComboBoxItem)value).Content;
        var isEnabled = content.Equals("yes");

        return isEnabled;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

And in your xaml you have to change

```<code>IsReadOnly="True"
</code>```

to

```<code>IsReadOnly="{Binding ElementName=wbselect, Path=SelectedItem, Converter={StaticResource ReadOnlyConverter}}"
</code>```

And you have to add a reference to your converter

```<code><Window xmlns:converter="clr-namespace:WpfApplication1.Converters">
    <Window.Resources>
        <ResourceDictionary>
            <converter:ReadonlyConverter x:Key="ReadOnlyConverter"/>
        </ResourceDictionary>
    </Window.Resources>
</code>```

Body:
I have datatemplate and list of 5 rows. So in every row, there is combobox with two comboboxitems "yes" and "no". So when the window is loaded, textboxes inside ListBox rows are set to readonly="True" inside the Datatemplate. But when I select "no" from combobox items in individual row, then textbox should become editable and isReadonly="False" for each individual row in the List. My ListBox items are 5. How to do this?

//xaml
 <ListBox x:Name="wbListDataTemplate"
                                  ItemsSource="{Binding wbVisibleItems}"
                                  DataContext="{DynamicResource wbItem}"
                                  Background="{x:Null}"
                                 SelectedItem="{Binding wbSelectedItem, Mode=TwoWay, UpdateSourceTrigger=Default}"
                                 IsSynchronizedWithCurrentItem="True" Canvas.Top="33"  Height="152" Width="628" LostFocus="wbListDataTemplate_LostFocus" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Initialized="wbListDataTemplate_Initialized_1">

                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <Grid Grid.ColumnSpan="1" Grid.RowSpan="1" Height="39" Width="642" Margin="0,0,0,-14" >
                                        <Grid x:Name="Grid1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="697"  Margin="10,0,0,0" Height="54" >

                                            <ComboBox x:Name="wbselect" Margin="0,0,60,1" Grid.Column="0"  Grid.ColumnSpan="2" Grid.Row="0" Loaded="wbselect_Loaded" >
                                                <ComboBoxItem x:Name="wbyes" IsSelected="True" Content="yes"></ComboBoxItem>
                                                <ComboBoxItem x:Name="wbno" Content="no"></ComboBoxItem>
                                            </ComboBox>
                                            <TextBox x:Name="wbdepth" Text="" MaxLength="20" Margin="217,0,230,1" LostKeyboardFocus="wbdepth_LostKeyboardFocus" Grid.ColumnSpan="2" IsReadOnly="True"/>

                                        </Grid>
                                    </Grid>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>

Body:
I would use an IValueConverter which could look like this.

public class ReadonlyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var content = ((ComboBoxItem)value).Content;
        var isEnabled = content.Equals("yes");

        return isEnabled;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And in your xaml you have to change

IsReadOnly="True"

to

IsReadOnly="{Binding ElementName=wbselect, Path=SelectedItem, Converter={StaticResource ReadOnlyConverter}}"

And you have to add a reference to your converter

<Window xmlns:converter="clr-namespace:WpfApplication1.Converters">
    <Window.Resources>
        <ResourceDictionary>
            <converter:ReadonlyConverter x:Key="ReadOnlyConverter"/>
        </ResourceDictionary>
    </Window.Resources>


问:
Regex - everything except string
I would like to replace every char that is not a string for a given char like | or ; or whatever.
I have simple regex patern: ([a-zA-Z])\w+

...and the problem is to replace everything except matches of that pattern.

Example: qwerty 123456 ;,.'[]?/ asd

Result: qwerty|||||||||||||||||asd

Thanks in advance.

答:
You can negate the characters in your character set using ^.

\w needs to be omitted, because otherwise it will also try to match any word character

The brackets are not necessary, since there is no need to group a single character set and you are not using a backreference to that capturing group

This results in the following regex:

```<code>[^a-zA-Z]+
</code>```

Title: Regex - everything except string

Body:
You can negate the characters in your character set using ^.

\w needs to be omitted, because otherwise it will also try to match any word character

The brackets are not necessary, since there is no need to group a single character set and you are not using a backreference to that capturing group

This results in the following regex:

[^a-zA-Z]+


问:
How to change text color based on specific option?
I want to change the first option's color to #ccc, others remain #000, but it doesn't work.Why? thanks.
 I don't wnat to use change function, which I think it's unnecessary.

something like this:

HTML:

```<code>  <select id="continent">
      <option value="-1">continent</option>
      <option value="1">US</option>
      <option value="2">UK</option>
  </select>
</code>```

JS:

```<code>$("#continent option[value='-1']").css('color','#ccc');
</code>```

答:
here is solution

```<code>$('.mySelect').change(function () {
     if($(this).find("option:selected").attr("value")==2){
    $(this).find('option:selected').css('color', 'red');
    }else{
     $(this).find('option:selected').css('color', 'blue');
    }

});
</code>```

In above code i use .find() method which is used for select child of selected element try this code in fiddle

Body:
I want to change the first option's color to #ccc, others remain #000, but it doesn't work.Why? thanks.
 I don't wnat to use change function, which I think it's unnecessary.

something like this:

HTML:

  <select id="continent">
      <option value="-1">continent</option>
      <option value="1">US</option>
      <option value="2">UK</option>
  </select>

JS:

$("#continent option[value='-1']").css('color','#ccc');

Body:
here is solution

$('.mySelect').change(function () {
     if($(this).find("option:selected").attr("value")==2){
    $(this).find('option:selected').css('color', 'red');
    }else{
     $(this).find('option:selected').css('color', 'blue');
    }

});

In above code i use .find() method which is used for select child of selected element try this code in fiddle


问:
What's the difference between curl -v vs curl -I
What's the difference between curl -v and curl -I?

I can see -v is verbose and -I is headers. Anything specific though?

答:
-I (uppercase letter i) means "no body" in curl speak, which for HTTP means sending a HEAD request. Such a request doesn't get response body. It also enables "show response headers".

-v (lower case letter v) means "verbose mode please" and will make curl show its request, the response headers and additional informational details about the transfer performed.

Additionally

You can get even more information with --trace or --trace-ascii or you can select to get to see the response headers as part of the regular output if you use -i (lower case letter i).


问:
php warning when use filetime()
I'm making a table in php that gets the file name in a directory.
Like this:

```<code>$myDirectory = opendir("./server/sandro/Sandro-PC/Printscreens/");
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

closedir($myDirectory);

$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");

sort($dirArray);
print("<TABLE class=table>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){
        echo('<TR><TD><a href="server/sandro/Sandro-PC/Printscreens/'.$dirArray[$index].'"><img height="80" width="120" src="server/sandro/Sandro-PC/Printscreens/'.$dirArray[$index].'"</a></td>');
        print("<td>");
        echo(filemtime($dirArray[$index]));
        print("</td>");
        print("<td>");
        print(filesize($dirArray[$index]));
        print("</td>");
        print("</TR>\n");
    }
}
print("</TABLE>\n");
</code>```

But in the function filemtime() or filesize()
give this error:

Warning: filemtime(): stat failed for image.png in C:\xampp\htdocs\dashboard3\printscreens.php on line 167

How can I solve this?

答:
In the above code it is fetching the file name but not getting the file path. When we are doing the filesize() or filemtime() please pass the file name with directory. I just modifies the code as below , please try</p>

```<code><?php

 $myDirectory = opendir("./server/sandro/Sandro-PC/Printscreens/");
 $mdir = "./server/sandro/Sandro-PC/Printscreens/";
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

closedir($myDirectory);

$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");

sort($dirArray);
print("<TABLE class=table>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){
        echo('<TR><TD><a href="server/sandro/Sandro-PC/Printscreens/'.$dirArray[$index].'"><img height="80" width="120" src="server/sandro/Sandro-PC/Printscreens/'.$dirArray[$index].'"</a></td>');
        print("<td>");
        //echo(filemtime($dirArray[$index]));
        $filename = "$mdir\\$dirArray[$index]";
        echo $filename;
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
        //echo filemtime($dirArray[$index]);
        print("</td>");
        print("<td>");
       // print(filesize($dirArray[$index]));
        print("</td>");
        print("</TR>\n");
    }
}

print("</TABLE>\n");

?>
</code>```

Title: php warning when use filetime()

Body:
I'm making a table in php that gets the file name in a directory.
Like this:

$myDirectory = opendir("./server/sandro/Sandro-PC/Printscreens/");
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

closedir($myDirectory);

$indexCount = count($dirArray);
Print ("$indexCount files
\n");

sort($dirArray);
print("
\n");
print("
Filename	Filetype	Filesize
\n");

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){
        echo('
<img height="80" width="120" src="server/sandro/Sandro-PC/Printscreens/'.$dirArray[$index].'"	');
        print("");
        echo(filemtime($dirArray[$index]));
        print("	");
        print("");
        print(filesize($dirArray[$index]));
        print("	");
        print("
\n");
    }
}
print("
\n");

But in the function filemtime() or filesize()
give this error:

Warning: filemtime(): stat failed for image.png in C:\xampp\htdocs\dashboard3\printscreens.php on line 167

How can I solve this?

Body:
In the above code it is fetching the file name but not getting the file path. When we are doing the filesize() or filemtime() please pass the file name with directory. I just modifies the code as below , please try

<?php

 $myDirectory = opendir("./server/sandro/Sandro-PC/Printscreens/");
 $mdir = "./server/sandro/Sandro-PC/Printscreens/";
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

closedir($myDirectory);

$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");

sort($dirArray);
print("<TABLE class=table>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){
        echo('<TR><TD><a href="server/sandro/Sandro-PC/Printscreens/'.$dirArray[$index].'"><img height="80" width="120" src="server/sandro/Sandro-PC/Printscreens/'.$dirArray[$index].'"</a></td>');
        print("<td>");
        //echo(filemtime($dirArray[$index]));
        $filename = "$mdir\\$dirArray[$index]";
        echo $filename;
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
        //echo filemtime($dirArray[$index]);
        print("</td>");
        print("<td>");
       // print(filesize($dirArray[$index]));
        print("</td>");
        print("</TR>\n");
    }
}

print("</TABLE>\n");

?>


问:
Get screen size in px on Android N with changed display zoom
I have a problem with the calculation of the display size on Android N with a changed display zoom.

With Android N you can change the display zoom (check here)

but the display size (...getSize()) doesn't change if the user sets a zoom from android settings...

Any idea to solve it? Have I to use the size in px multiplied by scaledDensity to have a real display size?

My app dinamically creates windows and components calculating screen dimensions in px, the components are designed on a server.
Briefly I do a math proportion by the width set on the server and the width of the smartphone screen :

```<code>DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
   display.getRealSize(sizePoint);
}else{
   display.getSize(sizePoint);
}
int smartphoneDisplayWidth =  sizePoint.x;
int smartphoneDisplayHeight = sizePoint.y;

int serverDisplayWidth = 720px; //this come from the server
int serverComponentWidth = 720px; //this come from the server
int smartphoneComponentWidth = (smartphoneDisplayWidth/serverDisplayWidth)*serverComponentWidth;
//ex: smartphoneComponentWidth = (1080/720)*720 = 1080; the component widht on the smartphone will be 1080px.
</code>```

If i set a smaller zoom I have this problem:

default:

small:

the windows components are to small:

The width in px doesn't change, it changes only the density:

small

```<code>DisplayMetrics{density=2.2250001, width=1080, height=1813, scaledDensity=2.2250001, xdpi=422.03, ydpi=424.069}
</code>```

default

```<code>DisplayMetrics{density=2.625,     width=1080, height=1794, scaledDensity=2.625,     xdpi=422.03, ydpi=424.069}
</code>```

large

```<code>DisplayMetrics{density=2.875,     width=1080, height=1782, scaledDensity=2.875,     xdpi=422.03, ydpi=424.069}
</code>```

larger

```<code>DisplayMetrics{density=3.125,     width=1080, height=1770, scaledDensity=3.125,      xdpi=422.03, ydpi=424.069}
</code>```

largest

```<code>DisplayMetrics{density=3.375,     width=1080, height=1758, scaledDensity=3.375,      xdpi=422.03, ydpi=424.069}
</code>```

答:
You should create views using dp value instead of px. When density changes (like in nugat settings) you see the result in second screen.

Probably you create layout like this:

```<code>int screenWidth = <value>;
LayoutParams lp = new LayoutParams(screenWidth, 200);
view.setlayoutparams(lp);
</code>```

You should use density:

```<code>float sampleDensity = 2f; // get from DisplayMetrics
int screenWidth = <value>;
LayoutParams lp = new LayoutParams((int) (screenWidth * sampleDensity), 200);
view.setlayoutparams(lp);
</code>```

Other reason is maybe you not update layouts after configuration change. Better solution is use MATCH_PARENT and WRAP_CONTENT in LayoutParams. Its more convenient and fast solution.

Body:
I have a problem with the calculation of the display size on Android N with a changed display zoom.

With Android N you can change the display zoom (check here)

but the display size (...getSize()) doesn't change if the user sets a zoom from android settings...

Any idea to solve it? Have I to use the size in px multiplied by scaledDensity to have a real display size?

My app dinamically creates windows and components calculating screen dimensions in px, the components are designed on a server.
Briefly I do a math proportion by the width set on the server and the width of the smartphone screen :

DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
   display.getRealSize(sizePoint);
}else{
   display.getSize(sizePoint);
}
int smartphoneDisplayWidth =  sizePoint.x;
int smartphoneDisplayHeight = sizePoint.y;

int serverDisplayWidth = 720px; //this come from the server
int serverComponentWidth = 720px; //this come from the server
int smartphoneComponentWidth = (smartphoneDisplayWidth/serverDisplayWidth)*serverComponentWidth;
//ex: smartphoneComponentWidth = (1080/720)*720 = 1080; the component widht on the smartphone will be 1080px.

If i set a smaller zoom I have this problem:

default:

small:

the windows components are to small:

The width in px doesn't change, it changes only the density:

small

DisplayMetrics{density=2.2250001, width=1080, height=1813, scaledDensity=2.2250001, xdpi=422.03, ydpi=424.069}

default

DisplayMetrics{density=2.625,     width=1080, height=1794, scaledDensity=2.625,     xdpi=422.03, ydpi=424.069}

large

DisplayMetrics{density=2.875,     width=1080, height=1782, scaledDensity=2.875,     xdpi=422.03, ydpi=424.069}

larger

DisplayMetrics{density=3.125,     width=1080, height=1770, scaledDensity=3.125,      xdpi=422.03, ydpi=424.069}

largest

DisplayMetrics{density=3.375,     width=1080, height=1758, scaledDensity=3.375,      xdpi=422.03, ydpi=424.069}

Body:
You should create views using dp value instead of px. When density changes (like in nugat settings) you see the result in second screen.

Probably you create layout like this:

int screenWidth = <value>;
LayoutParams lp = new LayoutParams(screenWidth, 200);
view.setlayoutparams(lp);

You should use density:

float sampleDensity = 2f; // get from DisplayMetrics
int screenWidth = <value>;
LayoutParams lp = new LayoutParams((int) (screenWidth * sampleDensity), 200);
view.setlayoutparams(lp);

Other reason is maybe you not update layouts after configuration change. Better solution is use MATCH_PARENT and WRAP_CONTENT in LayoutParams. Its more convenient and fast solution.


问:
Umbraco cannot start. A connection string is configured -running correctly in local but error on hosted one
My project is working perfectly on local host but I am trying to host it on iis and following error is showing

Steps which I have tried so far:

1.checked my connection string which is

```<code><connectionStrings>
    <remove name="umbracoDbDSN" />
    <add name="umbracoDbDSN" connectionString="Server=EIL-IT-360-39\SQLEXPRESS;Database=umbraco_16_6;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
</code>```

2.Using window authentication to login into my DB.

I have also refrered given sites but could not found desired solution:

Umbraco cannot start. A connection string is configured but the Umbraco cannot connect to the database

Umbraco cannot start after switching to local SQL database

答:
Thank you all for your help..my problem is now solved ..though it solved by adding a new user with some password in my ssms and then adding same in connection string as

```<code><add name="umbracoDbDSN" connectionString="..database=umbraco_16_6;user id=sa;password=*****" providerName="System.Data.SqlClient" />
</code>```

then,my umbraco password was not accepted at login screen[even though I haven't made any changes in that password]..for which I tried to update hashed password and other options..but none of those worked for me..
Then I have had a backup of my DB..which saved my project..and now I am able to login into my Umbraco site as well as hosted it successfully on my network.

Body:
My project is working perfectly on local host but I am trying to host it on iis and following error is showing

Steps which I have tried so far:

1.checked my connection string which is

<connectionStrings>
    <remove name="umbracoDbDSN" />
    <add name="umbracoDbDSN" connectionString="Server=EIL-IT-360-39\SQLEXPRESS;Database=umbraco_16_6;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>

2.Using window authentication to login into my DB.

I have also refrered given sites but could not found desired solution:

Umbraco cannot start. A connection string is configured but the Umbraco cannot connect to the database

Umbraco cannot start after switching to local SQL database

Body:
Thank you all for your help..my problem is now solved ..though it solved by adding a new user with some password in my ssms and then adding same in connection string as

<add name="umbracoDbDSN" connectionString="..database=umbraco_16_6;user id=sa;password=*****" providerName="System.Data.SqlClient" />

then,my umbraco password was not accepted at login screen[even though I haven't made any changes in that password]..for which I tried to update hashed password and other options..but none of those worked for me..
Then I have had a backup of my DB..which saved my project..and now I am able to login into my Umbraco site as well as hosted it successfully on my network.


问:
Query which can round to the previous 30minutes interval
I am querying database to get the results during 30minutes interval

1) Suppose if i am querying at 11:05am i should get the data from 10:30AM to 11:00AM
2) If I am querying at 11:35 I should get the data from 11:00AM TO 11;30AM.

In short I am looking for a query which can round to the previous 30minutes interval.

答:
```<code>with abcd as (select to_date('10:05','hh24:mi') test from dual
               union all select to_date('10:30','hh24:mi') from dual
               union all select to_date('10:31','hh24:mi') from dual
               )
select trunc(test,'HH') trunc_date_to_hour , NUMTODSINTERVAL( round((test - trunc(test,'HH'))*24)/2, 'hour') minuts_to_add,trunc(test,'HH')+  NUMTODSINTERVAL( round((test - trunc(test,'HH'))*24)/2, 'hour')  from abcd;
</code>```


问:
How to extract or export rules from SonarQube
Appriciate if I can get help for the below scenario. My issues to identify how to extract/export all java rules on SonarQube 4.5.7. I tried the below two API calls but I get a "The page you were looking for doesn't exist".

The sonarqube version I have shows 781 java rules my objective is to extract them to an excel or a csv file

[1]curl -X GET -v -u admin:admin http://localhost:9000/api/rules?language=java

[2]curl -X GET -v -u admin:admin http://localhost:9000/api/rules/search?languages=java >> java.json

The second option seems to generate an output but not all 781 rules are extracted
thanks,shavantha

答:
http://localhost:9000/api/rules/search?languages=java

the url parameter is languages rather language


问:
I am little bit confused about escaping closure
I am new to swift and trying to learn when I saw apple doc in it there is a definition about escaping closure like:

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

@ other hand I saw a blog where blogger explained about completion handler like:

There are times you put a closure as one of the parameters, but you only want to execute the closure after the function returns. For example, what if you want to print “Hello, world” only after you’ve completely switched to the next ViewController?

So I want to know if completion handler and escaping closure are same or what?

答:
Completion handlers are one example where escaping closures are passed, but they are not the only one.

In fact, the concept of a completion handler works on a different level than the concept of an escaping closure.

Escaping Closure

The closure is stored, and may be invoked at some time in the future.

This is in contrast to a non-escaping closure, where the closure gets called immediately or not at all.

The difference between escaping and non-escaping closure is important for memory management. For non-escaping closures, the compiler knows that any resources used by the closure aren't used anymore after the call.

Completion Handler

A completion handler is a closure that gets called once an operation is finished.

Operations that use completion handlers often are long-running and work on different threads. While such an operation is running, your program can continue with its control flow, thereby making the program more responsive. For example, if you call URLSession.downloadTask(withResumeData:completionHandler:), you will schedule a new download task in URLSession. Downloading may take a while, depending on your connectivity status and other factors, and only once the download was finished your completion handler gets called.

The way such operations are implemented is usually, that they store the completion handler somewhere, perform the operation, and then call the completion handler. Therefore, completion handlers are usually escaping closures.


问:
how to pass date format from controller to directive using angularjs
how to pass variable "$scope.dateformat" to "format" in
           directive.Please
           let me know if any examples are available or suggested.
           Please suggest me more examples on this.</p>

```<code>     $scope.dateformat ="yyyy-mm-dd";

      menuModule.directive("datepicker", function(){
      return {
        restrict: "EAC",
        require: "ngModel",
        scope: {
            "ngModel": "="
        },
        link: function(scope, elem, attr){
            $(elem).datepicker({
               format: "yyyy-mm-dd", // Above $scope.dateformat should be
                                             //   called here
            }).on("changeDate", function(e){
                return scope.$apply(function(){
                    console.log(attr);
                    return scope.ngModel = e.format();
                });
            });

            return scope.$watch("ngModel", function(newValue){
                $(elem).datepicker("update", newValue);
            });
             }
          };
         });
</code>```

答:
Directive

```<code>    scope: {
        "format": "="
    },
    link: function(scope, elem, attr){
        $(elem).datepicker({
           format: scope.format
        })
    }
</code>```

HTML

```<code>     <datepicker format="dateformat"></datepicker>
</code>```

Body:
how to pass variable "$scope.dateformat" to "format" in
           directive.Please
           let me know if any examples are available or suggested.
           Please suggest me more examples on this.

     $scope.dateformat ="yyyy-mm-dd";

      menuModule.directive("datepicker", function(){
      return {
        restrict: "EAC",
        require: "ngModel",
        scope: {
            "ngModel": "="
        },
        link: function(scope, elem, attr){
            $(elem).datepicker({
               format: "yyyy-mm-dd", // Above $scope.dateformat should be
                                             //   called here
            }).on("changeDate", function(e){
                return scope.$apply(function(){
                    console.log(attr);
                    return scope.ngModel = e.format();
                });
            });

            return scope.$watch("ngModel", function(newValue){
                $(elem).datepicker("update", newValue);
            });
             }
          };
         });

Body:
Directive

    scope: {
        "format": "="
    },
    link: function(scope, elem, attr){
        $(elem).datepicker({
           format: scope.format
        })
    }

HTML

     <datepicker format="dateformat"></datepicker>


问:
Generate sequence of strings from array
I have an alphabet array:

```<code>$ga = array_merge(range('A', 'Z'), range(0,9));
</code>```

How can I generate next strings:

```<code>AAAA, AAAB... AAAZ, AAA0... AAA9, AABA, AA9A... ABAA... 9999
</code>```

Thanks!

答:
This probably is the easiest approach:

```<code><?php
$alphabeth = array_merge(range('A', 'Z'), range(0,9));
$character = [];
foreach ($alphabeth as $character[0]) {
  foreach ($alphabeth as $character[1]) {
    foreach ($alphabeth as $character[2]) {
      foreach ($alphabeth as $character[3]) {
        $catalog[] = vsprintf('%s%s%s%s', $character);
      }
    }
  }
}
print_r($catalog);
</code>```

The output obviously is:

```<code>Array
(
    [0] => AAAA
    [1] => AAAB
    [2] => AAAC
    [3] => AAAD
    .....
    [1679613] => 9997
    [1679614] => 9998
    [1679615] => 9999
)
</code>```

UPDATE:

You mention in the comments below that you need to fill these strings into a file, if I got you right. If so, then this would be an example for a sequential processing which dramatically reduces the scripts memory footprint, as also mentioned in the comments:

```<code><?php
$alphabeth = array_merge(range('A', 'Z'), range(0,9));
$handle = fopen('/home/arkascha/catalog.list', 'w');
foreach ($alphabeth as $character[0]) {
  foreach ($alphabeth as $character[1]) {
    foreach ($alphabeth as $character[2]) {
      foreach ($alphabeth as $character[3]) {
        fwrite($handle, vsprintf("%s%s%s%s\n", $character));
      }
    }
  }
}
fclose($handle);
</code>```

Title: Generate sequence of strings from array

Body:
I have an alphabet array:

$ga = array_merge(range('A', 'Z'), range(0,9));

How can I generate next strings:

AAAA, AAAB... AAAZ, AAA0... AAA9, AABA, AA9A... ABAA... 9999

Thanks!

Body:
This probably is the easiest approach:

<?php
$alphabeth = array_merge(range('A', 'Z'), range(0,9));
$character = [];
foreach ($alphabeth as $character[0]) {
  foreach ($alphabeth as $character[1]) {
    foreach ($alphabeth as $character[2]) {
      foreach ($alphabeth as $character[3]) {
        $catalog[] = vsprintf('%s%s%s%s', $character);
      }
    }
  }
}
print_r($catalog);

The output obviously is:

Array
(
    [0] => AAAA
    [1] => AAAB
    [2] => AAAC
    [3] => AAAD
    .....
    [1679613] => 9997
    [1679614] => 9998
    [1679615] => 9999
)

UPDATE:

You mention in the comments below that you need to fill these strings into a file, if I got you right. If so, then this would be an example for a sequential processing which dramatically reduces the scripts memory footprint, as also mentioned in the comments:

<?php
$alphabeth = array_merge(range('A', 'Z'), range(0,9));
$handle = fopen('/home/arkascha/catalog.list', 'w');
foreach ($alphabeth as $character[0]) {
  foreach ($alphabeth as $character[1]) {
    foreach ($alphabeth as $character[2]) {
      foreach ($alphabeth as $character[3]) {
        fwrite($handle, vsprintf("%s%s%s%s\n", $character));
      }
    }
  }
}
fclose($handle);


问:
Java String quote delimiter
Is there any way in Java to use a special delimiter at the start and the end of a String to avoid having to backslash all of the quotes within that String?

i.e. not have to do this:

```<code>String s = "Quote marks like this \" are just the best, here are a few more \" \" \""
</code>```

答:
No - there's nothing like C#'s verbatim string literals or Groovy's slashy strings, for example.

On the other hand, it's the kind of feature which may be included in the future. It's not like it would require any fundamental changes in the type system. I'd be hugely surprised for it to make it into Java 7 this late in the day though, and I haven't seen any suggestions that it'll be in Java 8... so you're in for a long wait :(

Title: Java String quote delimiter

Body:
Is there any way in Java to use a special delimiter at the start and the end of a String to avoid having to backslash all of the quotes within that String?

i.e. not have to do this:

String s = "Quote marks like this \" are just the best, here are a few more \" \" \""