问:
Group By (Name) and Order By (Date) for two select query
I got a sort of large query which contains a inner select query. My objective is to group all the records by field call Product Number (which is not unique and appears multiple times) and then by the Date.

I added the Order By date at the end of the query and seems to work fine. The query generated all the records in order of the Date but the records are not grouped by the ProductNumber.

Here is a visual sample of the data

```<code>ProductId   Manufacturer        ProductNumber       Date
1           Kellog                H1            05/05/2017
5           Nestle                H1            05/01/2017
8           Nutmeg                H1            04/30/2017
9           Highland              H3            04/09/2017
10          Houston               H1            04/15/2017
11          Miami                 H3            04/12/2017
</code>```

I am trying to get the output to look like the following

```<code>ProductId   Manufacturer        ProductNumber       Date
1           Kellog                H1            05/05/2017
5           Nestle                H1            05/01/2017
8           Nutmeg                H1            04/30/2017
10          Houston               H1            04/15/2017
9           Highland              H3            04/09/2017
11          Miami                 H3            04/12/2017
</code>```

So, how would I group by a column field (ProductNumber) with group by and then order by Date?
In the query, I added the Order by Date. When I added the group by ProductNumber, the error message is asking me add all the fields in the inner select to the group by. Do I really need to all all the fields(there are lot of them in the real query) in the select to my group by? There must be a better solution.

Here is my query (just a sample) so far

```<code>SELECT DISTINCT TOP 100 *,
FROM   (SELECT DISTINCT NP.ManufacuturerId,
                        C.ManufacuturerName,
                        IR2.ProductNumber,
                        NP.Field1,
                        NP.Field2,
                        NP.Field3,
                        NP.Field4,
                        CN.C2Date                     CN.CompanyNotificationId,
                        NPR.NotificationProcessName,
                        Cast(NP.CompanyId AS VARCHAR(15))
                        + NPR.NotificationProcessName AS 'CompanyIdAndProcess',
                        CC.UserId,
                        NT.NotificationTypeName,
                        CC.EmailAddress,
                        IsRegistered = CASE
                                         WHEN C.IsRegistered = 1 THEN 'Yes'
                                         ELSE 'No'
                                       END,
        FROM   ProductDetails NP
               INNER JOIN Manufactuers C
                       ON C.ManufacuturerId = NP.ManufacturerId) Q
ORDER  BY CN.C2DateDESC;
</code>```

答:
What you are calling "grouping" is really ordering.

Order by ProductNumber, Date.

Body:
I got a sort of large query which contains a inner select query. My objective is to group all the records by field call Product Number (which is not unique and appears multiple times) and then by the Date.

I added the Order By date at the end of the query and seems to work fine. The query generated all the records in order of the Date but the records are not grouped by the ProductNumber.

Here is a visual sample of the data

ProductId   Manufacturer        ProductNumber       Date
1           Kellog                H1            05/05/2017
5           Nestle                H1            05/01/2017
8           Nutmeg                H1            04/30/2017
9           Highland              H3            04/09/2017
10          Houston               H1            04/15/2017
11          Miami                 H3            04/12/2017

I am trying to get the output to look like the following

ProductId   Manufacturer        ProductNumber       Date
1           Kellog                H1            05/05/2017
5           Nestle                H1            05/01/2017
8           Nutmeg                H1            04/30/2017
10          Houston               H1            04/15/2017
9           Highland              H3            04/09/2017
11          Miami                 H3            04/12/2017

So, how would I group by a column field (ProductNumber) with group by and then order by Date?
In the query, I added the Order by Date. When I added the group by ProductNumber, the error message is asking me add all the fields in the inner select to the group by. Do I really need to all all the fields(there are lot of them in the real query) in the select to my group by? There must be a better solution.

Here is my query (just a sample) so far

SELECT DISTINCT TOP 100 *,
FROM   (SELECT DISTINCT NP.ManufacuturerId,
                        C.ManufacuturerName,
                        IR2.ProductNumber,
                        NP.Field1,
                        NP.Field2,
                        NP.Field3,
                        NP.Field4,
                        CN.C2Date                     CN.CompanyNotificationId,
                        NPR.NotificationProcessName,
                        Cast(NP.CompanyId AS VARCHAR(15))
                        + NPR.NotificationProcessName AS 'CompanyIdAndProcess',
                        CC.UserId,
                        NT.NotificationTypeName,
                        CC.EmailAddress,
                        IsRegistered = CASE
                                         WHEN C.IsRegistered = 1 THEN 'Yes'
                                         ELSE 'No'
                                       END,
        FROM   ProductDetails NP
               INNER JOIN Manufactuers C
                       ON C.ManufacuturerId = NP.ManufacturerId) Q
ORDER  BY CN.C2DateDESC;


来源: stackexchange

问:
Google Places Search - Next Page Token returns same results
When I call

```<code>https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=42.9825,-81.254&radius=50000&name=Medical%22Clinic&sensor=false&key=[KEY GOES HERE]
</code>```

I get a set of results with next_page_token being available

now if i do the same

```<code>https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=42.9825,-81.254&radius=50000&name=Medical%22Clinic&sensor=false&key=[KEY GOES HERE]&next_page_token=[NEXT PAGE TOKEN GOES HERE]
</code>```

I get the same results as the first query not the next set of results

答:
At first request you must use parameters without pagetoken while the following requests only pagetoken parameters, for example:

First request

```https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=42.9825,-81.254&radius=50000&name=Medical%22Clinic&sensor=false&key=[KEY GOES HERE]```

Other request:

```https://maps.googleapis.com/maps/api/place/nearbysearch/xml?key=[KEY GOES HERE]&pagetoken=[NEXT PAGE TOKEN GOES HERE]```

In case any parameters are entered in subsequent calls in addition to pagetoken and key, in the response the status will be set to INVALID_REQUEST

ContentLicense: CC BY-SA 3.0

Body:
When I call

https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=42.9825,-81.254&radius=50000&name=Medical%22Clinic&sensor=false&key=[KEY GOES HERE]

I get a set of results with next_page_token being available

now if i do the same

https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=42.9825,-81.254&radius=50000&name=Medical%22Clinic&sensor=false&key=[KEY GOES HERE]&next_page_token=[NEXT PAGE TOKEN GOES HERE]

I get the same results as the first query not the next set of results

Body:
At first request you must use parameters without pagetoken while the following requests only pagetoken parameters, for example:

First request

https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=42.9825,-81.254&radius=50000&name=Medical%22Clinic&sensor=false&key=[KEY GOES HERE]

Other request:

https://maps.googleapis.com/maps/api/place/nearbysearch/xml?key=[KEY GOES HERE]&pagetoken=[NEXT PAGE TOKEN GOES HERE]

In case any parameters are entered in subsequent calls in addition to pagetoken and key, in the response the status will be set to INVALID_REQUEST


答:
I would use OpenSSL. Assuming that you have the key in DER format, you can use this command to convert from DER to PEM.

```<code>openssl x509 -inform der -in input.der -out output.pem
</code>```

If you are not sure whether you have the correctly formatted DER (ASN.1) encoded key, try this tool to parse your input file.

ContentLicense: CC BY-SA 2.5

Title: RSA key convert to PEM file

Body:
How can I convert this RSA public key:
109120132967399429278860960508995541528237502902798129123468757937266291492576446330739696001110 6039072308886100726558188253585034290 57592827629436413108566029093628 2126359538366865626758497206207862794310902180176810615217550567108238764764442605581471797071 19674283982419152118103759076030616683978566631413

to *.pem file?

Body:
I would use OpenSSL. Assuming that you have the key in DER format, you can use this command to convert from DER to PEM.

openssl x509 -inform der -in input.der -out output.pem

If you are not sure whether you have the correctly formatted DER (ASN.1) encoded key, try this tool to parse your input file.


问:
ERROR 2245: Cannot get schema from loadFunc org.apache.hive.hcatalog.pig.HCatLoader
I try to load files from a partitioned Hive table.

```<code>LKR_BU = LOAD 'baseName.tableName' USING org.apache.hive.hcatalog.pig.HCatLoader();
</code>```

After running I get the following error:

```<code>2016-07-04 15:01:58,743 [uber-SubtaskRunner] ERROR org.apache.pig.tools.grunt.Grunt  - ERROR 2245: Cannot get schema from loadFunc org.apache.hive.hcatalog.pig.HCatLoader
</code>```

For information, I have all the required libraries and HCatalog {Loader, Storer} works perfectly with oozie launcher.

Someone already encountered this kind of problem ?

答:
There are many steps you need to follow to make HCatalog work in Pig.

Overall, I assume that you would have configured all the paths (hcatalog) and you would have included all the required jars in the classpath.

If not, please follow this post :-
http://www.thecloudavenue.com/2013/11/InstallingAndConfiguringHCatalogAndIntegratingWithPig.html#comment-form

Or, you can also follow below post :-
https://acadgild.com/blog/loading-and-storing-hive-data-into-pig/

After you have followed all the steps above, you would need to start following services :-

hiveserver2 --> hive --service hiveserver2

hive metastore  -->  hive  --service metastore

After following above steps, definitely it would work as I was facing same issue and then I resolved it.

Hope it helps.

Body:
I try to load files from a partitioned Hive table.

LKR_BU = LOAD 'baseName.tableName' USING org.apache.hive.hcatalog.pig.HCatLoader();

After running I get the following error:

2016-07-04 15:01:58,743 [uber-SubtaskRunner] ERROR org.apache.pig.tools.grunt.Grunt  - ERROR 2245: Cannot get schema from loadFunc org.apache.hive.hcatalog.pig.HCatLoader

For information, I have all the required libraries and HCatalog {Loader, Storer} works perfectly with oozie launcher.

Someone already encountered this kind of problem ?


问:
History back() Method go back twice
Using this sample code as an example:
    Go Back

```<code><script>
function goBack() {
    window.history.back();
}
</script>
</code>```

Then, pressing this button will be the same as pressing the back button once on the browser.

