问:
I can connect digital ocean droplet via SSH connected in home network but not in work network
Scenario...

WiFi Network home = Can connect with my Digital Ocean servers fine via SSH;
WiFi Network work = Can't connect with my Digital Ocean servers via SSH;

WiFi Network work SSH debug:

```<code>OpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to xxx.xxx.xxx.xxx [xxx.xxx.xxx.xxx] port 22.
debug1: connect to address xxx.xxx.xxx.xxx port 22: Connection timed out
ssh: connect to host xxx.xxx.xxx.xxx port 22: Connection timed out
</code>```

Anyone?

答:
Try to  check with nc

```<code>nc -zvw4 your_host 22
</code>```

If not open - probably 22 port not allowed in your network, you can ask your network administrator about it

on your server make forward from 443 to 22 via iptables, for example:

```<code>iptables -t nat -I PREROUTING -i eth0 -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 22
</code>```

Body:
Scenario...

WiFi Network home = Can connect with my Digital Ocean servers fine via SSH;
WiFi Network work = Can't connect with my Digital Ocean servers via SSH;

WiFi Network work SSH debug:

OpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to xxx.xxx.xxx.xxx [xxx.xxx.xxx.xxx] port 22.
debug1: connect to address xxx.xxx.xxx.xxx port 22: Connection timed out
ssh: connect to host xxx.xxx.xxx.xxx port 22: Connection timed out

Anyone?

Body:
Try to  check with nc

nc -zvw4 your_host 22

If not open - probably 22 port not allowed in your network, you can ask your network administrator about it

on your server make forward from 443 to 22 via iptables, for example:

iptables -t nat -I PREROUTING -i eth0 -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 22


来源: stackexchange

问:
.htaccess redirect all calls to forum to specific url
I'm trying to add to our .htaccess file so all calls to domain.com/forum go to our new domain.com/site3/forum location.    Note that I do not want to use the actual url, but all calls to that original folder (regardless of url) to go to exactly domain.com/site3/forum.   This would include both secure and insecure version and with or without the www.
Your help would be greatly appreciated.</p>

答:
You can use:
Without change for http/https and www

```<code>RewriteEngine on
RewriteRule ^forum(/|$) /site3/forum [R=301,L]
</code>```

Or all with http and without www:

```<code>RewriteRule ^forum(/|$) http://example.com/site3/forum [R=301,L]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use:
Without change for http/https and www

RewriteEngine on
RewriteRule ^forum(/|$) /site3/forum [R=301,L]

Or all with http and without www:

RewriteRule ^forum(/|$) http://example.com/site3/forum [R=301,L]


问:
A script to toggle WiFi in MacOS
I'm trying to write a script that toggles WiFi on or off.

I'm having trouble with the "if" statement. I'm starting with a simple script that should tell you if Wifi is on or off. It doesn't work as written. I get "Wifi is off" no matter what the WiFi status is

```<code>#!/bin/sh
STATUS=`networksetup -getairportpower en0`
if $STATUS == On
then
   echo "Wifi is on"
else
    echo "Wifi is off"
fi
</code>```

答:
Thou shall use [ expr ] to evaluate the logical expression. So, the condition would be like:

```<code>if [ $STATUS == On ]
</code>```

If you need to evaluate some more elaborated expression, you may use [[ expr ]]. Meaning of both is explained in this section of bash manual.

Title: A script to toggle WiFi in MacOS

Body:
I'm trying to write a script that toggles WiFi on or off.

I'm having trouble with the "if" statement. I'm starting with a simple script that should tell you if Wifi is on or off. It doesn't work as written. I get "Wifi is off" no matter what the WiFi status is

#!/bin/sh
STATUS=`networksetup -getairportpower en0`
if $STATUS == On
then
   echo "Wifi is on"
else
    echo "Wifi is off"
fi

Body:
Thou shall use [ expr ] to evaluate the logical expression. So, the condition would be like:

if [ $STATUS == On ]

If you need to evaluate some more elaborated expression, you may use [[ expr ]]. Meaning of both is explained in this section of bash manual.


问:
Centering multiple labels with autolayout
Is it possible to center these countdown labels using autolayout?

I have a centered view (as pictured in dark blue) with four labels: minuteValue, minuteUnit, secondValue and secondUnit.

When the countdown timer is under 60 seconds the minute labels are hidden. Is it possible to center the timer whatever state it is in; i.e. whether I have 2 or 4 labels?

If no one knows of an autolayout solution I am happy to code it in, but my preference is to do achieve this using autolayout if possible.

答:
If I understand you correctly, you want them always be centered, whether two or four labels. In this case, I would add one contentView for them. So, you receive something like this:

YourBlueView -> ContainerView -> FourLabels

Next, center your containerView in YourBlueView with:

```<code>yourBlueView.addConstraint(NSLayoutConstraint(item: yourBlueView, attribute: .centerY, relatedBy: .equal, toItem: containerView, attribute: .centerY, multiplier: 1, constant: 0))
yourBlueView.addConstraint(NSLayoutConstraint(item: yourBlueView, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1, constant: 0))
</code>```

Final step, add constraints to your labels in containerView, something like

```<code>containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[firstLabel]|", metrics: nil, views: ["firstLabel": firstLabel]))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[firstLabel][secondLabel][thirdLabel][fourthLabel]|",options: [.alignAllCenterY], metrics: nil, views: ["firstLabel": firstLabel,"secondLabel": secondLabel,"thirdLabel": thirdLabel,"fourthLabel": fourthLabel]))
</code>```

Now, when you set your labels width to 0, they will remain in the center.

Another solution, more clear, but requires UIStackView. Put all labels into it, as you're using storyboard, it can be done with button Embed In Stack, under your storyboard window, and center this stack view in your blue view. Job is done

Body:
If I understand you correctly, you want them always be centered, whether two or four labels. In this case, I would add one contentView for them. So, you receive something like this:

YourBlueView -> ContainerView -> FourLabels

Next, center your containerView in YourBlueView with:

yourBlueView.addConstraint(NSLayoutConstraint(item: yourBlueView, attribute: .centerY, relatedBy: .equal, toItem: containerView, attribute: .centerY, multiplier: 1, constant: 0))
yourBlueView.addConstraint(NSLayoutConstraint(item: yourBlueView, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1, constant: 0))

Final step, add constraints to your labels in containerView, something like

containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[firstLabel]|", metrics: nil, views: ["firstLabel": firstLabel]))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[firstLabel][secondLabel][thirdLabel][fourthLabel]|",options: [.alignAllCenterY], metrics: nil, views: ["firstLabel": firstLabel,"secondLabel": secondLabel,"thirdLabel": thirdLabel,"fourthLabel": fourthLabel]))

Now, when you set your labels width to 0, they will remain in the center.

Another solution, more clear, but requires UIStackView. Put all labels into it, as you're using storyboard, it can be done with button Embed In Stack, under your storyboard window, and center this stack view in your blue view. Job is done


问:
Apps Scripts OAuth2 authorization using gapi from inside HtmlService
I'm trying to be OAuth2-authorized by using the gapi library from inside an HtmlService project. I've got my CLIENT_ID from the console and I've set up the "Authorized Javascript Origins" with all of what I could think about like "https://script.google.com", "https://script.googleusercontent.com", etc, but I always end with an "origin mismatch" error.

This is the code I'm using from inside the html javascript code.

```<code>function checkAuth() {
  gapi.auth.authorize({
    'client_id': CLIENT_ID,
    'scope': SCOPES,
    'immediate': false
  }, handleAuthResult);
}
</code>```

What am I doing wrong?

Thanks

答:
To get the origin you need launch your webapp. Right click and click Inspect.  This should open Devtools. Click on the Elements tab. Look for the iframe with the id="sandboxFrame". The source the that iframe in your webapp origin. It will look like:

When you add it to your credentials just add the domain part leaving off the endpoint.

https://n-rilyfaex6q3..iimkn7ufgvlphhi2..l3l73y-0lu-script.googleusercontent.com

Body:
I'm trying to be OAuth2-authorized by using the gapi library from inside an HtmlService project. I've got my CLIENT_ID from the console and I've set up the "Authorized Javascript Origins" with all of what I could think about like "https://script.google.com", "https://script.googleusercontent.com", etc, but I always end with an "origin mismatch" error.

This is the code I'm using from inside the html javascript code.

function checkAuth() {
  gapi.auth.authorize({
    'client_id': CLIENT_ID,
    'scope': SCOPES,
    'immediate': false
  }, handleAuthResult);
}

What am I doing wrong?

Thanks


问:
Using wstring and wcout doesn't get the expected output
I'm writing a program in C++ which have to handle unicode characters.
The main problem is I use algorithms where I need to parse my s/wstrings char by char :

```<code>std::wstring word = L"Héllo"
for (auto &e : word)
// doing something with e
</code>```

But if I run this :

```<code>std::wstring word = L"Héllo"
for (auto &e : word)
    std::wcout << e << std::endl;
</code>```

I get this output :

```<code>H
?
l
l
o
</code>```

Am I doing something wrong ?

Do note that word prints properly when I use std::wcout << word;.

EDIT FOR  @Ben Voigt

Here is the out with std::wcout << std::hex << std::setw(4) << (int)e << L" " << e << L'\n';

:

```<code>  48 H
  e9 �
  6c l
  6c l
  6f o