However I would like to have a button that makes the back button pressed twice.
I tried window.history.back(-2); but it doesnt work.
also tried window.history.go(-2); but it doesnt give desired results.
I could have the button link back to the page but the reason why i want it to go back instead is so that previously entered data in a form is preserved.

答:
Now

```<code>window.history.go(-2);
</code>```

works; strange.

Title: History back() Method go back twice

Body:
Using this sample code as an example:
    Go Back

Then, pressing this button will be the same as pressing the back button once on the browser.

However I would like to have a button that makes the back button pressed twice.
I tried window.history.back(-2); but it doesnt work.
also tried window.history.go(-2); but it doesnt give desired results.
I could have the button link back to the page but the reason why i want it to go back instead is so that previously entered data in a form is preserved.

Body:
Now

window.history.go(-2);

works; strange.


问:
How to manually set p and q in tbats() in r?
I am using the tbats() function in r to create a forecasting model.

I was wondering if anyone knew how to manually pass the ARMA(p,q) directly into the tbats() function?

edit: I apologize if the question was vague. In the docs for the package, the following argument explanation is printed:

"Additional arguments to be passed to auto.arima when choose an ARMA(p, q) model for the errors. (Note that xreg will be ignored, as will any arguments concerning seasonality and differencing, but arguments controlling the values of p and q will be used.)"

It clearly states that manually controlling the ARMA(p,q) can be done with an argument passed directly into the tbats() function. Does anyone know how to do this?

https://www.rdocumentation.org/packages/forecast/versions/7.3/topics/tbats

答:
Shortly, you cannot.

tbats is a hybrid algorithm so you should not try to think about building an ARMA model with it. The tbats function does the applying of the arma error terms automatically by the boolean parameter use.arma.errors=TRUE/FALSE, this tries to model better the residuals.

If you want to build an ARIMA model, you can use the auto.arima from forecast package.

Example about auto.arima

```<code>auto.arima(USJudgeRatings[,1], ic='aicc', stepwise=FALSE, start.p=3, start.q=1, max.p=3, max.q=3)
</code>```

Example about tbats

```<code>omega<-USJudgeRatings[,1];p<-10; q<-2; phi<-3;
tbats(omega, p,q, phi,use.arma.errors=TRUE)
BATS(0, {0,0}, 0.979, -)

Call: tbats(y = omega, use.box.cox = p, use.trend = q, use.damped.trend = phi,
    use.arma.errors = TRUE)

Parameters
  Lambda: 0
  Alpha: -0.04239053
  Beta: 0.04362955
  Damping Parameter: 0.978616

Seed States:
         [,1]
[1,] 1.917976
[2,] 0.017468

Sigma: 0.1206409
AIC: 163.774
</code>```

where my parameters p, q and phi stand for use.box.cox, use.trend and use.damped.trend.

Further Information

There is an excellent demonstration about using the different models of forecast package here.

Definition of Tbats is the following:

[Tbats] time series decomposition model consists of decomposing a time
  series into trend, seasonal, cyclical, and irregular components.  Then
  each component is explicitly estimated and measured statistically.
  Each estimated component is then recombined in order to estimate a
  final model and calculate predictions going forward.  A BATS model
  will then incorporate additional autoregressive and moving average
  components (p, q) to better model any leftover patterns presented in
  the model residuals. (Source)

Body:
Shortly, you cannot.

tbats is a hybrid algorithm so you should not try to think about building an ARMA model with it. The tbats function does the applying of the arma error terms automatically by the boolean parameter use.arma.errors=TRUE/FALSE, this tries to model better the residuals.

If you want to build an ARIMA model, you can use the auto.arima from forecast package.

Example about auto.arima

auto.arima(USJudgeRatings[,1], ic='aicc', stepwise=FALSE, start.p=3, start.q=1, max.p=3, max.q=3)

Example about tbats

omega<-USJudgeRatings[,1];p<-10; q<-2; phi<-3;
tbats(omega, p,q, phi,use.arma.errors=TRUE)
BATS(0, {0,0}, 0.979, -)

Call: tbats(y = omega, use.box.cox = p, use.trend = q, use.damped.trend = phi,
    use.arma.errors = TRUE)

Parameters
  Lambda: 0
  Alpha: -0.04239053
  Beta: 0.04362955
  Damping Parameter: 0.978616

Seed States:
         [,1]
[1,] 1.917976
[2,] 0.017468

Sigma: 0.1206409
AIC: 163.774

where my parameters p, q and phi stand for use.box.cox, use.trend and use.damped.trend.

Further Information

There is an excellent demonstration about using the different models of forecast package here.

Definition of Tbats is the following:

[Tbats] time series decomposition model consists of decomposing a time
  series into trend, seasonal, cyclical, and irregular components.  Then
  each component is explicitly estimated and measured statistically.
  Each estimated component is then recombined in order to estimate a
  final model and calculate predictions going forward.  A BATS model
  will then incorporate additional autoregressive and moving average
  components (p, q) to better model any leftover patterns presented in
  the model residuals. (Source)


问:
ESP8266 crashes when PubSubClient set mqttserver
I'm using NodeMCU (ESP12E) controlled using  pubsubclient library.
NodeMCU is crashed when i call
 client.setServer(mqtt_server, 1883);

Message:

```<code>Exception (28):
    epc1=0x4000bf80 epc2=0x00000000 epc3=0x00000000 excvaddr=0x0000096c depc=0x00000000
</code>```

It seems setServer action conflicting with ESP8266WebServer.

I tried: this but the problem is not resolved.

This is my code:

```<code>#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <EEPROM.h>
#include <ESP8266WebServer.h>

// Khởi tạo biến toàn cục
const char* mqtt_server = "iot.eclipse.org";

WiFiClient espClient;
PubSubClient client;
ESP8266WebServer *server;
void setup() {
  EEPROM.begin(512);
  Serial.begin(9600);
  //I tried this
  server = new (ESP8266WebServer);
  //Check wifi, if failed -> run as web server
  if (!setup_wifi()) {
    wifiStartServerMode();
  }

  //.....Some function to get username and password from EEPROM

  // Call back-end using new local WiFiClient
  //  String serverResponse = registerDevice(mac, username, userpassword, 3);
  //If ok, serser response this:
  String serverResponse = "null;null;root/phan/abc";
  if (serverResponse.indexOf(';') > 0) {
    Serial.println("start mqtt client");
    client.setClient(espClient);

    ////////////////
    //CRASHED HERE//
    ///////////////
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
    String tempTopic = getValue(serverResponse, ';', 2);
    for (int i = 0; i < tempTopic.length(); i++) {
      topic += tempTopic[i];
    }
    //Đăng ký nhận tín hiệu
    client.subscribe(topic);
    errConnect2BackEnd = false;
    stConnectBroker = true;
  } else if (serverResponse.equals("failed")) {//Không thể kết nối server
    Serial.println("Can't connect to server");
    //TODO: Báo lỗi, không kết nối server
  } else {
    Serial.print("Error: ");
    Serial.println(serverResponse);
    //TODO: Nhập sai thông tin đăng nhập -> reset để nhập lại (nhấn nút, xóa EEPROM)
  }
  Serial.println("End of setup");

}
</code>```

Function start run server in loop and stop when it's done

```<code>  //-> run as web server

  void wifiStartServerMode() {
  //Active AP_ST_MODE
  setupAP_STA_Mode();
  //Run server->handleClient(); in loop
  viewRunConfig();
  server->stop();
  server->close();
  delay(100);
  delete(server);
  setup_Station_Mode();
}
</code>```

When function "wifiStartServerMode" not run, it still crash.

What could be the problem?

答:
If your algorithm is right. Please check pointer.....and move others files.
It seems bug of Arduino IDE, when i copy this functions, code to other files.
It works.

Body:
I'm using NodeMCU (ESP12E) controlled using  pubsubclient library.
NodeMCU is crashed when i call
 client.setServer(mqtt_server, 1883);

Message:

Exception (28):
    epc1=0x4000bf80 epc2=0x00000000 epc3=0x00000000 excvaddr=0x0000096c depc=0x00000000

It seems setServer action conflicting with ESP8266WebServer.

I tried: this but the problem is not resolved.

This is my code:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <EEPROM.h>
#include <ESP8266WebServer.h>

// Khởi tạo biến toàn cục
const char* mqtt_server = "iot.eclipse.org";

WiFiClient espClient;
PubSubClient client;
ESP8266WebServer *server;
void setup() {
  EEPROM.begin(512);
  Serial.begin(9600);
  //I tried this
  server = new (ESP8266WebServer);
  //Check wifi, if failed -> run as web server
  if (!setup_wifi()) {
    wifiStartServerMode();
  }

  //.....Some function to get username and password from EEPROM

  // Call back-end using new local WiFiClient
  //  String serverResponse = registerDevice(mac, username, userpassword, 3);
  //If ok, serser response this:
  String serverResponse = "null;null;root/phan/abc";
  if (serverResponse.indexOf(';') > 0) {
    Serial.println("start mqtt client");
    client.setClient(espClient);

    ////////////////
    //CRASHED HERE//
    ///////////////
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
    String tempTopic = getValue(serverResponse, ';', 2);
    for (int i = 0; i < tempTopic.length(); i++) {
      topic += tempTopic[i];
    }
    //Đăng ký nhận tín hiệu
    client.subscribe(topic);
    errConnect2BackEnd = false;
    stConnectBroker = true;
  } else if (serverResponse.equals("failed")) {//Không thể kết nối server
    Serial.println("Can't connect to server");
    //TODO: Báo lỗi, không kết nối server
  } else {
    Serial.print("Error: ");
    Serial.println(serverResponse);
    //TODO: Nhập sai thông tin đăng nhập -> reset để nhập lại (nhấn nút, xóa EEPROM)
  }
  Serial.println("End of setup");

}

Function start run server in loop and stop when it's done

  //-> run as web server

  void wifiStartServerMode() {
  //Active AP_ST_MODE
  setupAP_STA_Mode();
  //Run server->handleClient(); in loop
  viewRunConfig();
  server->stop();
  server->close();
  delay(100);
  delete(server);
  setup_Station_Mode();
}

When function "wifiStartServerMode" not run, it still crash.

What could be the problem?


问:
Labels for tooltips on primefaces barchartseries
I have tried to search both the forum and Google extensively, but I have problems understanding how I should make this work:

PrimeFaces6

I have a BarchartModel based on the tutorial in the ShowCase:
CODE: SELECT ALL
private BarChartModel initStatusBarChart() {
        BarChartModel model = new BarChartModel();

```<code>    ChartSeries statusMessages = new ChartSeries();
    statusMessages.setLabel("Label"));
    statusMessages.set("Some String 1", list1.size());
    statusMessages.set("Some String 2", list2.size());

    model.addSeries(statusMessages);
    return model;
}
</code>```

The issue is that on render, I get tooltips the format of

"1, 515" and "2, 432", where 515 and 432 are the sizes of list1 and list2, respectively.

How can I replace 1 and 2 with the values "Some String" 1 and 2 ? Have tried extending highlighter and using dataTipFormat, with no success.

答:
I solved the problem using the datatip editor of the chart model (with Primefaces 6.1, by the way). I used this for a stacked bar chart.
I needed to apply this solution at two places: the backing bean and the JSF page.

In the backing bean I had to set a JavaScript function name this way:

```<code>barModel.setDatatipEditor("chartDatatipEditor");
</code>```

I tried to set it using the corresponding tag attribute in the JSF page but to no effect.

In the JSF I inserted this JavaScript code:

```<code><script type="text/javascript">
function chartDatatipEditor(str, seriesIndex, pointIndex, plot) {
  //console.log('chartDatatipEditor: '+str+" - "+seriesIndex+" - "+pointIndex);
  var point = seriesIndex+','+pointIndex;
  #{bean.datatipsJs}
}
</script>
</code>```

This JS function gets the chart coordinates as parameters. I concat them so that the following JS code gets easier.
seriesIndex is the index of the chart series. pointIndex is the index on the X scale of the diagram.

To find out what are the correct values for your chart you can uncomment the console.log line above.

The inserted JS code is constructed in the backing bean this way:

```<code>private Map<String, String> chartDatatips;

public String getDatatipsJs() {
    StringBuilder sb = new StringBuilder("switch ( point ) {\n");
    for (String point : chartDatatips.keySet()) {
        sb.append("case '").append(point).append("': return '").append(chartDatatips.get(point)).append("'; break;\n");
    }
    sb.append("default: return 'Unknown point'; break; }");
    return sb.toString();
}
</code>```

The map chartDatatips has the coordinate point as key (e.g., "2,1") and the tooltip as value.

During the chart setup you obviously have to fill this map with useful details ;-)

Like this:

```<code>chartDatatips.put("2,5", "Label ...");
...
</code>```

Hope this helps, if you didn't already solved this.

~Alex

Body:
I have tried to search both the forum and Google extensively, but I have problems understanding how I should make this work:

PrimeFaces6

I have a BarchartModel based on the tutorial in the ShowCase:
CODE: SELECT ALL
private BarChartModel initStatusBarChart() {
        BarChartModel model = new BarChartModel();

    ChartSeries statusMessages = new ChartSeries();
    statusMessages.setLabel("Label"));
    statusMessages.set("Some String 1", list1.size());
    statusMessages.set("Some String 2", list2.size());

    model.addSeries(statusMessages);
    return model;
}

The issue is that on render, I get tooltips the format of

"1, 515" and "2, 432", where 515 and 432 are the sizes of list1 and list2, respectively.

How can I replace 1 and 2 with the values "Some String" 1 and 2 ? Have tried extending highlighter and using dataTipFormat, with no success.

Body:
I solved the problem using the datatip editor of the chart model (with Primefaces 6.1, by the way). I used this for a stacked bar chart.
I needed to apply this solution at two places: the backing bean and the JSF page.

In the backing bean I had to set a JavaScript function name this way:

barModel.setDatatipEditor("chartDatatipEditor");

I tried to set it using the corresponding tag attribute in the JSF page but to no effect.

In the JSF I inserted this JavaScript code:

<script type="text/javascript">
function chartDatatipEditor(str, seriesIndex, pointIndex, plot) {
  //console.log('chartDatatipEditor: '+str+" - "+seriesIndex+" - "+pointIndex);
  var point = seriesIndex+','+pointIndex;
  #{bean.datatipsJs}
}
</script>

This JS function gets the chart coordinates as parameters. I concat them so that the following JS code gets easier.
seriesIndex is the index of the chart series. pointIndex is the index on the X scale of the diagram.

To find out what are the correct values for your chart you can uncomment the console.log line above.

The inserted JS code is constructed in the backing bean this way:

private Map<String, String> chartDatatips;

public String getDatatipsJs() {
    StringBuilder sb = new StringBuilder("switch ( point ) {\n");
    for (String point : chartDatatips.keySet()) {
        sb.append("case '").append(point).append("': return '").append(chartDatatips.get(point)).append("'; break;\n");
    }
    sb.append("default: return 'Unknown point'; break; }");
    return sb.toString();
}

The map chartDatatips has the coordinate point as key (e.g., "2,1") and the tooltip as value.

During the chart setup you obviously have to fill this map with useful details ;-)

Like this:

chartDatatips.put("2,5", "Label ...");
...

Hope this helps, if you didn't already solved this.

~Alex


问:
Forcing flexbox element to float right
I'm currently working on responsiveness on my website and I hit the wall. On smaller resolutions I changed the flex-direction to column from row, changed the ordering of flex elements, changed the main textbox width to 100% and sideboxes to 50%.

Code looks like this:

```<code><section class="about" id="ABOUT">
    <div class="about-sidebox l">
    </div>

    <div class="about-mainbox">
    </div>

    <div class="about-sidebox r">
    </div>
</section>
</code>```

As you can see the sideboxes are not within the container. Putting them in container helps but completely ruins my previous layout.

CSS for wanted resolution is:

```<code>.about {
    flex-direction: column;
}

.about-mainbox {
    order: 1;
}

.about-sidebox {
    order: 2;
    width: 50%;
    flex-wrap: wrap;
}
</code>```

Effect is like this:

As you can see I want the sideboxes to be next to each other. Any solution I can't think of without adding additional container?

答:
The simplest possible is to do this;

Set the about to flex-wrap: wrap so its flex items can wrap, skip flex-direction so it uses its default row

Set the mainbox to order: -1 (default is 0), which will position it before the sidebox's, and flex-basis: 100%, which will make it take full width and by doing that, it pushes the sidebox's to a new line

Give the sidebox's flex-basis: 50% to be equally wide, and min-width: 0; so they stay side-by-side (if you wan't them to wrap and stack vertical when their content force's them to, drop this, or control it with a set width, i.e. min-width: 150px;)

I also recommend you use Flexbox's own properties, i.e. in this case flex-basis instead of width

.about {
  display: flex;
  flex-wrap: wrap;
}

.about-mainbox {
  flex-basis: 100%;
  order: -1;
}