</code>```

答:
To print the characters as you intend, try the following:

```<code>#include <string>
#include <iostream>
#include <fcntl.h>
#include <io.h>
int _tmain(int argc, _TCHAR* argv[])
{
    std::wstring word = L"Héllo";
    _setmode(_fileno(stdout), _O_U16TEXT);
    for (auto &e : word)
        std::wcout << e << std::endl;
    return 0;
}
</code>```

More detailed description in this post: Why are certain Unicode characters causing std::wcout to fail in a console app?

Body:
I'm writing a program in C++ which have to handle unicode characters.
The main problem is I use algorithms where I need to parse my s/wstrings char by char :

std::wstring word = L"Héllo"
for (auto &e : word)
// doing something with e

But if I run this :

std::wstring word = L"Héllo"
for (auto &e : word)
    std::wcout << e << std::endl;

I get this output :

H
?
l
l
o

Am I doing something wrong ?

Do note that word prints properly when I use std::wcout << word;.

EDIT FOR  @Ben Voigt

Here is the out with std::wcout << std::hex << std::setw(4) << (int)e << L" " << e << L'\n';

:

  48 H
  e9 �
  6c l
  6c l
  6f o

Body:
To print the characters as you intend, try the following:

#include <string>
#include <iostream>
#include <fcntl.h>
#include <io.h>
int _tmain(int argc, _TCHAR* argv[])
{
    std::wstring word = L"Héllo";
    _setmode(_fileno(stdout), _O_U16TEXT);
    for (auto &e : word)
        std::wcout << e << std::endl;
    return 0;
}

More detailed description in this post: Why are certain Unicode characters causing std::wcout to fail in a console app?


问:
Google map clustering is not working for small count of cordinates
I am using the Google Map Clustering demo application example to play with it. As per in the example offset are following:

```<code>private void readItems() throws JSONException {
    InputStream inputStream = getResources().openRawResource(R.raw.radar_search);
    List<MyItem> items = new MyItemReader().read(inputStream);
    for (int i = 0; i < 5; i++) {
        double offset = i / 60d;
        for (MyItem item : items) {
            LatLng position = item.getPosition();
            double lat = position.latitude + offset;
            double lng = position.longitude + offset;
            MyItem offsetItem = new MyItem(lat, lng);
            mClusterManager.addItem(offsetItem);
        }
    }
}
</code>```

Clustering is working perfectly for large numbers of coordinates (=>5). To understand let's take two scenarios:

First scenario
I am loading two coordinates through following data file:

```<code>[
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 }
]
</code>```

As we can see in above data file that count of { "lat" : 28.5102148, "lng" : 77.411671 } is 9 and count of { "lat" : 28.5092163, "lng" : 77.4135367 }, is 5. Screenshot of the emulator:

Second scenario
I am loading two coordinates through following data file:

```<code>[
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 }
]
</code>```

As we can see in above data file that count of { "lat" : 28.5102148, "lng" : 77.411671 } is 9 and count of { "lat" : 28.5092163, "lng" : 77.4135367 }, is 4. Screenshot of the emulator:

So, the problem is whenever I am passing less than 5 coordinators for the same Lat,Lng. Google map wont's showing the cluster. It supposed to be show as 9 and 4.

I tried to follow the documentation but nothing is heling me out. What am I doing wrong here?

Thanks for your help.

答:
After so many attempts. I looked at the Cluster library code and found:

```<code>private int mClusterSize = 4;
</code>```

Change it to as per your convenience.

Body:
I am using the Google Map Clustering demo application example to play with it. As per in the example offset are following:

private void readItems() throws JSONException {
    InputStream inputStream = getResources().openRawResource(R.raw.radar_search);
    List<MyItem> items = new MyItemReader().read(inputStream);
    for (int i = 0; i < 5; i++) {
        double offset = i / 60d;
        for (MyItem item : items) {
            LatLng position = item.getPosition();
            double lat = position.latitude + offset;
            double lng = position.longitude + offset;
            MyItem offsetItem = new MyItem(lat, lng);
            mClusterManager.addItem(offsetItem);
        }
    }
}

Clustering is working perfectly for large numbers of coordinates (=>5). To understand let's take two scenarios:

First scenario
I am loading two coordinates through following data file:

[
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 }
]

As we can see in above data file that count of { "lat" : 28.5102148, "lng" : 77.411671 } is 9 and count of { "lat" : 28.5092163, "lng" : 77.4135367 }, is 5. Screenshot of the emulator:

Second scenario
I am loading two coordinates through following data file:

[
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5092163, "lng" : 77.4135367 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 },
 { "lat" : 28.5102148, "lng" : 77.411671 }
]

As we can see in above data file that count of { "lat" : 28.5102148, "lng" : 77.411671 } is 9 and count of { "lat" : 28.5092163, "lng" : 77.4135367 }, is 4. Screenshot of the emulator:

So, the problem is whenever I am passing less than 5 coordinators for the same Lat,Lng. Google map wont's showing the cluster. It supposed to be show as 9 and 4.

I tried to follow the documentation but nothing is heling me out. What am I doing wrong here?

Thanks for your help.

Body:
After so many attempts. I looked at the Cluster library code and found:

private int mClusterSize = 4;

Change it to as per your convenience.


问:
How can I make a random choice according to probabilities stored in a list (weighted random distribution)?
Given a list of probabilities like:

```<code>P = [0.10, 0.25, 0.60, 0.05]
</code>```

(I can ensure that the sum of all the variables in P is always 1)

How can I write a function that randomly returns a valid index, according to the values in the list? In other words, for this specific input, I want it to return 0 10% of the time, 1 25% of the time, 2 60% of the time and 3 the remainind 5% of the time.

答:
Hmm interesting, how about...

Generate a number between 0 and 1.

Walk the list substracting the probability of each item from your number.

Pick the item that, after substraction, took your number down to 0 or below.

That's simple, O(n) and should work :)

ContentLicense: CC BY-SA 4.0

Body:
Given a list of probabilities like:

P = [0.10, 0.25, 0.60, 0.05]

(I can ensure that the sum of all the variables in P is always 1)

How can I write a function that randomly returns a valid index, according to the values in the list? In other words, for this specific input, I want it to return 0 10% of the time, 1 25% of the time, 2 60% of the time and 3 the remainind 5% of the time.

ContentLicense: CC BY-SA 2.5


问:
Join two tables with same ID and merge ID columns
This is probably a pretty simple question, but most of the searches I do have to do with merging rows (not merging columns) or concatenating them.

I want to join two tables on an ID column, but I only want it to return a single ID column.

Example:

Table 1:

```<code>ID|Data1|Data2
</code>```

Table2:

```<code>ID|Data3|Data4
</code>```

I want it to return:

```<code>ID|Data1|Data2|Data3|Data4
</code>```

EDIT:

I realize I can specify every column, but there are actually closer to 50 columns that I'm bringing over and I would prefer not to have to specify every single one. Is there a way to do this without specifying each column to bring over from the query?

I believe natural join is what I need, but see this error I'm getting:

```<code>SELECT *
FROM allqachecklists t1
WHERE t1.IsIncorrect=1
NATURAL JOIN (SELECT QAID, PMC, SiteName, Submitter, QAer FROM qabin.allqas) t2
</code>```

1 errors were found during analysis.

Unrecognized keyword. (near "NATURAL" at position 59)

答:
Sound like a pretty straight forward inner join:</p>

```<code>select A.ID, data1, data2, data3, data4 from A
inner join B ON A.ID = B.ID
</code>```

Body:
This is probably a pretty simple question, but most of the searches I do have to do with merging rows (not merging columns) or concatenating them.

I want to join two tables on an ID column, but I only want it to return a single ID column.

Example:

Table 1:

ID|Data1|Data2

Table2:

ID|Data3|Data4

I want it to return:

ID|Data1|Data2|Data3|Data4

EDIT:

I realize I can specify every column, but there are actually closer to 50 columns that I'm bringing over and I would prefer not to have to specify every single one. Is there a way to do this without specifying each column to bring over from the query?

I believe natural join is what I need, but see this error I'm getting:

SELECT *
FROM allqachecklists t1
WHERE t1.IsIncorrect=1
NATURAL JOIN (SELECT QAID, PMC, SiteName, Submitter, QAer FROM qabin.allqas) t2

1 errors were found during analysis.

Unrecognized keyword. (near "NATURAL" at position 59)

Body:
Sound like a pretty straight forward inner join:

select A.ID, data1, data2, data3, data4 from A
inner join B ON A.ID = B.ID


问:
Long to wide with automatic dummy creation and multiple value columns
I'm sitting in front of a dataframe that looks like this:

```<code>      country year Indicator         a         b        c
48996      US 2003      var1        NA        NA       NA
16953      FR 1988      var2        NA 10664.920       NA
22973      FR 1943      var3        NA  5774.334       NA
8760       CN 1995      var4  8804.565        NA 12750.31
47795      US 2012      var5        NA        NA       NA
30033      GB 1969      var6        NA 29631.362       NA
25796      FR 1921      var7        NA 14004.520       NA
39534      NL 1941      var8        NA        NA       NA
42255      NZ 1969      var8        NA        NA       NA
7249       CN 1995      var9 50635.862        NA 75260.56
</code>```

What I want to do is basically a long to wide transformation with Indicator as key variable. I would usually use spread() from the tidyr package. However, spread() unfortunately does not accept multiple value columns (in this case a, b and c) and it does not fully do what I want to achieve:

Make the entries of Indicator the new columns

Keep the Country / Year combinations as rows

Creat a UNIQUE row for every old value from a, b and c

Create a Dummy Variable for every "old" value column name (i.e. a,
b, c)

So in the end, the Chinese observations of my example should become

```<code>country year var1 [...] var4       [...]   var9       dummy.a dummy.b dummy.c
CN      1995 NA         8804.565           50635.862        1       0       0
CN      1995 NA         12750.31           75260.56         0       0       1
</code>```

As my original dataframe is 58.162x119, I would appreciate something that does not include a lot of manual work :-)

I hope I was clear in what I want to achieve. Thanks for your help!

The above mentioned dataframe can be reproduced using the following code:

```<code>structure(list(country = c("US", "FR", "FR", "CN", "US", "GB",
"FR", "NL", "NZ", "CN"), year = c(2003L, 1988L, 1943L, 1995L,
2012L, 1969L, 1921L, 1941L, 1969L, 1995L), Indicator = structure(c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 8L, 9L), .Label = c("var1", "var2",
"var3", "var4", "var5", "var6", "var7", "var8", "var9", "var10",
"var11", "var12", "var13", "var14", "var15", "var16", "var17",
"var18"), class = "factor"), a = c(NA, NA, NA, 8804.56480733,
NA, NA, NA, NA, NA, 50635.8621327), b = c(NA, 10664.9199219,
5774.33398438, NA, NA, 29631.3618614, 14004.5195312, NA, NA,
NA), c = c(NA, NA, NA, 12750.3056855, NA, NA, NA, NA, NA, 75260.555946
)), .Names = c("country", "year", "Indicator", "a", "b", "c"), row.names = c(48996L,
16953L, 22973L, 8760L, 47795L, 30033L, 25796L, 39534L, 42255L,
7249L), class = "data.frame")
</code>```

答:
dt would be your original data. dt2 is the final output.

```<code>dt2 <- dt %>%
  gather(Parameter, Value, a:c) %>%
  spread(Indicator, Value) %>%
  mutate(Data = ifelse(rowSums(is.na(.[, paste0("var", 1:9)])) != 9, 1, 0)) %>%
  filter(Data != 0) %>%
  spread(Parameter, Data, fill = 0) %>%
  rename(dummy.a = a, dummy.b = b, dummy.c = c)