.about-sidebox {
  flex-basis: 50%;
  min-width: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="about" id="ABOUT">

  <div class="about-sidebox l">Left
  </div>

  <div class="about-mainbox">Main
  </div>

  <div class="about-sidebox r">Right
  </div>

</section></code>```

Title: Forcing flexbox element to float right

Body:
I'm currently working on responsiveness on my website and I hit the wall. On smaller resolutions I changed the flex-direction to column from row, changed the ordering of flex elements, changed the main textbox width to 100% and sideboxes to 50%.

Code looks like this:

As you can see the sideboxes are not within the container. Putting them in container helps but completely ruins my previous layout.

CSS for wanted resolution is:

.about {
    flex-direction: column;
}

.about-mainbox {
    order: 1;
}

.about-sidebox {
    order: 2;
    width: 50%;
    flex-wrap: wrap;
}

Effect is like this:

As you can see I want the sideboxes to be next to each other. Any solution I can't think of without adding additional container?

Body:
The simplest possible is to do this;

Set the about to flex-wrap: wrap so its flex items can wrap, skip flex-direction so it uses its default row

Set the mainbox to order: -1 (default is 0), which will position it before the sidebox's, and flex-basis: 100%, which will make it take full width and by doing that, it pushes the sidebox's to a new line

Give the sidebox's flex-basis: 50% to be equally wide, and min-width: 0; so they stay side-by-side (if you wan't them to wrap and stack vertical when their content force's them to, drop this, or control it with a set width, i.e. min-width: 150px;)

I also recommend you use Flexbox's own properties, i.e. in this case flex-basis instead of width

.about {
  display: flex;
  flex-wrap: wrap;
}

.about-mainbox {
  flex-basis: 100%;
  order: -1;
}

.about-sidebox {
  flex-basis: 50%;
  min-width: 0;
}

<section class="about" id="ABOUT">

  <div class="about-sidebox l">Left
  </div>

  <div class="about-mainbox">Main
  </div>

  <div class="about-sidebox r">Right
  </div>

</section>


问:
XSLT Confusion with xsl:apply-templates
I have an XML file with this format:

```<code><?xml version="1.0" encoding="utf-8" ?>
<OpacResult>
<valueObjects class="list">
    <Catalog>
        <notes>
            Daily newsletter available via e-mail.
            IP authenticated. Login not needed within firm.
        </notes>
        <title>Health law360. </title>
        <url>http://health.law360.com/</url>
        <catalogTitles class="list">
            <CatalogTitle>
                <uuid>e5e2bc53ac1001f808cddc29f93ecad8</uuid>
                <timeChanged class="sql-timestamp">2010-12-14 09:17:10.707</timeChanged>
                <timeEntered class="sql-timestamp">2010-12-14 09:17:10.707</timeEntered>
                <whoChanged>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoChanged>
                <whoEntered>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoEntered>
                <updateSearchIndex>true</updateSearchIndex>
                <corpId>RopesGray</corpId>
                <catalogUuid>a20b6b4bac1001f86d28280ed0ebeb9e</catalogUuid>
                <type>O</type>
                <title>Law 360. Health law.</title>
            </CatalogTitle>
            <CatalogTitle>
                <uuid>e5e2bc53ac1001f808cddc299ddfe49d</uuid>
                <timeChanged class="sql-timestamp">2010-12-14 09:17:10.707</timeChanged>
                <timeEntered class="sql-timestamp">2010-12-14 09:17:10.707</timeEntered>
                <whoChanged>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoChanged>
                <whoEntered>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoEntered>
                <updateSearchIndex>true</updateSearchIndex>
                <corpId>RopesGray</corpId>
                <catalogUuid>a20b6b4bac1001f86d28280ed0ebeb9e</catalogUuid>
                <type>O</type>
                <title>Health law 360</title>
            </CatalogTitle>
            <CatalogTitle>
                <uuid>e5e2bc53ac1001f808cddc29ec1d959b</uuid>
                <timeChanged class="sql-timestamp">2010-12-14 09:17:10.707</timeChanged>
                <timeEntered class="sql-timestamp">2010-12-14 09:17:10.707</timeEntered>
                <whoChanged>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoChanged>
                <whoEntered>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoEntered>
                <updateSearchIndex>true</updateSearchIndex>
                <corpId>RopesGray</corpId>
                <catalogUuid>a20b6b4bac1001f86d28280ed0ebeb9e</catalogUuid>
                <type>O</type>
                <title>Health law three hundred sixty</title>
            </CatalogTitle>
        </catalogTitles>
        <catalogUrls class="list"/>
        <gmd>
            <uuid>f8f123acc0a816070192e296a6a71715</uuid>
            <timeChanged class="sql-timestamp">2006-10-10 15:23:37.813</timeChanged>
            <timeEntered class="sql-timestamp">2005-01-27 00:00:00.0</timeEntered>
            <whoChanged>25db9fcd3fd247f4a20485b40cc134ad</whoChanged>
            <whoEntered>user</whoEntered>
            <updateSearchIndex>true</updateSearchIndex>
            <corpId>RopesGray</corpId>
            <isRuleDefault>false</isRuleDefault>
            <ruleName>text</ruleName>
            <term>electronic resource</term>
            <preferCollection>false</preferCollection>
            <isTechnicalManual>false</isTechnicalManual>
            <sip2IsMagnetic>false</sip2IsMagnetic>
        </gmd>
        <issues class="list"/>
    </Catalog>
</valueObjects>
</OpacResult>
</code>```

As you can see, there are other  elements under sibling nodes, but I don't care about these and only want to see the first one.

I'm using this code to call a template with the string of desired elements as the parameter
and a template to loop through the asterisk-delimited string parameter: (title*url*notes*)

```<code><?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="columns" />
<xsl:template match="/OpacResult/valueObjects">
    <html>
        <body>
            <table border="1">

                <!-- Header row -->
                <tr>
                    <xsl:call-template name="print-headers">
                        <xsl:with-param name="columns" select="$columns"/>
                    </xsl:call-template>
                </tr>

                <!-- Value rows -->
                <xsl:for-each select="Catalog">
                    <tr>
                        <xsl:call-template name="print-values">
                            <xsl:with-param name="columns" select="$columns"/>
                        </xsl:call-template>
                    </tr>
                </xsl:for-each>
            </table>
        </body>
    </html>
</xsl:template>

<!-- Split up string of column names and create header field names based on element names-->
<xsl:template name="print-headers">
    <xsl:param name="columns"/>

    <xsl:variable name="newList" select="$columns"/>
    <xsl:variable name="first" select="substring-before($newList, '*')" />
    <xsl:variable name="remaining" select="substring-after($newList, '*')" />

    <th>
        <xsl:apply-templates select="Catalog/*[name()=$first]">
            <xsl:with-param name="header">true</xsl:with-param>
        </xsl:apply-templates>
    </th>

    <xsl:if test="$remaining">
        <xsl:call-template name="print-headers">
            <xsl:with-param name="columns" select="$remaining"/>
        </xsl:call-template>
    </xsl:if>

</xsl:template>

<xsl:template name="print-values">
    <xsl:param name="columns"/>

    <xsl:variable name="newList" select="$columns"/>
    <xsl:variable name="first" select="substring-before($newList, '*')" />
    <xsl:variable name="remaining" select="substring-after($newList, '*')" />

    <td>
        <xsl:apply-templates select="Catalog/*[name()=$first]"/>
    </td>

    <xsl:if test="$remaining">
        <xsl:call-template name="print-values">
            <xsl:with-param name="columns" select="$remaining"/>
        </xsl:call-template>
    </xsl:if>

</xsl:template>

<xsl:template match="title">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>Title</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <a>
                <xsl:attribute name="href">
                    <xsl:value-of select="//*[name()='url']"/>
                </xsl:attribute>
                <xsl:value-of select="//*[name()='title']"/>
            </a>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="url">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>URL</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <a>
                <xsl:attribute name="href">
                    <xsl:value-of select="//*[name()='url']"/>
                </xsl:attribute>
                <xsl:value-of select="//*[name()='url']"/>
            </a>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="notes">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>Notes</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="//*[name()='notes']"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="holdingNotes">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>Holding Notes</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="//*[name()='holdingNotes']"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="relatedUrl">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>Related URL</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="//*[name()='relatedUrl']"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="bibliographicType/hasDataFile">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>File</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="Catalog/*[name()='hasDataFile']"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

The only way I can access this template is to use the //*[name()=$first] syntax to extract the value of the element based on the name from the $first parameter.

Any help is greatly appreciated.  Thanks very much in advance.  Not including the full XML as there are thousands of lines of unnecessary text.

答:
This stylesheet:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:h="header"
 exclude-result-prefixes="h">
    <h:h>
        <title>Title</title>
        <url>URL</url>
        <notes>Notes</notes>
    </h:h>
    <xsl:param name="pColumns" select="'title url notes'"/>
    <xsl:template match="/OpacResult/valueObjects">
        <html>
            <body>
                <table border="1">
                    <tr>
                        <xsl:apply-templates
                             select="document('')/*/h:h"
                             mode="filter"/>
                    </tr>
                    <xsl:apply-templates/>
                </table>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="Catalog">
        <tr>
            <xsl:call-template name="filter"/>
        </tr>
    </xsl:template>
    <xsl:template match="h:h/*">
        <th>
            <xsl:value-of select="."/>
        </th>
    </xsl:template>
    <xsl:template match="Catalog/*">
        <td>
            <xsl:value-of select="."/>
        </td>
    </xsl:template>
    <xsl:template match="node()" mode="filter" name="filter">
        <xsl:apply-templates select="*[contains(
                                          concat(' ',$pColumns,' '),
                                          concat(' ',name(),' '))]">
            <xsl:sort select="substring-before(
                                 concat(' ',$pColumns,' '),
                                 concat(' ',name(),' '))"/>
        </xsl:apply-templates>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output:

```<code><html>
    <body>
        <table border="1">
            <tr>
                <th>Title</th>
                <th>URL</th>
                <th>Notes</th>
            </tr>
            <tr>
                <td>Health law360. </td>
                <td>http://health.law360.com/</td>
                <td>             Daily newsletter available via e-mail.
             IP authenticated. Login not needed within firm.         </td>
            </tr>
        </table>
    </body>
</html>
</code>```

Note: Inline data for headers, pseudo sequence parameter for filtering and sorting, modes not for processing the same element in different way but for processing different elements in the same way also.

Title: XSLT Confusion with xsl:apply-templates

Body:
I have an XML file with this format:

<?xml version="1.0" encoding="utf-8" ?>
<OpacResult>
<valueObjects class="list">
    <Catalog>
        <notes>
            Daily newsletter available via e-mail.
            IP authenticated. Login not needed within firm.
        </notes>
        <title>Health law360. </title>
        <url>http://health.law360.com/</url>
        <catalogTitles class="list">
            <CatalogTitle>
                <uuid>e5e2bc53ac1001f808cddc29f93ecad8</uuid>
                <timeChanged class="sql-timestamp">2010-12-14 09:17:10.707</timeChanged>
                <timeEntered class="sql-timestamp">2010-12-14 09:17:10.707</timeEntered>
                <whoChanged>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoChanged>
                <whoEntered>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoEntered>
                <updateSearchIndex>true</updateSearchIndex>
                <corpId>RopesGray</corpId>
                <catalogUuid>a20b6b4bac1001f86d28280ed0ebeb9e</catalogUuid>
                <type>O</type>
                <title>Law 360. Health law.</title>
            </CatalogTitle>
            <CatalogTitle>
                <uuid>e5e2bc53ac1001f808cddc299ddfe49d</uuid>
                <timeChanged class="sql-timestamp">2010-12-14 09:17:10.707</timeChanged>
                <timeEntered class="sql-timestamp">2010-12-14 09:17:10.707</timeEntered>
                <whoChanged>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoChanged>
                <whoEntered>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoEntered>
                <updateSearchIndex>true</updateSearchIndex>
                <corpId>RopesGray</corpId>
                <catalogUuid>a20b6b4bac1001f86d28280ed0ebeb9e</catalogUuid>
                <type>O</type>
                <title>Health law 360</title>
            </CatalogTitle>
            <CatalogTitle>
                <uuid>e5e2bc53ac1001f808cddc29ec1d959b</uuid>
                <timeChanged class="sql-timestamp">2010-12-14 09:17:10.707</timeChanged>
                <timeEntered class="sql-timestamp">2010-12-14 09:17:10.707</timeEntered>
                <whoChanged>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoChanged>
                <whoEntered>B23DE2FFE8DD49B0B0A03D1FEB3E7DA2</whoEntered>
                <updateSearchIndex>true</updateSearchIndex>
                <corpId>RopesGray</corpId>
                <catalogUuid>a20b6b4bac1001f86d28280ed0ebeb9e</catalogUuid>
                <type>O</type>
                <title>Health law three hundred sixty</title>
            </CatalogTitle>
        </catalogTitles>
        <catalogUrls class="list"/>
        <gmd>
            <uuid>f8f123acc0a816070192e296a6a71715</uuid>
            <timeChanged class="sql-timestamp">2006-10-10 15:23:37.813</timeChanged>
            <timeEntered class="sql-timestamp">2005-01-27 00:00:00.0</timeEntered>
            <whoChanged>25db9fcd3fd247f4a20485b40cc134ad</whoChanged>
            <whoEntered>user</whoEntered>
            <updateSearchIndex>true</updateSearchIndex>
            <corpId>RopesGray</corpId>
            <isRuleDefault>false</isRuleDefault>
            <ruleName>text</ruleName>
            <term>electronic resource</term>
            <preferCollection>false</preferCollection>
            <isTechnicalManual>false</isTechnicalManual>
            <sip2IsMagnetic>false</sip2IsMagnetic>
        </gmd>
        <issues class="list"/>
    </Catalog>