</code>```

Body:
I'm sitting in front of a dataframe that looks like this:

      country year Indicator         a         b        c
48996      US 2003      var1        NA        NA       NA
16953      FR 1988      var2        NA 10664.920       NA
22973      FR 1943      var3        NA  5774.334       NA
8760       CN 1995      var4  8804.565        NA 12750.31
47795      US 2012      var5        NA        NA       NA
30033      GB 1969      var6        NA 29631.362       NA
25796      FR 1921      var7        NA 14004.520       NA
39534      NL 1941      var8        NA        NA       NA
42255      NZ 1969      var8        NA        NA       NA
7249       CN 1995      var9 50635.862        NA 75260.56

What I want to do is basically a long to wide transformation with Indicator as key variable. I would usually use spread() from the tidyr package. However, spread() unfortunately does not accept multiple value columns (in this case a, b and c) and it does not fully do what I want to achieve:

Make the entries of Indicator the new columns

Keep the Country / Year combinations as rows

Creat a UNIQUE row for every old value from a, b and c

Create a Dummy Variable for every "old" value column name (i.e. a,
b, c)

So in the end, the Chinese observations of my example should become

country year var1 [...] var4       [...]   var9       dummy.a dummy.b dummy.c
CN      1995 NA         8804.565           50635.862        1       0       0
CN      1995 NA         12750.31           75260.56         0       0       1

As my original dataframe is 58.162x119, I would appreciate something that does not include a lot of manual work :-)

I hope I was clear in what I want to achieve. Thanks for your help!

The above mentioned dataframe can be reproduced using the following code:

structure(list(country = c("US", "FR", "FR", "CN", "US", "GB",
"FR", "NL", "NZ", "CN"), year = c(2003L, 1988L, 1943L, 1995L,
2012L, 1969L, 1921L, 1941L, 1969L, 1995L), Indicator = structure(c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 8L, 9L), .Label = c("var1", "var2",
"var3", "var4", "var5", "var6", "var7", "var8", "var9", "var10",
"var11", "var12", "var13", "var14", "var15", "var16", "var17",
"var18"), class = "factor"), a = c(NA, NA, NA, 8804.56480733,
NA, NA, NA, NA, NA, 50635.8621327), b = c(NA, 10664.9199219,
5774.33398438, NA, NA, 29631.3618614, 14004.5195312, NA, NA,
NA), c = c(NA, NA, NA, 12750.3056855, NA, NA, NA, NA, NA, 75260.555946
)), .Names = c("country", "year", "Indicator", "a", "b", "c"), row.names = c(48996L,
16953L, 22973L, 8760L, 47795L, 30033L, 25796L, 39534L, 42255L,
7249L), class = "data.frame")

Body:
dt would be your original data. dt2 is the final output.

dt2 <- dt %>%
  gather(Parameter, Value, a:c) %>%
  spread(Indicator, Value) %>%
  mutate(Data = ifelse(rowSums(is.na(.[, paste0("var", 1:9)])) != 9, 1, 0)) %>%
  filter(Data != 0) %>%
  spread(Parameter, Data, fill = 0) %>%
  rename(dummy.a = a, dummy.b = b, dummy.c = c)


问:
Ionic framework version mission
When I typed ionic-info, I was missing Ionic Framework version but everything else was showing. Does anybody know why this is so.

Related or not, apps built on a teammates machine worked well (he had the Ionic Framework Version) but when the same app was built on mine, it showed a white screen

答:
ionic info should give system info regarding environment and cli
 $ ionic info

Your system information:

Cordova CLI: 5.1.1

Gulp version:  CLI version 3.9.0

Gulp local:   Local version 3.9.0

Ionic CLI Version: 1.6.1

Ionic App Lib Version: 0.3.3

ios-deploy version: 1.7.0

ios-sim version: 3.1.1

OS: Mac OS X Yosemite

Node Version: v0.12.5

Xcode version: Xcode 6.4 Build version 6E35b

But  although ionic framework version doesn't affect the running  of application in most cases it must be plugin issues or  read this article

How To Debug The White Screen Of Death In Your Ionic App
https://gonehybrid.com/how-to-debug-the-white-screen-of-death-in-your-ionic-app/

But can you check what are you getting any errors in your console?

You can debug in chrome or in safari

Title: Ionic framework version mission


问:
Dropbox delegate methods are not calling first time
This is i have written in viewDidLoad.

```<code> if DBSession.shared().isLinked() {
        print("already linked")

        initDropboxRestClient()
    }
    else
    {
        print("connecting2")
        DBSession.shared().link(from: self)
        initDropboxRestClient()
    }