</valueObjects>
</OpacResult>

As you can see, there are other  elements under sibling nodes, but I don't care about these and only want to see the first one.

I'm using this code to call a template with the string of desired elements as the parameter
and a template to loop through the asterisk-delimited string parameter: (title*url*notes*)

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="columns" />
<xsl:template match="/OpacResult/valueObjects">

                    <xsl:call-template name="print-headers">
                        <xsl:with-param name="columns" select="$columns"/>
                    </xsl:call-template>

                <xsl:for-each select="Catalog">

                        <xsl:call-template name="print-values">
                            <xsl:with-param name="columns" select="$columns"/>
                        </xsl:call-template>

                </xsl:for-each>

</xsl:template>

<xsl:template name="print-headers">
    <xsl:param name="columns"/>

    <xsl:variable name="newList" select="$columns"/>
    <xsl:variable name="first" select="substring-before($newList, '*')" />
    <xsl:variable name="remaining" select="substring-after($newList, '*')" />

        <xsl:apply-templates select="Catalog/*[name()=$first]">
            <xsl:with-param name="header">true</xsl:with-param>
        </xsl:apply-templates>

    <xsl:if test="$remaining">
        <xsl:call-template name="print-headers">
            <xsl:with-param name="columns" select="$remaining"/>
        </xsl:call-template>
    </xsl:if>

</xsl:template>

<xsl:template name="print-values">
    <xsl:param name="columns"/>

    <xsl:variable name="newList" select="$columns"/>
    <xsl:variable name="first" select="substring-before($newList, '*')" />
    <xsl:variable name="remaining" select="substring-after($newList, '*')" />

        <xsl:apply-templates select="Catalog/*[name()=$first]"/>

    <xsl:if test="$remaining">
        <xsl:call-template name="print-values">
            <xsl:with-param name="columns" select="$remaining"/>
        </xsl:call-template>
    </xsl:if>

</xsl:template>

<xsl:template match="title">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>Title</xsl:text>
        </xsl:when>
        <xsl:otherwise>

                <xsl:attribute name="href">
                    <xsl:value-of select="//*[name()='url']"/>
                </xsl:attribute>
                <xsl:value-of select="//*[name()='title']"/>

        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="url">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>URL</xsl:text>
        </xsl:when>
        <xsl:otherwise>

                <xsl:attribute name="href">
                    <xsl:value-of select="//*[name()='url']"/>
                </xsl:attribute>
                <xsl:value-of select="//*[name()='url']"/>

        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="notes">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>Notes</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="//*[name()='notes']"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="holdingNotes">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>Holding Notes</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="//*[name()='holdingNotes']"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="relatedUrl">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>Related URL</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="//*[name()='relatedUrl']"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="bibliographicType/hasDataFile">
    <xsl:param name="header"/>

    <xsl:choose>
        <xsl:when test="$header='true'">
            <xsl:text>File</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="Catalog/*[name()='hasDataFile']"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

The only way I can access this template is to use the //*[name()=$first] syntax to extract the value of the element based on the name from the $first parameter.

Any help is greatly appreciated.  Thanks very much in advance.  Not including the full XML as there are thousands of lines of unnecessary text.

Body:
This stylesheet:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:h="header"
 exclude-result-prefixes="h">
    <h:h>
        <title>Title</title>
        <url>URL</url>
        <notes>Notes</notes>
    </h:h>
    <xsl:param name="pColumns" select="'title url notes'"/>
    <xsl:template match="/OpacResult/valueObjects">
        <html>
            <body>
                <table border="1">
                    <tr>
                        <xsl:apply-templates
                             select="document('')/*/h:h"
                             mode="filter"/>
                    </tr>
                    <xsl:apply-templates/>
                </table>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="Catalog">
        <tr>
            <xsl:call-template name="filter"/>
        </tr>
    </xsl:template>
    <xsl:template match="h:h/*">
        <th>
            <xsl:value-of select="."/>
        </th>
    </xsl:template>
    <xsl:template match="Catalog/*">
        <td>
            <xsl:value-of select="."/>
        </td>
    </xsl:template>
    <xsl:template match="node()" mode="filter" name="filter">
        <xsl:apply-templates select="*[contains(
                                          concat(' ',$pColumns,' '),
                                          concat(' ',name(),' '))]">
            <xsl:sort select="substring-before(
                                 concat(' ',$pColumns,' '),
                                 concat(' ',name(),' '))"/>
        </xsl:apply-templates>
    </xsl:template>
</xsl:stylesheet>

Output:

<html>
    <body>
        <table border="1">
            <tr>
                <th>Title</th>
                <th>URL</th>
                <th>Notes</th>
            </tr>
            <tr>
                <td>Health law360. </td>
                <td>http://health.law360.com/</td>
                <td>             Daily newsletter available via e-mail.
             IP authenticated. Login not needed within firm.         </td>
            </tr>
        </table>
    </body>
</html>

Note: Inline data for headers, pseudo sequence parameter for filtering and sorting, modes not for processing the same element in different way but for processing different elements in the same way also.


问:
Generic Methods, how to call a parent method without specifying a type
I have this parent class

```<code>public abstract class Parent
{
    public string Id { get; set; }

    public static T Find<T>(string id) where T : class, new()
    {
        /* logic here ..*/
    }
}
</code>```

and this child

```<code>public class Child : Parent
{
    public string Name { get; set; }
}
</code>```

Right now, the Find() method can be called from child class like this Child.Find<Child>(myId);

What I need to change so it doesnt have to include class type like this Child.Find(myId);

EDIT

I want to make this method as extension, and get it directly without defining the class into variable. the generic classT should be it's child type.

答:
Do you mean something like this:

```<code>public abstract class Parent
{
    public string Id { get; set; }

    public static Parent Find(string id)
    {
        /* logic here ..*/
    }
}
</code>```

This way you would have to cast the output to the correct type of derived class. For example:

```<code>if(Parent.Find("123") is Child child)
{
   child.Name = "TEST";
}
</code>```

EDIT

Hide the inherited member and define a new one:

```<code>    public abstract class Parent
    {
        public string Id { get; set; }

        public static Parent Find(string id)
        {
            /* logic here ..*/
        }
    }

    public class Child : Parent
    {
        public string Name { get; set; }

        public new static Child Find(string id)
        {
            /* logic here */
        }
    }
</code>```

Body:
I have this parent class

public abstract class Parent
{
    public string Id { get; set; }

    public static T Find<T>(string id) where T : class, new()
    {
        /* logic here ..*/
    }
}

and this child

public class Child : Parent
{
    public string Name { get; set; }
}

Right now, the Find() method can be called from child class like this Child.Find<Child>(myId);

What I need to change so it doesnt have to include class type like this Child.Find(myId);

EDIT

I want to make this method as extension, and get it directly without defining the class into variable. the generic classT should be it's child type.

Body:
Do you mean something like this:

public abstract class Parent
{
    public string Id { get; set; }

    public static Parent Find(string id)
    {
        /* logic here ..*/
    }
}

This way you would have to cast the output to the correct type of derived class. For example:

if(Parent.Find("123") is Child child)
{
   child.Name = "TEST";
}

EDIT

Hide the inherited member and define a new one:

    public abstract class Parent
    {
        public string Id { get; set; }

        public static Parent Find(string id)
        {
            /* logic here ..*/
        }
    }

    public class Child : Parent
    {
        public string Name { get; set; }

        public new static Child Find(string id)
        {
            /* logic here */
        }
    }


问:
Read all SMS from a particular sender
How do I read all SMSes from a particular sender to me? E.g. I want to scan a) the body, and b) the date/time of all SMSes that came from 'TM-MYAMEX' to the phone.

Some websites seem to indicate this can be read from "content://sms/inbox". I couldn't figure out exactly how. Also not sure if it is supported on most phones. I am using a Galaxy S2.

答:
try this, its a easy way for reading message from inbox.

```<code>public class ReadMsg extends AppCompatActivity {

ListView listView;
private static final int PERMISSION_REQUEST_READ_CONTACTS = 100;
ArrayList smsList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_msg);
    listView = (ListView)findViewById(R.id.idList);

    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);

    if (permissionCheck == PackageManager.PERMISSION_GRANTED){
        showContacts();
    }else{
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},PERMISSION_REQUEST_READ_CONTACTS);
    }
}

private void showContacts() {
    Uri inboxURI = Uri.parse("content://sms/inbox");
    smsList = new ArrayList();
    ContentResolver cr = getContentResolver();

    Cursor c = cr.query(inboxURI,null,null,null,null);
    while (c.moveToNext()){
        String Number = c.getString(c.getColumnIndexOrThrow("address")).toString();
        String Body= c.getString(c.getColumnIndexOrThrow("body")).toString();
        smsList.add("Number: "+ Number + "\n" + "Body: "+ Body );
    }
        c.close();
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, smsList);
    listView.setAdapter(adapter);
}
</code>```

}

Add this permission into Manifests.