</code>```

and function initDropboxRestClient() is written below.

```<code>func initDropboxRestClient() {
    dbRestClient = DBRestClient(session: DBSession.shared())
    dbRestClient.delegate = self
    dbRestClient.loadMetadata("/")
</code>```

}

The problem is i have two view controllers for displaying dropbox file names, the first view controller is calling the delegate methods and displaying filename and folder names perfectly. But the second one isn't.

In the second view controller,
I observed that if i scroll my tableview in second view controller up and down then the delegate methods get called immediately and once it is linked next time the methods are called immediately.

So for the first time delegate methods are not getting called in my second dropbox view controller thats my problem here. Thanks in advance.

The restClient delegate methods are as follows.

```<code>func restClient(_ client: DBRestClient!, loadedMetadata metadata: DBMetadata!) {
    for file in metadata.contents
    {
        dbMetadataArray.append(file as! DBMetadata)
        fileNamesArray.append((file as AnyObject).filename)
    }
    tableView.reloadData()
    self.myActivityIndicator.stopAnimating()
    self.myActivityIndicator.hidesWhenStopped = true

}

func restClient(_ client: DBRestClient!, loadMetadataFailedWithError error: Error!) {
    print("in loadMetadataFailedWithError method in dropbox email view controller")
    print("Error dscription = %@",[error.localizedDescription])
    let alert = UIAlertController(title: "Go Back.", message: "Try Once Again", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
    self.myActivityIndicator.stopAnimating()
    self.myActivityIndicator.hidesWhenStopped = true
    tableView.reloadData()
}
</code>```

答:
There are a few things that might cause your delegate methods to not be called:

Your rest client is nil or is being released (e.g., by ARC) prematurely.

You're making the call in a background thread that doesn't have a run loop.

Your delegate method that should be called back has a typo in it. Unfortunately the SDK doesn't warn you if it can't find a delegate method to call; it just completes without telling anyone.

Also, note that the SDK you're using uses API v1, which is deprecated and being retired soon anyway:

https://blogs.dropbox.com/developers/2016/06/api-v1-deprecated/

You should switch to API v2:

https://www.dropbox.com/developers/documentation

Body:
This is i have written in viewDidLoad.

 if DBSession.shared().isLinked() {
        print("already linked")

        initDropboxRestClient()
    }
    else
    {
        print("connecting2")
        DBSession.shared().link(from: self)
        initDropboxRestClient()
    }

and function initDropboxRestClient() is written below.

func initDropboxRestClient() {
    dbRestClient = DBRestClient(session: DBSession.shared())
    dbRestClient.delegate = self
    dbRestClient.loadMetadata("/")

}

The problem is i have two view controllers for displaying dropbox file names, the first view controller is calling the delegate methods and displaying filename and folder names perfectly. But the second one isn't.

In the second view controller,
I observed that if i scroll my tableview in second view controller up and down then the delegate methods get called immediately and once it is linked next time the methods are called immediately.

So for the first time delegate methods are not getting called in my second dropbox view controller thats my problem here. Thanks in advance.

The restClient delegate methods are as follows.

func restClient(_ client: DBRestClient!, loadedMetadata metadata: DBMetadata!) {
    for file in metadata.contents
    {
        dbMetadataArray.append(file as! DBMetadata)
        fileNamesArray.append((file as AnyObject).filename)
    }
    tableView.reloadData()
    self.myActivityIndicator.stopAnimating()
    self.myActivityIndicator.hidesWhenStopped = true

}

func restClient(_ client: DBRestClient!, loadMetadataFailedWithError error: Error!) {
    print("in loadMetadataFailedWithError method in dropbox email view controller")
    print("Error dscription = %@",[error.localizedDescription])
    let alert = UIAlertController(title: "Go Back.", message: "Try Once Again", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
    self.myActivityIndicator.stopAnimating()
    self.myActivityIndicator.hidesWhenStopped = true
    tableView.reloadData()
}


问:
How to convert SQL Query result to PANDAS Data Structure?
Any help on this problem will be greatly appreciated.

So basically I want to run a query to my SQL database and store the returned data as Pandas data structure.

I have attached code for query.

I am reading the documentation on Pandas, but I have problem to identify the return type of my query.

I tried to print the query result, but it doesn't give any useful information.

Thanks!!!!

from sqlalchemy import create_engine

engine2 = create_engine('mysql://THE DATABASE I AM ACCESSING')
connection2 = engine2.connect()
dataid = 1022
resoverall = connection2.execute("
    SELECT
       sum(BLABLA) AS BLA,
       sum(BLABLABLA2) AS BLABLABLA2,
       sum(SOME_INT) AS SOME_INT,
       sum(SOME_INT2) AS SOME_INT2,
       100*sum(SOME_INT2)/sum(SOME_INT) AS ctr,
       sum(SOME_INT2)/sum(SOME_INT) AS cpc
    FROM daily_report_cooked
    WHERE campaign_id = '%s'",
    %dataid
)
```

So I sort of want to understand what's the format/datatype of my variable "resoverall" and how to put it with PANDAS data structure.

答:
Here is mine. Just in case if you are using "pymysql":</p>

```<code>import pymysql
from pandas import DataFrame

host   = 'localhost'
port   = 3306
user   = 'yourUserName'
passwd = 'yourPassword'
db     = 'yourDatabase'

cnx    = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
cur    = cnx.cursor()

query  = """ SELECT * FROM yourTable LIMIT 10"""
cur.execute(query)

field_names = [i[0] for i in cur.description]
get_data = [xx for xx in cur]

cur.close()
cnx.close()

df = DataFrame(get_data)
df.columns = field_names
</code>```

Body:
Any help on this problem will be greatly appreciated.

So basically I want to run a query to my SQL database and store the returned data as Pandas data structure.

I have attached code for query.

I am reading the documentation on Pandas, but I have problem to identify the return type of my query.

I tried to print the query result, but it doesn't give any useful information.

Thanks!!!!

from sqlalchemy import create_engine

engine2 = create_engine('mysql://THE DATABASE I AM ACCESSING')
connection2 = engine2.connect()
dataid = 1022
resoverall = connection2.execute("
    SELECT
       sum(BLABLA) AS BLA,
       sum(BLABLABLA2) AS BLABLABLA2,
       sum(SOME_INT) AS SOME_INT,
       sum(SOME_INT2) AS SOME_INT2,
       100*sum(SOME_INT2)/sum(SOME_INT) AS ctr,
       sum(SOME_INT2)/sum(SOME_INT) AS cpc
    FROM daily_report_cooked
    WHERE campaign_id = '%s'",
    %dataid
)

So I sort of want to understand what's the format/datatype of my variable "resoverall" and how to put it with PANDAS data structure.

Body:
Here is mine. Just in case if you are using "pymysql":

import pymysql
from pandas import DataFrame

host   = 'localhost'
port   = 3306
user   = 'yourUserName'
passwd = 'yourPassword'
db     = 'yourDatabase'

cnx    = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
cur    = cnx.cursor()

query  = """ SELECT * FROM yourTable LIMIT 10"""
cur.execute(query)

field_names = [i[0] for i in cur.description]
get_data = [xx for xx in cur]

cur.close()
cnx.close()

df = DataFrame(get_data)
df.columns = field_names


问:
How to access child element property in React?
I'm creating multi-level-Accordion-menu component on React Redux.

```<code>class MultiLevelAccordianMenu extends PureComponent {
    constructor(props){
        super(props);
        this.toggleList = this.toggleList.bind(this);

    }
    toggleList(event){
        console.log(event)
    }
    render(){
        return( <ul className="cd-accordion-menu animated">
            <li className="has-children" onClick={this.toggleList}>
                <input type="checkbox" name ="group-1" id="group-1" defaultChecked />
                <label htmlFor="group-1">Group 1</label>

                <ul>
                    <li className="has-children">
                        <input type="checkbox" name ="sub-group-1" id="sub-group-1" />
                        <label htmlFor="sub-group-1">Sub Group 1</label>

                        <ul>
                            <li><a href="#0">Image</a></li>
                            <li><a href="#0">Image</a></li>
                            <li><a href="#0">Image</a></li>
                        </ul>
                    </li>
                 </ul>
             </li>
          </ul>        );
    }
  }
export default MultiLevelAccordianMenu;
</code>```

while clicking on parent "li" element, i want to toggle the child "ul" element.
I have written a toggle function. In this how can i access and set the child property to make hide and show?

答:
You can use state and change it on click. Just make className of your child element dynamic:

```<code>class MultiLevelAccordianMenu extends PureComponent {
     constructor(props){
        super(props);
        this.state = {
          isActive : false
        };
        this.toggleList = this.toggleList.bind(this);
     }
     toggleList(event){
        this.setState({isActive: !this.state.isActive});
     }
    render(){
        ....
        <li className="has-children" onClick={this.toggleList}>
        .....
        <ul className={this.state.isActive ? "active" : ""}>
          ....

}
</code>```

and add to your css something like:

```<code>ul{
  visibility: hidden;
}
.active{
  visibility: visible;
}
</code>```

If you want to add animation you can use css rule transition:

```<code>ul{
   max-height: 0;
   transition: max-height 0.15s ease-out;
   overflow: hidden;
}
ul.active {
   max-height: 500px;
   transition: max-height 0.25s ease-in;
}
</code>```

Body:
I'm creating multi-level-Accordion-menu component on React Redux.

class MultiLevelAccordianMenu extends PureComponent {
    constructor(props){
        super(props);
        this.toggleList = this.toggleList.bind(this);

    }
    toggleList(event){
        console.log(event)
    }
    render(){
        return(

                <input type="checkbox" name ="group-1" id="group-1" defaultChecked />
                Group 1

                        <input type="checkbox" name ="sub-group-1" id="sub-group-1" />
                        Sub Group 1

Image

Image

Image

        );
    }
  }
export default MultiLevelAccordianMenu;

while clicking on parent "li" element, i want to toggle the child "ul" element.
I have written a toggle function. In this how can i access and set the child property to make hide and show?

Body:
You can use state and change it on click. Just make className of your child element dynamic:

class MultiLevelAccordianMenu extends PureComponent {
     constructor(props){
        super(props);
        this.state = {
          isActive : false
        };
        this.toggleList = this.toggleList.bind(this);
     }
     toggleList(event){
        this.setState({isActive: !this.state.isActive});
     }
    render(){
        ....
        <li className="has-children" onClick={this.toggleList}>
        .....
        <ul className={this.state.isActive ? "active" : ""}>
          ....

}

and add to your css something like:

ul{
  visibility: hidden;
}
.active{
  visibility: visible;
}

If you want to add animation you can use css rule transition:

ul{
   max-height: 0;
   transition: max-height 0.15s ease-out;
   overflow: hidden;
}
ul.active {
   max-height: 500px;
   transition: max-height 0.25s ease-in;
}


问:
How to structure a Redux store with interwoven data?
I'm a newbie to React/Redux and I could use your advice on how to structure the following data models in my react app.

I have the following models:

```<code>Users
Skills (id, title)
UserSkills (user_id, skill_id)
</code>```

I want to create a component that shows a User's Skills which I would get from my API /user_skills which would return (user_id, skill_id).

Should I update my API to include the extra fields I need to render the component like Skill.title or should I somehow, with Redux, also store Skills in the Redux store, and the have UserSkills somehow find the Skill.Title from the Redux store and if it doesn't exist, go fetch the title? How can I best structure this in Redux and how can I get started?

答:
The key word is "normalization".  Once you have normalized state, you would want to look up the right Skill entry based on a skill_id in your mapStateToProps function.

See Redux Many to Many Relationship , Redux: Normalizing Global State , and React-Redux-Links for prior discussion and links to more information.

Body:
I'm a newbie to React/Redux and I could use your advice on how to structure the following data models in my react app.

I have the following models:

Users
Skills (id, title)
UserSkills (user_id, skill_id)

I want to create a component that shows a User's Skills which I would get from my API /user_skills which would return (user_id, skill_id).

Should I update my API to include the extra fields I need to render the component like Skill.title or should I somehow, with Redux, also store Skills in the Redux store, and the have UserSkills somehow find the Skill.Title from the Redux store and if it doesn't exist, go fetch the title? How can I best structure this in Redux and how can I get started?


问:
How to add superscript text using Apache POI
I want to display some text with superscript into Excel cell. I tried to pass the HTML string to XSSFRichTextString but it displays the HTML string as it is in the output file.

I'm using Apache POI 3.16

Screenshot to explain the requirement

答:
You are thinking, RichTextString should be able to interpret HTML? It is not. It is only able to apply Font from startIndex to endIndex. And Font can be marked using TypeOffset SS_SUPER.

Example:

```<code>import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

import org.apache.poi.ss.util.*;

import java.io.FileOutputStream;

class RichTextSuperscript {

 public static void main(String[] args) {
  Workbook wb = new XSSFWorkbook();
  Sheet sheet = wb.createSheet("Sheet1");

  Font fontRed = wb.createFont();
  fontRed.setColor(Font.COLOR_RED);

  Font fontRedSuperscript = wb.createFont();
  fontRedSuperscript.setColor(Font.COLOR_RED);
  fontRedSuperscript.setTypeOffset(Font.SS_SUPER);

  String string = "Level 3";

  RichTextString richString = new XSSFRichTextString( "Level 13" );
                                                     //^0     ^7
  richString.applyFont(7, 8, fontRedSuperscript);

  for (int r = 0; r < 10; r++) {
   Row row = sheet.createRow(r);
   Cell cell = row.createCell(0);
   if ((r%2) == 0) {
    cell.setCellValue(string);
   } else {
    CellUtil.setFont(cell, fontRed);
    cell.setCellValue(richString);
   }
  }

  try {
   wb.write(new FileOutputStream("RichTextSuperscript.xlsx"));
   wb.close();
   } catch (Exception ex) {
   ex.printStackTrace();
  }
 }
}
</code>```

Body:
You are thinking, RichTextString should be able to interpret HTML? It is not. It is only able to apply Font from startIndex to endIndex. And Font can be marked using TypeOffset SS_SUPER.

Example:

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

import org.apache.poi.ss.util.*;

import java.io.FileOutputStream;

class RichTextSuperscript {

 public static void main(String[] args) {
  Workbook wb = new XSSFWorkbook();
  Sheet sheet = wb.createSheet("Sheet1");

  Font fontRed = wb.createFont();
  fontRed.setColor(Font.COLOR_RED);

  Font fontRedSuperscript = wb.createFont();
  fontRedSuperscript.setColor(Font.COLOR_RED);
  fontRedSuperscript.setTypeOffset(Font.SS_SUPER);

  String string = "Level 3";

  RichTextString richString = new XSSFRichTextString( "Level 13" );
                                                     //^0     ^7
  richString.applyFont(7, 8, fontRedSuperscript);

  for (int r = 0; r < 10; r++) {
   Row row = sheet.createRow(r);
   Cell cell = row.createCell(0);
   if ((r%2) == 0) {
    cell.setCellValue(string);
   } else {
    CellUtil.setFont(cell, fontRed);
    cell.setCellValue(richString);
   }
  }

  try {
   wb.write(new FileOutputStream("RichTextSuperscript.xlsx"));
   wb.close();
   } catch (Exception ex) {
   ex.printStackTrace();
  }
 }
}


问:
Android, textviews alignment within listitem
I want to arrange the text views in each of my list items so that textview (id:lnumber) is on the left end,  textview (id:lname) next to it and the textview (id:lname1) under textview (id:lname)

I was able to align the first two textviews but am unable to arrange the third, right below the second

list_item.xml

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

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/lname1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@+id/lname"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    </LinearLayout>
</code>```

答:
Use this:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold"
        />

    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:paddingBottom="20dip"
        android:gravity="end"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black"
        />

    <TextView
        android:id="@+id/lname1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lname"
        android:layout_alignStart="@+id/lname"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black"/>

</RelativeLayout>
</code>```

Body:
I want to arrange the text views in each of my list items so that textview (id:lnumber) is on the left end,  textview (id:lname) next to it and the textview (id:lname1) under textview (id:lname)

I was able to align the first two textviews but am unable to arrange the third, right below the second

list_item.xml

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

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/lname1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@+id/lname"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    </LinearLayout>

Body:
Use this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold"
        />

    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:paddingBottom="20dip"
        android:gravity="end"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black"
        />

    <TextView
        android:id="@+id/lname1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lname"
        android:layout_alignStart="@+id/lname"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black"/>

</RelativeLayout>


答:
```<code>import random

probs = [0.1, 0.25, 0.6, 0.05]
r = random.random()
index = 0
while(r >= 0 and index < len(probs)):
  r -= probs[index]
  index += 1
print index - 1
</code>```

Title: How can I make a random choice according to probabilities stored in a list (weighted random distribution)?


问:
Value contains many text in Conditional Format Rules Google Sheet
I want to set conditional format rules in my Google spreadsheet. For the format cell, I select "Text contains", then I type values "PA, MA, CT, NY", formatting style I choose red. When I click DONE, the columns containing these words didn't show the color. I don't want to create rules "PA', "MA", "CT"and "NY" one by one. How can I fix them? Thanks for helping.</p>

答:
Try using OR with custom formula like this:</p>

```<code>=or($A2="PA",$A2="MA",$A2="CT",$A2="NY")
</code>```

Body:
Try using OR with custom formula like this:

=or($A2="PA",$A2="MA",$A2="CT",$A2="NY")


问:
How to check array of dates are consecutive from todays date?
I have an array of unique dates from each time the user completes a task. I want to check if the dates within the array are consecutive from and including todays date.

If the array contains dates: "2017/6/2, 2017/6/3, 2017/6/4, 2017/6/5" then based on today's date being 2017/6/5 the function would return 4 as there are 4 consecutive dates from and including today.

If the array contains dates "2017/6/2, 2017/6/3, 2017/6/4" then it would return 0 as the array does not include today's date. Otherwise the count would be broken upon a non consecutive date.

```<code>List<Date> dateList = new ArrayList<Date>();
int count = 0;
Date todayDate = new Date();

for (int i=0; i<dateList.size(); i++){
    // Check if dates within the array are consecutive from todayDate, if so then increment count by 1.
}
</code>```

答:
There are a lot of ways to write it more clear:

Use new Date API;

Use libraries;

But, in such case, with usage of old Date classes, I would do that in such a way:

```<code>public static void main(String[] args) {
    long millisInDay = TimeUnit.DAYS.toMillis(1);
    List<Date> dates = Arrays.asList(new Date("2017/6/2"), new Date("2017/6/3"), new Date("2017/6/4"), new Date("2017/6/5"));
    System.out.println(getSequentialNumber(millisInDay, dates));
}

private static int getSequentialNumber(long millisInDay, List<Date> dates) {
    int count = 0;
    Date now = setMidnight(Calendar.getInstance().getTime());
    for (int i = dates.size() - 1; i >= 0; i--) {
        Date date = setMidnight(dates.get(i));
        if (date.getTime() == now.getTime()) {
            count++;
        }
        now.setTime(now.getTime() - millisInDay);
    }
    return count;
}

private static Date setMidnight(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    return calendar.getTime();
}
</code>```

Body:
I have an array of unique dates from each time the user completes a task. I want to check if the dates within the array are consecutive from and including todays date.

If the array contains dates: "2017/6/2, 2017/6/3, 2017/6/4, 2017/6/5" then based on today's date being 2017/6/5 the function would return 4 as there are 4 consecutive dates from and including today.

If the array contains dates "2017/6/2, 2017/6/3, 2017/6/4" then it would return 0 as the array does not include today's date. Otherwise the count would be broken upon a non consecutive date.

List<Date> dateList = new ArrayList<Date>();
int count = 0;
Date todayDate = new Date();

for (int i=0; i<dateList.size(); i++){
    // Check if dates within the array are consecutive from todayDate, if so then increment count by 1.
}

Body:
There are a lot of ways to write it more clear:

Use new Date API;

Use libraries;

But, in such case, with usage of old Date classes, I would do that in such a way:

public static void main(String[] args) {
    long millisInDay = TimeUnit.DAYS.toMillis(1);
    List<Date> dates = Arrays.asList(new Date("2017/6/2"), new Date("2017/6/3"), new Date("2017/6/4"), new Date("2017/6/5"));
    System.out.println(getSequentialNumber(millisInDay, dates));
}

private static int getSequentialNumber(long millisInDay, List<Date> dates) {
    int count = 0;
    Date now = setMidnight(Calendar.getInstance().getTime());
    for (int i = dates.size() - 1; i >= 0; i--) {
        Date date = setMidnight(dates.get(i));
        if (date.getTime() == now.getTime()) {
            count++;
        }
        now.setTime(now.getTime() - millisInDay);
    }
    return count;
}

private static Date setMidnight(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    return calendar.getTime();
}


问:
Body#setAsync munges value returned from Body#getAsync
Office JavaScript API Reference: Body

I would expect to be able to pass in the value received from Body#getAsync directly into Body#setAsync (with the same coercion type), and for the value of the body to remain the same. In practice, this is not the case.

Demonstration

```<code>const { body } = Office.context.mailbox.item;
const coercionType = Office.CoercionType.Html;

// First, let's get the current body of the mailbox item.
body.getAsync(coercionType, {}, (firstResult) => {
  const previousBodyHtml = firstResult.value;

  // Now, let's set the body to the value we received.
  body.setAsync(previousBodyHtml, { coercionType }, () => {

    // Now, let's get the body again.
    body.getAsync(coercionType, {}, (secondResult) => {
      const nextBodyHtml = secondResult.value;

      // The values do not match.
      console.error(previousBodyHtml, 'does not equal', nextBodyHtml);
    });
  });
});
</code>```

Instead of being idempotent as expected, Body#setAsync runs through quite a bit of filtering.

Observed Behavior

Any element in the HTML string with an id or class attribute has that attribute's value prefixed with x_.

Some elements in the string returned from Body#getAsync include id and class attributes which appear to have semantic meaning to Outlook (and also to our add-in). Affected elements include indicators for quoted replies, signatures, and the wrapper element for the body HTML itself. When setting the body, these indicators become munged.

If an affected attribute already has an x_ prefix, Outlook adds another one. Thus, each time an add-in set the body, these attribute values can grow to have a sizable quantity of x_ prefixes (e.g: x_x_x_x_x_x_x_x_x_x_divtagdefaultwrapper).

The value returned from Body#getAsync may include images with Data URIs (this is true in Office 365). Body#setAsync causes the src attributes of these images to be cleared, which causes the images to appear to the user as broken images.

Images in the body should never have Data URIs to begin with -- most email clients will not render inline images with Data URIs; they appear in those emails as broken images.

Outlook renders most inline images with a src attribute of a proxied image, and with an originalsrc attribute of a cid: URI referencing an attachment on the email with the corresponding Content-ID header. This seems reasonable.

What we have discovered when developing our add-in is that, in practice, Body#setAsync expects to receive an HTML string representing what is inside the first element with an id attribute of divtagdefaultwrapper in Office 365, or the first element with class WordSection1 in Outlook 2016.

Workaround

Thus, to work around this issue, when calling Body#getAsync, we must first parse the string and rebase to the appropriate root element before persisting any changes we make to the body via Body#setAsync. We also ended up having to remove all id and class attributes from elements within the body, add our own sentinel elements to mark semantically important parts of the body (quoted replies, signatures, etc), and implementing our own proxy for images we encounter with Data URIs.

答: Due to restraints on the Word rendering engine, we cannot guarantee body.getAsync and body.setAsync are idempotent. The issue you are seeing in Office 365 with inline images in the body that use a data URI is a known issue that we are currently investigating.

Body:
Office JavaScript API Reference: Body

I would expect to be able to pass in the value received from Body#getAsync directly into Body#setAsync (with the same coercion type), and for the value of the body to remain the same. In practice, this is not the case.

Demonstration

const { body } = Office.context.mailbox.item;
const coercionType = Office.CoercionType.Html;

// First, let's get the current body of the mailbox item.
body.getAsync(coercionType, {}, (firstResult) => {
  const previousBodyHtml = firstResult.value;

  // Now, let's set the body to the value we received.
  body.setAsync(previousBodyHtml, { coercionType }, () => {

    // Now, let's get the body again.
    body.getAsync(coercionType, {}, (secondResult) => {
      const nextBodyHtml = secondResult.value;

      // The values do not match.
      console.error(previousBodyHtml, 'does not equal', nextBodyHtml);
    });
  });
});

Instead of being idempotent as expected, Body#setAsync runs through quite a bit of filtering.

Observed Behavior

Any element in the HTML string with an id or class attribute has that attribute's value prefixed with x_.

Some elements in the string returned from Body#getAsync include id and class attributes which appear to have semantic meaning to Outlook (and also to our add-in). Affected elements include indicators for quoted replies, signatures, and the wrapper element for the body HTML itself. When setting the body, these indicators become munged.

If an affected attribute already has an x_ prefix, Outlook adds another one. Thus, each time an add-in set the body, these attribute values can grow to have a sizable quantity of x_ prefixes (e.g: x_x_x_x_x_x_x_x_x_x_divtagdefaultwrapper).

The value returned from Body#getAsync may include images with Data URIs (this is true in Office 365). Body#setAsync causes the src attributes of these images to be cleared, which causes the images to appear to the user as broken images.

Images in the body should never have Data URIs to begin with -- most email clients will not render inline images with Data URIs; they appear in those emails as broken images.

Outlook renders most inline images with a src attribute of a proxied image, and with an originalsrc attribute of a cid: URI referencing an attachment on the email with the corresponding Content-ID header. This seems reasonable.

What we have discovered when developing our add-in is that, in practice, Body#setAsync expects to receive an HTML string representing what is inside the first element with an id attribute of divtagdefaultwrapper in Office 365, or the first element with class WordSection1 in Outlook 2016.

Workaround

Thus, to work around this issue, when calling Body#getAsync, we must first parse the string and rebase to the appropriate root element before persisting any changes we make to the body via Body#setAsync. We also ended up having to remove all id and class attributes from elements within the body, add our own sentinel elements to mark semantically important parts of the body (quoted replies, signatures, etc), and implementing our own proxy for images we encounter with Data URIs.


问:
MarkLogic- How to use andNot in structuredQueryBuilder
{"uuid": 121222151, "path": "/aaa/bbb/ccc.json", "name": "newDoc1",
"uuid": 121222152, "path": "/aaa/ddd.json", "name": "newDoc1"}

I am using StructuredQueryBuilder to search for results.

```<code>StructuredQueryBuilder queryBuilder = new StructuredQueryBuilder();
StructuredQueryDefinition containPositiveQuery = queryBuilder.containerQuery(queryBuilder.jsonProperty("name"), queryBuilder.term("newDoc1"));
StructuredQueryDefinition containNegativeQuery = queryBuilder.containerQuery(queryBuilder.jsonProperty("path"), queryBuilder.term("*/bbb/*"));
StructuredQueryDefinition containQuery = qb.andNot(containPositiveQuery, containNegativeQuery);
</code>```

I want the result to search for the name "newDoc1" but not in the path which contains "*/bbb/*". The above code is not working. What could be the reason?

答:
Your example JSON document is flat.  There are no nested objects.  Therefore there are no containers to query.  To achieve your goal, I'm guessing your document would need to look more like this:

```<code>{ "container": {
    "uuid": 121222151,
    "path": "/aaa/bbb/ccc.json",
    "name": "newDoc1"
  },
  "container": {
    "uuid": 121222152,
    "path": "/aaa/ddd.json",
    "name": "newDoc1"
  }
}
</code>```

And your query more like this:

```<code>StructuredQueryBuilder queryBuilder = new StructuredQueryBuilder();
StructuredQueryDefinition positiveQuery = queryBuilder.term("newDoc1");
StructuredQueryDefinition negativeQuery = queryBuilder.term("*/bbb/*");
StructuredQueryDefinition containQuery =
  queryBuilder.containerQuery(queryBuilder.jsonProperty("container"),
    qb.andNot(positiveQuery, negativeQuery));
</code>```

I can't test this fully right now, but hopefully this starts you down the right direction.

Body:
{"uuid": 121222151, "path": "/aaa/bbb/ccc.json", "name": "newDoc1",
"uuid": 121222152, "path": "/aaa/ddd.json", "name": "newDoc1"}

I am using StructuredQueryBuilder to search for results.

StructuredQueryBuilder queryBuilder = new StructuredQueryBuilder();
StructuredQueryDefinition containPositiveQuery = queryBuilder.containerQuery(queryBuilder.jsonProperty("name"), queryBuilder.term("newDoc1"));
StructuredQueryDefinition containNegativeQuery = queryBuilder.containerQuery(queryBuilder.jsonProperty("path"), queryBuilder.term("*/bbb/*"));
StructuredQueryDefinition containQuery = qb.andNot(containPositiveQuery, containNegativeQuery);

I want the result to search for the name "newDoc1" but not in the path which contains "*/bbb/*". The above code is not working. What could be the reason?

Body:
Your example JSON document is flat.  There are no nested objects.  Therefore there are no containers to query.  To achieve your goal, I'm guessing your document would need to look more like this:

{ "container": {
    "uuid": 121222151,
    "path": "/aaa/bbb/ccc.json",
    "name": "newDoc1"
  },
  "container": {
    "uuid": 121222152,
    "path": "/aaa/ddd.json",
    "name": "newDoc1"
  }
}

And your query more like this:

StructuredQueryBuilder queryBuilder = new StructuredQueryBuilder();
StructuredQueryDefinition positiveQuery = queryBuilder.term("newDoc1");
StructuredQueryDefinition negativeQuery = queryBuilder.term("*/bbb/*");
StructuredQueryDefinition containQuery =
  queryBuilder.containerQuery(queryBuilder.jsonProperty("container"),
    qb.andNot(positiveQuery, negativeQuery));

I can't test this fully right now, but hopefully this starts you down the right direction.


问:
Why is uicontrol function in matlab returning a double value?
I am using this command to create a uicontrol object

```<code>h = uicontrol('style','listbox','max',10,'min',1,'Position',[200 200 200 200],'string',sheets,'Callback',@listbox1_Callback);
</code>```

It is returning random double values (0.017, 0.035 etc.) for h and thus giving error while executing callback since no object handle is being created.

Complete code

```<code>FileName = uigetfile('*.xlsx','Select the data file',filepath);
[status,sheets,xlFormat] = xlsfinfo(FileName)
h = uicontrol('style','listbox','max',10,'min',1,'Position',[200 200 200 200],'string',sheets,'Callback',@listbox1_Callback);
</code>```

答:
That is the behavior of different Matlab versions. To get a property of the uicontrol, this works no matter h is double or handle:

```<code>str = get(h, 'String'); % work for all versions
</code>```

Later Matlab supports more convenient way for this:

```<code>str = h.String; % only supported for later versions where h is handle
</code>```

If you like to use the latter syntax for earlier version, you can do this:

```<code>h = handle(h); % convert double to handle for earlier matlab
</code>```

Then you can do the same as for later matlab. The above command won't hurt for later matlab versions, if you worry about compatibility to different versions.

Body:
I am using this command to create a uicontrol object

h = uicontrol('style','listbox','max',10,'min',1,'Position',[200 200 200 200],'string',sheets,'Callback',@listbox1_Callback);

It is returning random double values (0.017, 0.035 etc.) for h and thus giving error while executing callback since no object handle is being created.

Complete code

FileName = uigetfile('*.xlsx','Select the data file',filepath);
[status,sheets,xlFormat] = xlsfinfo(FileName)
h = uicontrol('style','listbox','max',10,'min',1,'Position',[200 200 200 200],'string',sheets,'Callback',@listbox1_Callback);

Body:
That is the behavior of different Matlab versions. To get a property of the uicontrol, this works no matter h is double or handle:

str = get(h, 'String'); % work for all versions

Later Matlab supports more convenient way for this:

str = h.String; % only supported for later versions where h is handle

If you like to use the latter syntax for earlier version, you can do this:

h = handle(h); % convert double to handle for earlier matlab

Then you can do the same as for later matlab. The above command won't hurt for later matlab versions, if you worry about compatibility to different versions.


问:
Can I use Lucene to see if a "query" would match a word?
query_text = "Justin Beiber"; (Bieber is spelled wrong)

word = "Bieber";

boolean results = does_match(query_text, word);

Note: Neither "Justin Beiber" nor "Bieber" is in a Lucene document

答:
I'm not aware of anything that does that without building an index to actually run the query. However, you can create a temporary index in memory pretty easily. You will need to provide at least one more thing to a method like that, though, an analyzer.

So you could create a doesMatch method like this:

public static boolean doesMatch(String query, String doctext, Analyzer analyzer) throws IOException, ParseException {
    Directory dir = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);
    IndexWriter writer = new IndexWriter(dir, config);
    Document doc = new Document();
    doc.add(new TextField("text", doctext, Field.Store.NO));
    writer.addDocument(doc);
    writer.close();

    IndexReader reader = DirectoryReader.open(dir);
    IndexSearcher searcher = new IndexSearcher(reader);
    QueryParser parser = new QueryParser("text", analyzer);
    Query parsedQuery = parser.parse(query);
    TopDocs results = searcher.search(parsedQuery, 1);

    reader.close();
    dir.close();

    return results.totalHits == 1;
}
```


问:
Is terminating an object is the same as nulling it?
So i have been going through "Effective Java 2nd Ed."

In item 7 he talks about not using finalizers because they can cause a lot of problems .

But instead of using finalizers we can " provide an explicit termination method" and an example of those is the close statement . and i did not understand what is " termination statements and what are the differences between them and finalizers ?

I came to the conclusion that terminating an object is like nulling it thus the resourses is released . but i think i don`t understand the difference that well . so i appreciate any help .

Thanks !

答:
The main difference between an explicit termination method and finalize() is that the second one is not guaranteed to be called. It's called eventually during garbage collection which might to be honest never occur. Lets consider the following three classes.

```<code>class Foo {
    @Override
    public void finalize() {
        System.out.println("Finalize Foo");
    }
}

class Bar implements Closeable {
    @Override
    public void close() {
        System.out.println("Close Bar");
    }
}

class Baz implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("Close Baz");
    }
}
</code>```

The first one overrides the finalize() method inherited from Object. Foo and Bar implement both interfaces which are handled by ARM (Automatic Resource Management).

```<code>Foo foo = new Foo();
new Foo();
try (Bar bar = new Bar(); Baz baz = new Baz()) { // this is ARM
    System.out.println("termination example");
}
Bar bar = null;
try {
    bar = new Bar();
    // ...
} finally {
    if (bar != null) {
        bar.close();
    }
}
</code>```

This example should return:

```<code>termination example
Close Baz
Close Bar
Close Bar
</code>```

The finalize() method of Foo gets never called because Foo is not garbage collected. The JVM has available resources, so for performance optimization it does not perform garbage collecting. Furthermore - if a resource isn't garbage collected despite the fact of finishing the Application. Even the second created instance of Foo is not Garbage Collected, because there is plenty of resources for the JVM to thrive.

The second one with ARM is a lot better, because it creates both the resources (one implementing java.io.Closeable and one implementing java.lang.AutoCloseable, it's worth mentioning that Closeable extends AutoCloseable, that's why it's available for ARM). ARM guaranties for both of these resources to be closed, to close one when the other throws and so on. The second one presents something similar to ARM, but saving a lot of unnecessary boilerplate code.

Something making you a better developer:

But it's still not perfect. There is still a burden on the programmer to remember closing the object. The absence of destructors in Java forces the developer either to remember closing the resource, remember to use ARM and so on. There is a good design pattern (good explained by Venkat Subramaniam) - the Loan Pattern. A simple example of the loan pattern:

```<code>class Loan {
    private Loan() {
    }

    public Loan doSomething(int m) {
        System.out.println("Did something " + m);
        if (new Random().nextBoolean()) {
            throw new RuntimeException("Didn't see that commming");
        }
        return this;
    }

    public Loan doOtherThing(int n) {
        System.out.println("Did other thing " + n);
        return this;
    }

    private void close() {
        System.out.println("Closed");
    }

    public static void loan(Consumer<Loan> toPerform) {
        Loan loan = new Loan();
        try {
            toPerform.accept(loan);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            loan.close();
        }
    }
}
</code>```

You can use it like that:

```<code>class Main {
    public static void main(String[] args) {
        Loan.loan(loan -> loan.doOtherThing(2)
                .doSomething(3)
                .doOtherThing(3));
    }
}
</code>```

It relieves the developer of the burden of closing the resource, because it has already been handled for him. If one of these methods throws, then it's handled and the developer does not have to bother. The close method and constructor are private to not tempt the developer to use them.

Body:
The main difference between an explicit termination method and finalize() is that the second one is not guaranteed to be called. It's called eventually during garbage collection which might to be honest never occur. Lets consider the following three classes.

class Foo {
    @Override
    public void finalize() {
        System.out.println("Finalize Foo");
    }
}

class Bar implements Closeable {
    @Override
    public void close() {
        System.out.println("Close Bar");
    }
}

class Baz implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("Close Baz");
    }
}

The first one overrides the finalize() method inherited from Object. Foo and Bar implement both interfaces which are handled by ARM (Automatic Resource Management).

Foo foo = new Foo();
new Foo();
try (Bar bar = new Bar(); Baz baz = new Baz()) { // this is ARM
    System.out.println("termination example");
}
Bar bar = null;
try {
    bar = new Bar();
    // ...
} finally {
    if (bar != null) {
        bar.close();
    }
}

This example should return:

termination example
Close Baz
Close Bar
Close Bar

The finalize() method of Foo gets never called because Foo is not garbage collected. The JVM has available resources, so for performance optimization it does not perform garbage collecting. Furthermore - if a resource isn't garbage collected despite the fact of finishing the Application. Even the second created instance of Foo is not Garbage Collected, because there is plenty of resources for the JVM to thrive.

The second one with ARM is a lot better, because it creates both the resources (one implementing java.io.Closeable and one implementing java.lang.AutoCloseable, it's worth mentioning that Closeable extends AutoCloseable, that's why it's available for ARM). ARM guaranties for both of these resources to be closed, to close one when the other throws and so on. The second one presents something similar to ARM, but saving a lot of unnecessary boilerplate code.

Something making you a better developer:

But it's still not perfect. There is still a burden on the programmer to remember closing the object. The absence of destructors in Java forces the developer either to remember closing the resource, remember to use ARM and so on. There is a good design pattern (good explained by Venkat Subramaniam) - the Loan Pattern. A simple example of the loan pattern:

class Loan {
    private Loan() {
    }

    public Loan doSomething(int m) {
        System.out.println("Did something " + m);
        if (new Random().nextBoolean()) {
            throw new RuntimeException("Didn't see that commming");
        }
        return this;
    }

    public Loan doOtherThing(int n) {
        System.out.println("Did other thing " + n);
        return this;
    }

    private void close() {
        System.out.println("Closed");
    }

    public static void loan(Consumer<Loan> toPerform) {
        Loan loan = new Loan();
        try {
            toPerform.accept(loan);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            loan.close();
        }
    }
}

You can use it like that:

class Main {
    public static void main(String[] args) {
        Loan.loan(loan -> loan.doOtherThing(2)
                .doSomething(3)
                .doOtherThing(3));
    }
}

It relieves the developer of the burden of closing the resource, because it has already been handled for him. If one of these methods throws, then it's handled and the developer does not have to bother. The close method and constructor are private to not tempt the developer to use them.


问:
MVC5 TextboxFor dispay Date without Time
I'm trying to display the date only without the time but nothing seems to work with MVC5. I need to use TextboxFor and not EditorFor. I tried:

```<code> <td class="input-pricing">@Html.TextBoxFor(m => new ProjectPricing().UnitTypePriceEffDate,"{0:MM/dd/yy}", new {id = "model-effectiveDate", @class = "date" })</td>
</code>```

and it still shows the time.

```<code>UnitTypePriceEffDate is of DateTimeOffSet type.
</code>```

I clone the model in jQuery:

```<code>  $("#model-pricing-row").clone().attr("id", "pricing-row-" + i).appendTo("#pricing-table");
     $("#pricing-row-" + i + " #model-effectiveDate").attr("id", "effectiveDate-" + i);
    $("#effectiveDate-" + i).attr("name", "Project.ProjectPricings[" + i + "].UnitTypePriceEffDate");
  $("#effectiveDate-" + i).val(selectedUnitTypePriceEffDate[i]);
</code>```

Can anyone help? Thanks!

答:
Try the following (I'm assuming that UnitTypePriceEffDate is a DateTime type):</p>

```<code> <td class="input-pricing">
     @Html.TextBox("model-effectiveDate",
                    new ProjectPricing().UnitTypePriceEffDate.ToShortDateString(),
                    new { @class = "date" })
 </td>
</code>```

Body:
I'm trying to display the date only without the time but nothing seems to work with MVC5. I need to use TextboxFor and not EditorFor. I tried:

 @Html.TextBoxFor(m => new ProjectPricing().UnitTypePriceEffDate,"{0:MM/dd/yy}", new {id = "model-effectiveDate", @class = "date" })

and it still shows the time.

UnitTypePriceEffDate is of DateTimeOffSet type.

I clone the model in jQuery:

  $("#model-pricing-row").clone().attr("id", "pricing-row-" + i).appendTo("#pricing-table");
     $("#pricing-row-" + i + " #model-effectiveDate").attr("id", "effectiveDate-" + i);
    $("#effectiveDate-" + i).attr("name", "Project.ProjectPricings[" + i + "].UnitTypePriceEffDate");
  $("#effectiveDate-" + i).val(selectedUnitTypePriceEffDate[i]);

Can anyone help? Thanks!

Body:
Try the following (I'm assuming that UnitTypePriceEffDate is a DateTime type):

 <td class="input-pricing">
     @Html.TextBox("model-effectiveDate",
                    new ProjectPricing().UnitTypePriceEffDate.ToShortDateString(),
                    new { @class = "date" })
 </td>


问:
Can't load Image HTTP
I can't load this image, help me please!
My info.plist >

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>
</code>```

my Code >

```<code>      <View style={{flex: 1, flexDirection: 'row'}}>
        <Image
        source={{uri: 'http://ro-character-simulator.ratemyserver.net/charsim.php?gender=1&job=40&hair=1&viewid=0&location=256&direction=0&action=1&hdye=1&dye=0&framenum=0&bg=0&cart=&mount=0&shield=0&weapon=0&animate=1&rand=9725591', width: 50, height: 50}}/>
      </View>
</code>```

答:
I think you need one more key in your Info.plist

```<code><key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>
</code>```

Title: Can't load Image HTTP

Body:
I can't load this image, help me please!
My info.plist >

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

my Code >

      <View style={{flex: 1, flexDirection: 'row'}}>
        <Image
        source={{uri: 'http://ro-character-simulator.ratemyserver.net/charsim.php?gender=1&job=40&hair=1&viewid=0&location=256&direction=0&action=1&hdye=1&dye=0&framenum=0&bg=0&cart=&mount=0&shield=0&weapon=0&animate=1&rand=9725591', width: 50, height: 50}}/>
      </View>

Body:
I think you need one more key in your Info.plist

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>


问:
Return R output to Java when using RServe
I am using rServe to integrate R and Java. I'm able to call R function from Java and that function returns summary of variable. But the problem is I am unable to display that summary in Java. Below is the snippet of Java code I'm using.

```<code>RConnection c = new RConnection();
c.eval("library(ggplot)");
REXP desc = c.eval("describe(mpg)");
System.out.println(desc.asString());
</code>```

describe function in R gives following output.

```<code>describe(mpg)
mpg

 11  Variables      234  Observations
--------------------------------------------------------------------------
manufacturer
       n  missing distinct
     234        0       15

audi (18, 0.077), chevrolet (19, 0.081), dodge (37, 0.158), ford (25,
0.107), honda (9, 0.038), hyundai (14, 0.060), jeep (8, 0.034), land
rover (4, 0.017), lincoln (3, 0.013), mercury (4, 0.017), nissan (13,
0.056), pontiac (5, 0.021), subaru (14, 0.060), toyota (34, 0.145)
</code>```

答:
The way that I capture my R output in java is:</p>

```<code>String ret = c.eval("paste(capture.output(describe(mpg))),collapse='\\n')").asString();
System.out.print(ret);
</code>```

Body:
I am using rServe to integrate R and Java. I'm able to call R function from Java and that function returns summary of variable. But the problem is I am unable to display that summary in Java. Below is the snippet of Java code I'm using.

RConnection c = new RConnection();
c.eval("library(ggplot)");
REXP desc = c.eval("describe(mpg)");
System.out.println(desc.asString());

describe function in R gives following output.

describe(mpg)
mpg

 11  Variables      234  Observations
--------------------------------------------------------------------------
manufacturer
       n  missing distinct
     234        0       15

audi (18, 0.077), chevrolet (19, 0.081), dodge (37, 0.158), ford (25,
0.107), honda (9, 0.038), hyundai (14, 0.060), jeep (8, 0.034), land
rover (4, 0.017), lincoln (3, 0.013), mercury (4, 0.017), nissan (13,
0.056), pontiac (5, 0.021), subaru (14, 0.060), toyota (34, 0.145)

Body:
The way that I capture my R output in java is:

String ret = c.eval("paste(capture.output(describe(mpg))),collapse='\\n')").asString();
System.out.print(ret);


问:
Resolving macro variable inside PROC SQL
I have a macro variable I need to use within PROC SQL. The way it resolves appears to have perfect syntax, but I am getting a syntax error and I'm not sure why;

```<code>%let test = mytext;
PROC SQL;
CREATE TABLE myTalbe&test AS
SELECT DISTINCT
    a.column
FROM
    tablename a
WHERE
    a.column = %bquote('&test')
;QUIT;
</code>```

The error I get throws a red line under the resolved text, 'mytext', and says

ERROR 22-322: Syntax error, expecting one of the following: a name, a
  quoted string, a numeric constant, a datetime constant,
                a missing value, (, *, +, -, ALL, ANY, BTRIM, CALCULATED, CASE, INPUT, PUT, SELECT, SOME, SUBSTRING, TRANSLATE,
                USER.

I don't feel like this error applies here. If I hard code in 'mytext' it works fine. Am I missing something right under my nose? Can anyone lend me a hand?

Thanks!!!

答:
The macro quoting is confusing the SAS parser. For this program I would remove the use of %bquote() and just use double quotes instead of single quotes so that the macro variable reference will resolve.

```<code>WHERE a.column = "&test"
</code>```

If your are actually generating pass thru SQL into a system that requires the use of single quotes for string literals then you will need to use %unquote() to remove the macro quoting.

```<code>... from connection to ... ( ...
WHERE a.column = %unquote(%bquote('&test'))
... ) ...
</code>```

Body:
I have a macro variable I need to use within PROC SQL. The way it resolves appears to have perfect syntax, but I am getting a syntax error and I'm not sure why;

%let test = mytext;
PROC SQL;
CREATE TABLE myTalbe&test AS
SELECT DISTINCT
    a.column
FROM
    tablename a
WHERE
    a.column = %bquote('&test')
;QUIT;

The error I get throws a red line under the resolved text, 'mytext', and says

ERROR 22-322: Syntax error, expecting one of the following: a name, a
  quoted string, a numeric constant, a datetime constant,
                a missing value, (, *, +, -, ALL, ANY, BTRIM, CALCULATED, CASE, INPUT, PUT, SELECT, SOME, SUBSTRING, TRANSLATE,
                USER.

I don't feel like this error applies here. If I hard code in 'mytext' it works fine. Am I missing something right under my nose? Can anyone lend me a hand?

Thanks!!!

Body:
The macro quoting is confusing the SAS parser. For this program I would remove the use of %bquote() and just use double quotes instead of single quotes so that the macro variable reference will resolve.

WHERE a.column = "&test"

If your are actually generating pass thru SQL into a system that requires the use of single quotes for string literals then you will need to use %unquote() to remove the macro quoting.

... from connection to ... ( ...
WHERE a.column = %unquote(%bquote('&test'))
... ) ...


问:
Bing Maps Geocode Creators Update
Since the Creators Update, results from using the UWP Bing Maps API for geocoding and reverse geocoding have significantly changed.  Locations that used to be found are now not and the addresses have values in different properties.  I can run the same application on different machines with and without the Creators Update to see the differences.  These addresses are in the UK, are anyone else experiencing this issue or have any ideas?</p>

答: This is to be expected. Previous versions of the UWP maps used data primarily from a single data provider and had a lot of issues. The creators update now uses the Bing Maps data source which has data from hundreds of data providers around the world. The forward and reverse geocoding quality globally in the UWP maps has improved significantly. However, the UK is still a work in progress. The Bing Maps team has been rolling out a new geocoder which is a lot of improvements, but hasn't yet enabled this for the UK yet as they are working through some known issues. This will likely be enabled in a few months time once these issues are worked through. Currently the geocoder for the UK is using the Bing Maps geocoder which is still better than what the UWP map control was using, but the data is older.</p>

Title: Bing Maps Geocode Creators Update


问:
Using Case in a Cursor with T-SQL
With the code below, I'd like make a "switch", check a field value and set another field depending of the value. I have to do this for each row then it's in a cursor. But something is missing ...

Thanks for your help

```<code>DECLARE @Res int
OPEN MyCursor;

 FETCH NEXT FROM MyCursor
 INTO @field1, @field2, @field3, @field4

 WHILE @@FETCH_STATUS = 0
 BEGIN
  SELECT
  CASE @field1
   WHEN 'A' THEN @Res = 1
   WHEN 'B' THEN @Res = 2
   WHEN 'C' THEN @Res = 3
   WHEN 'D' THEN @Res = 4
   WHEN 'E' THEN @Res = 5
  END

  FETCH NEXT FROM MyCursor
  INTO @field1, @field2, @field3, @field4

 END

CLOSE MyCursor;
</code>```

答:
To fix your immediate issue, you'd do this:

```<code>SELECT @Res =
  CASE @field1
   WHEN 'A' THEN 1
   WHEN 'B' THEN 2
   WHEN 'C' THEN 3
   WHEN 'D' THEN 4
   WHEN 'E' THEN 5
  END
</code>```

What do you want to do with @Res? And why do you think you need a cursor?

Title: Using Case in a Cursor with T-SQL

Body:
With the code below, I'd like make a "switch", check a field value and set another field depending of the value. I have to do this for each row then it's in a cursor. But something is missing ...

Thanks for your help

DECLARE @Res int
OPEN MyCursor;

 FETCH NEXT FROM MyCursor
 INTO @field1, @field2, @field3, @field4

 WHILE @@FETCH_STATUS = 0
 BEGIN
  SELECT
  CASE @field1
   WHEN 'A' THEN @Res = 1
   WHEN 'B' THEN @Res = 2
   WHEN 'C' THEN @Res = 3
   WHEN 'D' THEN @Res = 4
   WHEN 'E' THEN @Res = 5
  END

  FETCH NEXT FROM MyCursor
  INTO @field1, @field2, @field3, @field4

 END

CLOSE MyCursor;

Body:
To fix your immediate issue, you'd do this:

SELECT @Res =
  CASE @field1
   WHEN 'A' THEN 1
   WHEN 'B' THEN 2
   WHEN 'C' THEN 3
   WHEN 'D' THEN 4
   WHEN 'E' THEN 5
  END

What do you want to do with @Res? And why do you think you need a cursor?


问:
How to change the order of fields in an already opened TADODataSet?
I have a TADODataSet that loads some columns from the DB (a SP, but that does not matter). e.g:

```<code>SELECT A, B, C, D FROM Foo
</code>```

Now, after I open the dataset, Is it possible to change the order  of fields (or swap them) in that TADODataSet so that it will contain e.g:

```<code>C, D, A, B
</code>```

I want to do it without changing the command text itself.
Is it possible?

答:
You can use the Index property of the TField class to set the desired order.

Example:

```<code>MyDataset.FieldByName('C').Index := 0;
MyDataset.FieldByName('D').Index := 1;
MyDataset.FieldByName('A').Index := 2;
MyDataset.FieldByName('B').Index := 3;
</code>```

This also works if the fields are persistent:

```<code>MyDatasetC.Index := 0;
MyDatasetD.Index := 1;
MyDatasetA.Index := 2;
MyDatasetB.Index := 3;
</code>```

Body:
I have a TADODataSet that loads some columns from the DB (a SP, but that does not matter). e.g:

SELECT A, B, C, D FROM Foo

Now, after I open the dataset, Is it possible to change the order  of fields (or swap them) in that TADODataSet so that it will contain e.g:

C, D, A, B

I want to do it without changing the command text itself.
Is it possible?

Body:
You can use the Index property of the TField class to set the desired order.

Example:

MyDataset.FieldByName('C').Index := 0;
MyDataset.FieldByName('D').Index := 1;
MyDataset.FieldByName('A').Index := 2;
MyDataset.FieldByName('B').Index := 3;

This also works if the fields are persistent:

MyDatasetC.Index := 0;
MyDatasetD.Index := 1;
MyDatasetA.Index := 2;
MyDatasetB.Index := 3;


问:
Occlusion in Tango AR Camera
I have a simple Tango Unity app which uses the Tango AR Camera prefab to display a 3D object in augmented reality.

Following this question, I wanted to try out the occlusion feature provided by TangoARScreen.

Therefore I have:

checked the "Enable Occlusion" checkbox

enabled depth detection in Tango Manager

added a Tango Point Cloud with Update points mesh enabled.

However the 3D object never gets hidden by foreground real-world objects. What am I missing?

Is there any sample project that demonstrates this "Enable Occlusion" feature?

答: That seems to have been fixed in latest versions of the Tango SDK.</p>

Title: Occlusion in Tango AR Camera


问:
Browser agnostic C++ DOM interface
When programming in C++ against the browser's DOM each engine has a different set of interfaces, IE has the COM based [MSHTML](http://msdn.microsoft.com/en-us/library/aa752279(VS.85).aspx), Mozilla has the XPCOM based Gecko DOM etc.

Is there a common API that has adapters for major browsers (and versions)?

As a clarification, the application in question is a desktop application written in C++ which interacts with browsers, currently we have separate code bases for support of IE and Mozilla and I'm trying to reduce duplications of logic and allow adding new browsers with less effort.

A concrete example can be getting the innerHTML property of an HTML element.

```<code>// Firefox
nsAutoString html;
nsCOMPtr<nsIDOMNSHTMLElement> elem = do_QueryInterface(obj);
if (elem)
    elem->GetInnerHTML(html);

// IE
CComBSTR html;
MSHTML::IHTMLElementPtr elem = obj;
if (elem)
     elem->get_innerHTML(&html);
</code>```

答: Any reason why it has to be C++? Can't you use jQuery? Or something like http://webkit.org/blog/156/queryselector-and-queryselectorall/ in WebKit might do the trick..</p>

OwnerDisplayName: Motti

Title: Browser agnostic C++ DOM interface

Body:
When programming in C++ against the browser's DOM each engine has a different set of interfaces, IE has the COM based [MSHTML](http://msdn.microsoft.com/en-us/library/aa752279(VS.85).aspx), Mozilla has the XPCOM based Gecko DOM etc.

Is there a common API that has adapters for major browsers (and versions)?

As a clarification, the application in question is a desktop application written in C++ which interacts with browsers, currently we have separate code bases for support of IE and Mozilla and I'm trying to reduce duplications of logic and allow adding new browsers with less effort.

A concrete example can be getting the innerHTML property of an HTML element.

// Firefox
nsAutoString html;
nsCOMPtr<nsIDOMNSHTMLElement> elem = do_QueryInterface(obj);
if (elem)
    elem->GetInnerHTML(html);

// IE
CComBSTR html;
MSHTML::IHTMLElementPtr elem = obj;
if (elem)
     elem->get_innerHTML(&html);

LastEditorDisplayName: Motti

OwnerDisplayName: Henrik Hartz


问:
Reading Word Documents stored in Oracle DB as a BLOB object using C#
We store a word document in an Oracle 10g database as a BLOB object. I want to read the contents (the text) of this word document, make some changes, and write the text alone to a different field in a C# code.

How do I do this in C# 2.0?

The easiest logic that I came up with is this -

Read the BLOB object

Store it in the FileSystem

Extract the text contents

Do your job

Write the text into a separate field.

I can use Word.dll but not any commercial solutions such as Aspose

答:
I assume that you already know how to do steps 1 and 2 (use the Oracle.DataAccess and System.IO namespaces).

For step 3 and 5, use Word Automation. This MS support article shows you how to get started: How to automate Microsoft Word to create a new document by using Visual C#

If you know what version of Word it will be, then I'd suggest using early binding, otherwise use late binding. More details and sample code here: Using early binding and late binding in Automation

Edit: If you don't know how to use BLOBs from C#, take a look here: How to: Read and Write BLOB Data to a Database Table Through an Anonymous PL/SQL Block