```<code><uses-permission android:name="android.permission.READ_SMS"></uses-permission>
</code>```

Title: Read all SMS from a particular sender

Body:
try this, its a easy way for reading message from inbox.

public class ReadMsg extends AppCompatActivity {

ListView listView;
private static final int PERMISSION_REQUEST_READ_CONTACTS = 100;
ArrayList smsList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_msg);
    listView = (ListView)findViewById(R.id.idList);

    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);

    if (permissionCheck == PackageManager.PERMISSION_GRANTED){
        showContacts();
    }else{
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},PERMISSION_REQUEST_READ_CONTACTS);
    }
}

private void showContacts() {
    Uri inboxURI = Uri.parse("content://sms/inbox");
    smsList = new ArrayList();
    ContentResolver cr = getContentResolver();

    Cursor c = cr.query(inboxURI,null,null,null,null);
    while (c.moveToNext()){
        String Number = c.getString(c.getColumnIndexOrThrow("address")).toString();
        String Body= c.getString(c.getColumnIndexOrThrow("body")).toString();
        smsList.add("Number: "+ Number + "\n" + "Body: "+ Body );
    }
        c.close();
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, smsList);
    listView.setAdapter(adapter);
}

}

Add this permission into Manifests.

<uses-permission android:name="android.permission.READ_SMS"></uses-permission>


问:
NavController's push doesn't show Google Maps
I am trying to draw a map when a button is clicked. However, it doesn't seem to work when I use NavController.push(), but only with NavController.setRoot(). I don't get any errors, so I can't figure out what causes this.

This is the class that draws the map:

```<code>declare var google: any;

@Component({
  selector: 'page-Map',
  templateUrl: 'Map.html'
})

export class MapPage {

  public directionsService: any;
  public directionsDisplay: any;
  public directions: any;
  map: any;
  markers = [];

  constructor(private _theme: ThemeService, private shareService: ShareService, public ajaxService: AjaxService) {
    let rendererOptions = { draggable: true };
    this.directionsService = new google.maps.DirectionsService;
    let googleDiplay = new google.maps.DirectionsRenderer(rendererOptions);
    this.directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
    this.initMap();

  }

  //initialises the map
  initMap() {
    var point = { lat: 12.65, lng: 12.5683 };
    let divMap = (<HTMLInputElement>document.getElementById('map'));
    this.map = new google.maps.Map(divMap, {
      center: point,
      zoom: 15,
      disableDefaultUI: true,
      draggable: true,
      zoomControl: true,
    });
    let locationOptions = { timeout: 30000, enableHighAccuracy: true, maximumAge: 0 };

    navigator.geolocation.getCurrentPosition((position) => {
      this.map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    }, (error) => { }, locationOptions);

    //create marker and set to initialised map
    var myLatLng = this.map.getCenter();
    this.directionsDisplay.setMap(this.map);
  }
}
</code>```

This is the HTML:

```<code><ion-header>
    <ion-navbar>
      <ion-title>Location</ion-title>
    </ion-navbar>
  </div>
</ion-header>

<ion-content>
  <div id="map"></div>
</ion-content>
</code>```

答:
Try initializing the map after a platform.ready()

```<code>import { Platform } from 'ionic-angular';

constructor(public platform: Platform){
  // ...ALL YOUR CODE...
  platform.ready().then(() => {
    this.initMap();
  });
}
</code>```

And be sure your map has the size it needs via css

```<code>#map {
  width: 100%;
  height: 100%; // 'auto' might work too
}
</code>```

Body:
I am trying to draw a map when a button is clicked. However, it doesn't seem to work when I use NavController.push(), but only with NavController.setRoot(). I don't get any errors, so I can't figure out what causes this.

This is the class that draws the map:

declare var google: any;

@Component({
  selector: 'page-Map',
  templateUrl: 'Map.html'
})

export class MapPage {

  public directionsService: any;
  public directionsDisplay: any;
  public directions: any;
  map: any;
  markers = [];

  constructor(private _theme: ThemeService, private shareService: ShareService, public ajaxService: AjaxService) {
    let rendererOptions = { draggable: true };
    this.directionsService = new google.maps.DirectionsService;
    let googleDiplay = new google.maps.DirectionsRenderer(rendererOptions);
    this.directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
    this.initMap();

  }

  //initialises the map
  initMap() {
    var point = { lat: 12.65, lng: 12.5683 };
    let divMap = (<HTMLInputElement>document.getElementById('map'));
    this.map = new google.maps.Map(divMap, {
      center: point,
      zoom: 15,
      disableDefaultUI: true,
      draggable: true,
      zoomControl: true,
    });
    let locationOptions = { timeout: 30000, enableHighAccuracy: true, maximumAge: 0 };

    navigator.geolocation.getCurrentPosition((position) => {
      this.map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    }, (error) => { }, locationOptions);

    //create marker and set to initialised map
    var myLatLng = this.map.getCenter();
    this.directionsDisplay.setMap(this.map);
  }
}

This is the HTML:

<ion-header>
    <ion-navbar>
      <ion-title>Location</ion-title>
    </ion-navbar>

</ion-header>

<ion-content>

</ion-content>

Body:
Try initializing the map after a platform.ready()

import { Platform } from 'ionic-angular';

constructor(public platform: Platform){
  // ...ALL YOUR CODE...
  platform.ready().then(() => {
    this.initMap();
  });
}

And be sure your map has the size it needs via css

#map {
  width: 100%;
  height: 100%; // 'auto' might work too
}


问:
How to change already added string column to a Reference in Rails
I've already created a model in Rails to collect some user information

I created the columns as :string initially but I've since changed the way this data is looked up and entered by using separate populated models.

Now instead of entering into these fields as string - i want these columns to be "references" instead.

Is there an easy way to change from the string to reference without having to create a new model entirely?

*do not need to save the existing data

答:
You can create migrations to serve the exact purpose.

```<code>rails generate migration AddAddressToUsers address:references
</code>```

This will create a migration file in db/migrate directory.
Then run: rails db:migrate to run migration and make changes in your database.

Don't forget to create associations in your models (belongs_to, has_many, etc.) depending on your system structure.

Body:
You can create migrations to serve the exact purpose.

rails generate migration AddAddressToUsers address:references

This will create a migration file in db/migrate directory.
Then run: rails db:migrate to run migration and make changes in your database.

Don't forget to create associations in your models (belongs_to, has_many, etc.) depending on your system structure.


问:
How to add column in Dataframe base on the value of other Columns spark
I have a Data-frame with column "Age" of type String,I want to get a new column containing the range in string format

Range as follows

[-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000]

Input Values for example

```<code>Age
=====
-1
12
18
28
38
46
======
</code>```

Output Required

```<code>  Age    Age-Range
 =====  =========
 -1     (-1,12)
 12     (-1,12)
 18     (12-17)
 28     (24-34)
 38     (34-44)
 46     (44-54)
======  ==========
</code>```

Any Suggestion or Help is Highly Appreciated

Body:
I have a Data-frame with column "Age" of type String,I want to get a new column containing the range in string format

Range as follows

[-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000]

Input Values for example

Age
=====
-1
12
18
28
38
46
======

Output Required

  Age    Age-Range
 =====  =========
 -1     (-1,12)
 12     (-1,12)
 18     (12-17)
 28     (24-34)
 38     (34-44)
 46     (44-54)
======  ==========

Any Suggestion or Help is Highly Appreciated

Body:
Here is the simple solution using UDF but you need to manually create a list.

//dataframe with column age
val df = spark.sparkContext.parallelize(Seq("-1", "12", "18", "28", "38", "38", "388", "3", "41")).toDF("Age")

val updateUDF = udf((age : String) => {
  val range = Seq(
    (-1, 12, "(-1 - 12)"),
    (12, 17, "(12 - 17)"),
    (17, 24, "(17 - 24)"),
    (24, 34, "(24 - 34)"),
    (34, 44, "(34 - 44)"),
    (44, 54, "(44 - 54)"),
    (54, 64, "(54 - 64)"),
    (64, 10, "(64 - 100)"),
    (100, 1000, "(100- 1000)")
  )
 range.map( value =>  {
   if (age.toInt >= value._1 && age.toInt < value._2) value._3
  else  ""
 }).filter(!_.equals(""))(0)

})

  df.withColumn("Age-Range", updateUDF($"Age")).show(false)

Here is the output:
+---+-----------+
|Age|Age-Range  |
+---+-----------+
|-1 |(-1 - 12)  |
|12 |(12 - 17)  |
|18 |(17 - 24)  |
|28 |(24 - 34)  |
|38 |(34 - 44)  |
|38 |(34 - 44)  |
|388|(100- 1000)|
|3  |(-1 - 12)  |
|41 |(34 - 44)  |
+---+-----------+

I hope this helps!


问:
Validate dates in XML Document before writing to database
I'm currently getting user input from a very large form as an XML document. I'd like to validate this XML document against a schema before any database related operations. The problem is that users input dates according to their own preferences (US standard, ISO standard, etc.) and the database expects dates to be ISO standard. Is there anyway I can validate this XML document and change the dates to ISO format before adding it to the database? I'm using Perl for the back-end, any libraries that can help me do the same?

Cheers,

答:
For date conversion

HTTP::Date

For dealing with xmls in general

Perl-XML

PM for processing XLST (you guessed it)

XML::XLST


问:
android - Format Double and put it in TextView without comma (if needed)
I get the "price" value from the server in Double and I need to put it in TextView in my application. The problem is: when price = 500 I get 500.0 because it's Double. I want it to look like 500.55 or 500.50 or just 500 - how do I format these numbers in the right way?

答:
you can use rexgex to do the formatting

1.) Create a function to identify the following conditions

If precision values contains only zeros then truncate them

If there is any non-zero value after decimal then return original value

```<code>public String formatValue(double d){
    String dStr = String.valueOf(d);
    String value = dStr.matches("\\d+\\.\\d*[1-9]\\d*") ? dStr : dStr.substring(0,dStr.indexOf("."));
    return value;
}
</code>```

\\d+\\.\\d*[1-9]\\d* : match one or more digits then a .

\\d*[1-9]\\d*  : match one non-zero value

Test cases

```<code>    yourTextView.setText(formatValue(500.00000000)); // 500
    yourTextView.setText(formatValue(500.0001));       // 500.0001
    yourTextView.setText(formatValue(500));          // 500
    yourTextView.setText(formatValue(500.1111));     // 500.1111
</code>```

Learn more about regular expressions

ContentLicense: CC BY-SA 4.0

Body:
you can use rexgex to do the formatting

1.) Create a function to identify the following conditions

If precision values contains only zeros then truncate them

If there is any non-zero value after decimal then return original value

public String formatValue(double d){
    String dStr = String.valueOf(d);
    String value = dStr.matches("\\d+\\.\\d*[1-9]\\d*") ? dStr : dStr.substring(0,dStr.indexOf("."));
    return value;
}

\\d+\\.\\d*[1-9]\\d* : match one or more digits then a .

\\d*[1-9]\\d*  : match one non-zero value

Test cases

    yourTextView.setText(formatValue(500.00000000)); // 500
    yourTextView.setText(formatValue(500.0001));       // 500.0001
    yourTextView.setText(formatValue(500));          // 500
    yourTextView.setText(formatValue(500.1111));     // 500.1111

Learn more about regular expressions


问:
How to deploy Apprtc's collider into Google App Engine?
I have deployed the apprtc's google app engine code on my own GAE server. I don't find instructions on how to deploy the Go based collider for websocket signaling.

Here is the collider project: https://github.com/webrtc/apprtc/tree/master/src/collider

Any insights would help.

答:
Goto https://github.com/webrtc/apprtc/blob/master/src/collider/README.md
This has all the steps to run collider
the instructions given are specifically for google compute engine(GCE) which is a linux based machine

Create a instance in GCE and connect through browser

Install Go using

Set up GO workspace and path accordingly

Install git and Clone the apprtc project in your home directory

Create symbolic links from your apprtc collider folders to go workspace src folders

Goto Apprtc-->src-->collidermain-->main.go and change the room server to the server address of the app deployed in google app engine(GAE)

var roomSrv = flag.String("room-server", "https://your.apprtc.server",
  "The origin of the room server")

Get dependencies and install collidermain

Goto root path and install collider as given in the instructions

start collider in root using
sudo nohup collider/collidermain -port=443 -tls=true

**this is just for development purpose not for production


问:
How to format an email 'From' header that contains a comma
The standard way to format the 'From' email header is

```<code>From: John Doe <john.doe@example.com>
</code>```

But what to do if there's a comma in the name?

```<code>From: John Doe, chief bottle washer <john.doe@example.com>
</code>```

If I do that, my MTA automatically converts this into:

```<code>From: John@this.server.com, Doe@this.server.com, chief bottle washer <john.doe@example.com>
</code>```

My first guess is to use double-quotes around the full name, but I can't find any official documentation confirming this and I'd like my emails to be readable by all email clients.

答:
When the following regular expression matches, then an email display address must be quoted.

```<code>[^-A-Za-z0-9!#$%&'*+/=?^_`{|}~\s]
</code>```

For ASCII characters, this can be done by escaping any double quote characters with a backslash, and enclosing the string in double quotes.  For non-ASCII characters, the more complex MIME escaping is required.

Body:
The standard way to format the 'From' email header is

From: John Doe <john.doe@example.com>

But what to do if there's a comma in the name?

From: John Doe, chief bottle washer <john.doe@example.com>

If I do that, my MTA automatically converts this into:

From: John@this.server.com, Doe@this.server.com, chief bottle washer <john.doe@example.com>

My first guess is to use double-quotes around the full name, but I can't find any official documentation confirming this and I'd like my emails to be readable by all email clients.

Body:
When the following regular expression matches, then an email display address must be quoted.

[^-A-Za-z0-9!#$%&'*+/=?^_`{|}~\s]

For ASCII characters, this can be done by escaping any double quote characters with a backslash, and enclosing the string in double quotes.  For non-ASCII characters, the more complex MIME escaping is required.


问:
Laravel Elixir BrowserSync not loading correct project from wamp directory
I have a new issue regarding the Laravel-Elixir-BrowserSync task.

Currently I set up a new laravel project in "C:\wamp64\www\projectname" but when I run my gulp watch command it does not load the project that I want to work on.
There is however a laravel blog application folder that I created to play around in laravel on my wamp setup so whenever I start wampserver it loads the laravel blog application or it just loads a blank webpage that keeps loading all the time.

Should I just remove the blog folder permanently from the wamp/www folder or how can I change this to load the specific project I want to work on?

My gulp file looks like this.

```<code>var gulp = require('gulp');

var elixir = require('laravel-elixir');
var vueify = require('laravel-elixir-vueify');

elixir(function (mix) {

  // compile all .scss files into this main file
  mix.sass('app.scss');
  mix.sass('main.scss');
  mix.scripts('app.js');
  mix.browserify('app.js');

  mix.browserSync({
    proxy: 'dev.myprojectname',
    port: 5000
  });

  // export it into the public folder here.
  mix.version('public/css/app.css');
  mix.version('public/css/main.css');
  mix.version('public/js/app.js');

  mix.phpUnit();
  mix.phpSpec();

});
</code>```

答:
I fixed it. I found that there was an error in my httpd-vhosts.conf file where the DocumentRoot was missing (I deleted the project) so I just set it to the new folder path for the site I want to serve when running my gulp watch file.

```<code><VirtualHost *:80>
ServerName localhost
DocumentRoot c:/wamp64/www/project-name/public
<Directory  "c:/wamp64/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local
</Directory>
</code>```

```<code>mix.browserSync({
  proxy: 'local.dev',
  port: 5000
});
</code>```

Body:
I have a new issue regarding the Laravel-Elixir-BrowserSync task.

Currently I set up a new laravel project in "C:\wamp64\www\projectname" but when I run my gulp watch command it does not load the project that I want to work on.
There is however a laravel blog application folder that I created to play around in laravel on my wamp setup so whenever I start wampserver it loads the laravel blog application or it just loads a blank webpage that keeps loading all the time.

Should I just remove the blog folder permanently from the wamp/www folder or how can I change this to load the specific project I want to work on?

My gulp file looks like this.

var gulp = require('gulp');

var elixir = require('laravel-elixir');
var vueify = require('laravel-elixir-vueify');

elixir(function (mix) {

  // compile all .scss files into this main file
  mix.sass('app.scss');
  mix.sass('main.scss');
  mix.scripts('app.js');
  mix.browserify('app.js');

  mix.browserSync({
    proxy: 'dev.myprojectname',
    port: 5000
  });

  // export it into the public folder here.
  mix.version('public/css/app.css');
  mix.version('public/css/main.css');
  mix.version('public/js/app.js');

  mix.phpUnit();
  mix.phpSpec();

});

Body:
I fixed it. I found that there was an error in my httpd-vhosts.conf file where the DocumentRoot was missing (I deleted the project) so I just set it to the new folder path for the site I want to serve when running my gulp watch file.

<VirtualHost *:80>
ServerName localhost
DocumentRoot c:/wamp64/www/project-name/public
<Directory  "c:/wamp64/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local
</Directory>

mix.browserSync({
  proxy: 'local.dev',
  port: 5000
});


问:
Azure SQL server database [Win32Exception (0x80004005): Access is denied]
I have managed to deploy a web application on Azure with VS2015 and I have created a database but something seems to be wrong configured in the web.config because I get an error.
I have followed a tutorial that helped me through the process.

Here is the link, maybe someone finds it useful: Link to pluralsight tutorial

Well, when I have finished, I got this:

Error image

My connection string:

```<code>  <add name="DefaultConnection" connectionString="Data Source=tcp:xxxx.database.windows.net,1433;Initial Catalog={database};Persist Security Info=False;User ID={xxx};Password={xxxx};MultipleActiveResultSets=False;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
</code>```

I have tried several solutions on stackoverflow like changing the target framework version to 4.5. from 4.5.2. Link to solution Did not work for me. I would be so greatful if someone could help! Thanks!

答: If you are using ASP.NET 5 then configure your connection string in appsettings.json file.</p>

Body:
I have managed to deploy a web application on Azure with VS2015 and I have created a database but something seems to be wrong configured in the web.config because I get an error.
I have followed a tutorial that helped me through the process.

Here is the link, maybe someone finds it useful: Link to pluralsight tutorial

Well, when I have finished, I got this:

Error image

My connection string:

  <add name="DefaultConnection" connectionString="Data Source=tcp:xxxx.database.windows.net,1433;Initial Catalog={database};Persist Security Info=False;User ID={xxx};Password={xxxx};MultipleActiveResultSets=False;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False" providerName="System.Data.SqlClient" />

I have tried several solutions on stackoverflow like changing the target framework version to 4.5. from 4.5.2. Link to solution Did not work for me. I would be so greatful if someone could help! Thanks!


问:
How to modify the message in "when and otherwise" function in spark datafarme in scala?
I have dataframe where I'm doing some conditional check with it and creating a column name like valRow and maintaining their status on it. I'm also trying to display message into console, here I'm able to display the message into console successfully. I got stuck with two things

1) I wanted to display the uniqueID of the false result in otherwise function which in highlighted bold letter below, right now in the log it display their name like uniqueID as it is.

```<code>.otherwise(getFlagStatus(false.booleanValue(),"valRow","JKM record -- ITC_SALE_TYPE cannot be empty ", childDF("uniqueID").toString))
</code>```

2) I wanted the count of a false result.

```<code>childDF=
+--------+-------------+-------------+---------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR |
+--------+-------------+-------------+---------+
|    2568|            F|            3|      S  |
|    2569|            F|            1|      S  |
|    2570|            F|            1|      C  |
|    2571|            F|             |      S  |
|    2572|            F|            3|      S  |
|    2572|            F|            3|      S  |
|    2574|            F|             |      C  |
+--------+-------------+-------------+---------+

Dataframe creates in runtime.
    +--------+-------------+-------------+---------+---------+
    |uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR |valRow   |
    +--------+-------------+-------------+---------+---------+
    |    2568|            F|            3|      S  |  true   |
    |    2569|            F|            1|      S  |  true   |
    |    2570|            F|            1|      C  |  true   |
    |    2571|            F|            1|      S  |  false  |
    |    2572|            F|            3|      S  |  true   |
    |    2573|            F|            3|      S  |  true   |
    |    2574|            F|            3|      C  |  false  |
    +--------+-------------+-------------+---------+---------+

def getFlagStatus(flagValue:Boolean,functionName:String,message:String,uniqueID:String) :Boolean =  {

        if(flagValue.equals(false)) {
          ValidationMap.put(ValidationStatus,false)
          logger.mdLog(LogTypeError, functionName, Map(
            Message -> message,
            idNumber->uniqueID
          ))

        }
        false
      }

val newChildDF2 =childD
 .withColumn("valRow",when(childDF("ITC_SALE_TYPE") =!= " " && childDF("ITC_SALE_TYPE") =!= Nil.toString(),lit(true))
              .otherwise(getFlagStatus(false.booleanValue(),"valRow","JKM record -- ITC_SALE_TYPE cannot be empty ",childDF("uniqueID").toString)))
              .drop("valRow")
</code>```

My English is not so much good if anybody faces any problem with it please leave your message,any help will be appricated.

答:
I don't think what you want to achieve can be done with 'otherwise'. However, I have managed to get it working using a UDF:

```<code>val df = Seq(
  (2568, false, "3", "S"),
  (2569, false, "1", "S"),
  (2570, false, "1", "C"),
  (2571, false, "", "S"),
  (2572, false, "3", "S"),
  (2572, false, "3", "S"),
  (2574, false, "", "C")
).toDF("uniqueID", "HACKER_K_TYPE", "ITC_SALE_TYPE", "OPERATOR")

val logResults = udf((saleType: String, uniqueID: String) => {
  var res = true
  if(saleType == "") {
    println("logging unique id here:" + uniqueID)
    res = false
  }
  res
})

val newdf = df.withColumn("valRow",logResults($"ITC_SALE_TYPE", $"uniqueID"))

newdf.show()
</code>```

Output:

```<code>df: org.apache.spark.sql.DataFrame = [uniqueID: int, HACKER_K_TYPE: boolean ... 2 more fields]
logResults: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function2>,BooleanType,Some(List(StringType, StringType)))
newdf: org.apache.spark.sql.DataFrame = [uniqueID: int, HACKER_K_TYPE: boolean ... 3 more fields]
logging unique id here:2571
logging unique id here:2574
+--------+-------------+-------------+--------+------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR|valRow|
+--------+-------------+-------------+--------+------+
|    2568|        false|            3|       S|  true|
|    2569|        false|            1|       S|  true|
|    2570|        false|            1|       C|  true|
|    2571|        false|             |       S| false|
|    2572|        false|            3|       S|  true|
|    2572|        false|            3|       S|  true|
|    2574|        false|             |       C| false|
+--------+-------------+-------------+--------+------+
</code>```

Body:
I have dataframe where I'm doing some conditional check with it and creating a column name like valRow and maintaining their status on it. I'm also trying to display message into console, here I'm able to display the message into console successfully. I got stuck with two things

1) I wanted to display the uniqueID of the false result in otherwise function which in highlighted bold letter below, right now in the log it display their name like uniqueID as it is.

.otherwise(getFlagStatus(false.booleanValue(),"valRow","JKM record -- ITC_SALE_TYPE cannot be empty ", childDF("uniqueID").toString))

2) I wanted the count of a false result.

childDF=
+--------+-------------+-------------+---------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR |
+--------+-------------+-------------+---------+
|    2568|            F|            3|      S  |
|    2569|            F|            1|      S  |
|    2570|            F|            1|      C  |
|    2571|            F|             |      S  |
|    2572|            F|            3|      S  |
|    2572|            F|            3|      S  |
|    2574|            F|             |      C  |
+--------+-------------+-------------+---------+

Dataframe creates in runtime.
    +--------+-------------+-------------+---------+---------+
    |uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR |valRow   |
    +--------+-------------+-------------+---------+---------+
    |    2568|            F|            3|      S  |  true   |
    |    2569|            F|            1|      S  |  true   |
    |    2570|            F|            1|      C  |  true   |
    |    2571|            F|            1|      S  |  false  |
    |    2572|            F|            3|      S  |  true   |
    |    2573|            F|            3|      S  |  true   |
    |    2574|            F|            3|      C  |  false  |
    +--------+-------------+-------------+---------+---------+

def getFlagStatus(flagValue:Boolean,functionName:String,message:String,uniqueID:String) :Boolean =  {

        if(flagValue.equals(false)) {
          ValidationMap.put(ValidationStatus,false)
          logger.mdLog(LogTypeError, functionName, Map(
            Message -> message,
            idNumber->uniqueID
          ))

        }
        false
      }

val newChildDF2 =childD
 .withColumn("valRow",when(childDF("ITC_SALE_TYPE") =!= " " && childDF("ITC_SALE_TYPE") =!= Nil.toString(),lit(true))
              .otherwise(getFlagStatus(false.booleanValue(),"valRow","JKM record -- ITC_SALE_TYPE cannot be empty ",childDF("uniqueID").toString)))
              .drop("valRow")

My English is not so much good if anybody faces any problem with it please leave your message,any help will be appricated.

Body:
I don't think what you want to achieve can be done with 'otherwise'. However, I have managed to get it working using a UDF:

val df = Seq(
  (2568, false, "3", "S"),
  (2569, false, "1", "S"),
  (2570, false, "1", "C"),
  (2571, false, "", "S"),
  (2572, false, "3", "S"),
  (2572, false, "3", "S"),
  (2574, false, "", "C")
).toDF("uniqueID", "HACKER_K_TYPE", "ITC_SALE_TYPE", "OPERATOR")

val logResults = udf((saleType: String, uniqueID: String) => {
  var res = true
  if(saleType == "") {
    println("logging unique id here:" + uniqueID)
    res = false
  }
  res
})

val newdf = df.withColumn("valRow",logResults($"ITC_SALE_TYPE", $"uniqueID"))

newdf.show()

Output:

df: org.apache.spark.sql.DataFrame = [uniqueID: int, HACKER_K_TYPE: boolean ... 2 more fields]
logResults: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function2>,BooleanType,Some(List(StringType, StringType)))
newdf: org.apache.spark.sql.DataFrame = [uniqueID: int, HACKER_K_TYPE: boolean ... 3 more fields]
logging unique id here:2571
logging unique id here:2574
+--------+-------------+-------------+--------+------+
|uniqueID|HACKER_K_TYPE|ITC_SALE_TYPE|OPERATOR|valRow|
+--------+-------------+-------------+--------+------+
|    2568|        false|            3|       S|  true|
|    2569|        false|            1|       S|  true|
|    2570|        false|            1|       C|  true|
|    2571|        false|             |       S| false|
|    2572|        false|            3|       S|  true|
|    2572|        false|            3|       S|  true|
|    2574|        false|             |       C| false|
+--------+-------------+-------------+--------+------+


问:
Loop Through Column to find Match - VBA
I'm trying to create a VBA Command that goes through many cases in order to find a commission fee percentage. Starting off, I need to compare a ID to a list of Special IDs (Using one Integer, loop through a column of 30 integers). I also need to check to see if the 'komisija' value is greater than 40, which would then simply return 40.</p>

```<code>Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double

Set kSheet = ThisWorkbook.Sheets("komisijas")

'Set variables equal to the cell data
  klienta_nr = Range("A2").Value
  ISIN = Range("E2").Value
  Cena = Range("H2").Value
  Skaits = Range("I2").Value

'First, have case for non-special klients
If Application.WorksheetFunction.Match(klienta_nr, kSheet.Range("A2:A40")) Then
      If Right(klienta_nr, 1) = 1 Or Right(klienta_nr, 1) = 8 Then
        Komisija = (Cena * Skaits) * 0.003
        End If
      If Right(klienta_nr, 1) = 7 Then
        Komisija = (Cena * Skaits) * 0.01
        End If
      If Komisija > 40 Then
        Range("K2").Value = Komisija
        End If
      Range("K2").Value = Komisija
End If

Range("K2").Value = Komisija
</code>```

答:
Try this:</p>

```<code>Dim var as Variant
var = Application.WorksheetFunction.Match(klienta_nr, kSheet.Range("A2:A17"))
If Not iserror(var) Then
</code>```

Title: Loop Through Column to find Match - VBA

Body:
I'm trying to create a VBA Command that goes through many cases in order to find a commission fee percentage. Starting off, I need to compare a ID to a list of Special IDs (Using one Integer, loop through a column of 30 integers). I also need to check to see if the 'komisija' value is greater than 40, which would then simply return 40.

Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double

Set kSheet = ThisWorkbook.Sheets("komisijas")

'Set variables equal to the cell data
  klienta_nr = Range("A2").Value
  ISIN = Range("E2").Value
  Cena = Range("H2").Value
  Skaits = Range("I2").Value

'First, have case for non-special klients
If Application.WorksheetFunction.Match(klienta_nr, kSheet.Range("A2:A40")) Then
      If Right(klienta_nr, 1) = 1 Or Right(klienta_nr, 1) = 8 Then
        Komisija = (Cena * Skaits) * 0.003
        End If
      If Right(klienta_nr, 1) = 7 Then
        Komisija = (Cena * Skaits) * 0.01
        End If
      If Komisija > 40 Then
        Range("K2").Value = Komisija
        End If
      Range("K2").Value = Komisija
End If

Range("K2").Value = Komisija

Body:
Try this:

Dim var as Variant
var = Application.WorksheetFunction.Match(klienta_nr, kSheet.Range("A2:A17"))
If Not iserror(var) Then