问:
How to use a public method from a controller to another controller in codeigniter?
I have 2 controllers, Listes.php and Campagnes.php. I want to use a method from the Listes controller in a method from the campagnes, is it possible? And is it possible to pass some parameters to it?

I use Codeigniter 3.

I tried some answers I found here but none of them worked.

I also this in the campagnes.php controller :

```<code>    include_once (dirname(__FILE__) . "/Listes.php");

     class Campagnes extends Listes {

       public function listes_recap()
       {
         $result = parent::add($parameter1, $parameter2);
       }

      }
</code>```

and in the Listes.php controller :

```<code>    class Listes extends CI_Controller {

     public function add($parameter1, $parameter2)
     {
       code here...
     }

    }
</code>```

Thanks in advance for you're help.

答:
There are a couple ways to achieve the results you want. But calling one controller from another is NOT the way to go. The "best" way to do it depends on what actually happens in the function that both controllers will use.

The first way is to create a "helper" that each controller will load and then use.

file: /application/helpers/list_add_helper.php

```<code>defined('BASEPATH') OR exit('No direct script access allowed');

if ( ! function_exists('add'))
{
    function add($parameter1, $parameter2)
    {
       code here...
    }
}
</code>```

Use it in the controller like this

```<code>$this->load->helper('list_add');
$result = add($one, $two);
</code>```

The second way is to create a custom library (class)

file: /application/libraries/List_adder.php

```<code>class List_adder
{
    public function add($parameter1, $parameter2)
    {
       //code here
    }
}
</code>```

Used in any controller

```<code>$this->load->library('list_adder');
$result = $this->list_adder->add($one, $two);
</code>```

If you need to use CI code in your custom library you have a little more work to do. Read all about it HERE.

Body:
I have 2 controllers, Listes.php and Campagnes.php. I want to use a method from the Listes controller in a method from the campagnes, is it possible? And is it possible to pass some parameters to it?

I use Codeigniter 3.

I tried some answers I found here but none of them worked.

I also this in the campagnes.php controller :

    include_once (dirname(__FILE__) . "/Listes.php");

     class Campagnes extends Listes {

       public function listes_recap()
       {
         $result = parent::add($parameter1, $parameter2);
       }

      }

and in the Listes.php controller :

    class Listes extends CI_Controller {

     public function add($parameter1, $parameter2)
     {
       code here...
     }

    }

Thanks in advance for you're help.

Body:
There are a couple ways to achieve the results you want. But calling one controller from another is NOT the way to go. The "best" way to do it depends on what actually happens in the function that both controllers will use.

The first way is to create a "helper" that each controller will load and then use.

file: /application/helpers/list_add_helper.php

defined('BASEPATH') OR exit('No direct script access allowed');

if ( ! function_exists('add'))
{
    function add($parameter1, $parameter2)
    {
       code here...
    }
}

Use it in the controller like this

$this->load->helper('list_add');
$result = add($one, $two);

The second way is to create a custom library (class)

file: /application/libraries/List_adder.php

class List_adder
{
    public function add($parameter1, $parameter2)
    {
       //code here
    }
}

Used in any controller

$this->load->library('list_adder');
$result = $this->list_adder->add($one, $two);

If you need to use CI code in your custom library you have a little more work to do. Read all about it HERE.


来源: stackexchange

问:
Access last row added to table - PHP
I have a simple sql query adding a new row to a database and need it to return the a field back to Javascript. The field does Auto_increment but stupildy I called it 'itemId' so mysql_insert_id doesnt work and I don't think I have time to go and amend all the php files that use 'itemId'

Here's my code if it helps:

```<code>$addMainItem = "INSERT INTO newsItems (itemId, title, date, tags, location, latitude, longitude, visibleFrontpage, introText, fullDome, liveEvent, customServing, visitorAttraction, retail, digitalCinema, visiblePublic, thumbPath, links, smallDesc) VALUES ('','$title','$date','$tags','$loco','$lat','$long','$visiFront','$intro','$dome ','$live','$custom','$attrac','$retail','$cinema','$public','$thumbPath','$links','$smallDesc')";
$result = mysql_query($addMainItem) or die('error '.mysql_error());

if($result) echo (mysql_insert_id());
</code>```

答:
I've never heard that naming a column itemId breaking mysql_isert_id().

But you can just select the last inserted record if auto_increment is working.

```<code>SELECT * FROM newsItems ORDER BY itemId DESC LIMIT 1
</code>```

You can put the select statement into a transaction with the insert statement if you're using innoDB and you're worried about a race condition.

ContentLicense: CC BY-SA 2.5

Title: Access last row added to table - PHP

Body:
I have a simple sql query adding a new row to a database and need it to return the a field back to Javascript. The field does Auto_increment but stupildy I called it 'itemId' so mysql_insert_id doesnt work and I don't think I have time to go and amend all the php files that use 'itemId'

Here's my code if it helps:

$addMainItem = "INSERT INTO newsItems (itemId, title, date, tags, location, latitude, longitude, visibleFrontpage, introText, fullDome, liveEvent, customServing, visitorAttraction, retail, digitalCinema, visiblePublic, thumbPath, links, smallDesc) VALUES ('','$title','$date','$tags','$loco','$lat','$long','$visiFront','$intro','$dome ','$live','$custom','$attrac','$retail','$cinema','$public','$thumbPath','$links','$smallDesc')";
$result = mysql_query($addMainItem) or die('error '.mysql_error());

if($result) echo (mysql_insert_id());

Body:
I've never heard that naming a column itemId breaking mysql_isert_id().

But you can just select the last inserted record if auto_increment is working.

SELECT * FROM newsItems ORDER BY itemId DESC LIMIT 1

You can put the select statement into a transaction with the insert statement if you're using innoDB and you're worried about a race condition.


问:
Implementing Java String's hashCode() method in Swift 3
I am creating an iOS version of an existing Android app.
On the Android side, hashCode() of a String (username) is sent to the server and based on that hash, a JSON object is returned.

On Swift, I tried hash and hashValue properties but both of them produces values that are different from their Android counterpart.

So I decided to write my own implementation based on Java's implementation:

```<code>int h = hash;
if (h == 0 && value.length > 0) {
  char val[] = value;
  for (int i = 0; i < value.length; i++) {
    h = 31 * h + val[i];
  }
  hash = h;
}
return h;
</code>```

But when I write the above implementation in Swift, I get overflow crash. Can anybody help me here?

Thanks in advance.

Here is the Swift implementation:

I first had to write a Character extension that would return Ascii value of the character:

```<code>extension Character {
    var asciiValue: UInt32? {
        return String(self).unicodeScalars.filter{$0.isASCII}.first?.value
    }
}
</code>```

Then I created a String extension with:
1. a property that returns Ascii values of each character in the String.
2. a hash method to return the hash (copying the Java code)

```<code>extension String {
    var asciiArray: [UInt32] {
        return unicodeScalars.filter{$0.isASCII}.map{$0.value}
    }
    func myHash() -> Int {
        var h = 0 as Int!
        for i in 0..<asciiArray.count {
            h = 31*h! + Int(array[i])
        }
        return h!
    }
}
</code>```

答:
As the post is still missing an answer, here is the working code:

1) Write an extension for Characters, to map their ascii representation to an int - we need UInt32, as Java uses for the hashing a 32 bit system, not 64 bit.

2) Make sure our represented string does ONLY contain characters, which are mappable to ASCII

3) Now perform the mentioned hashing function

```<code>int h = 0;
if (h == 0 && value.length > 0) {
  char val[] = value;
  for (int i = 0; i < value.length; i++) {
    h = 31 * h + val[i];
  }
  hash = h;
}
return h;
</code>```

So, we will get the following code snippet, which could be used in your projects.

```<code>// 1) Here is our Character extension
extension Character {
    var asciiValue: UInt32? {
        return String(self).unicodeScalars.filter{$0.isASCII}.first?.value
    }
}

extension String {
    // 2) ascii array to map our string
    var asciiArray: [UInt32] {
        return unicodeScalars.filter{$0.isASCII}.map{$0.value}
    }

    // this is our hashCode function, which produces equal output to the Java or Android hash function
    func hashCode() -> Int32 {
        var h : Int32 = 0
        for i in self.asciiArray {
            h = 31 &* h &+ Int32(i) // Be aware of overflow operators,
        }
        return h
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating an iOS version of an existing Android app.
On the Android side, hashCode() of a String (username) is sent to the server and based on that hash, a JSON object is returned.

On Swift, I tried hash and hashValue properties but both of them produces values that are different from their Android counterpart.

So I decided to write my own implementation based on Java's implementation:

int h = hash;
if (h == 0 && value.length > 0) {
  char val[] = value;
  for (int i = 0; i < value.length; i++) {
    h = 31 * h + val[i];
  }
  hash = h;
}
return h;

But when I write the above implementation in Swift, I get overflow crash. Can anybody help me here?

Thanks in advance.

Here is the Swift implementation:

I first had to write a Character extension that would return Ascii value of the character:

extension Character {
    var asciiValue: UInt32? {
        return String(self).unicodeScalars.filter{$0.isASCII}.first?.value
    }
}

Then I created a String extension with:
1. a property that returns Ascii values of each character in the String.
2. a hash method to return the hash (copying the Java code)

extension String {
    var asciiArray: [UInt32] {
        return unicodeScalars.filter{$0.isASCII}.map{$0.value}
    }
    func myHash() -> Int {
        var h = 0 as Int!
        for i in 0..<asciiArray.count {
            h = 31*h! + Int(array[i])
        }
        return h!
    }
}

Body:
As the post is still missing an answer, here is the working code:

1) Write an extension for Characters, to map their ascii representation to an int - we need UInt32, as Java uses for the hashing a 32 bit system, not 64 bit.

2) Make sure our represented string does ONLY contain characters, which are mappable to ASCII

3) Now perform the mentioned hashing function

int h = 0;
if (h == 0 && value.length > 0) {
  char val[] = value;
  for (int i = 0; i < value.length; i++) {
    h = 31 * h + val[i];
  }
  hash = h;
}
return h;

So, we will get the following code snippet, which could be used in your projects.

// 1) Here is our Character extension
extension Character {
    var asciiValue: UInt32? {
        return String(self).unicodeScalars.filter{$0.isASCII}.first?.value
    }
}

extension String {
    // 2) ascii array to map our string
    var asciiArray: [UInt32] {
        return unicodeScalars.filter{$0.isASCII}.map{$0.value}
    }

    // this is our hashCode function, which produces equal output to the Java or Android hash function
    func hashCode() -> Int32 {
        var h : Int32 = 0
        for i in self.asciiArray {
            h = 31 &* h &+ Int32(i) // Be aware of overflow operators,
        }
        return h
    }
}


问:
Hide or Custom page for ionic 2 Error handling box
In application using ionic 2 when an error happens a dialog like below appears:

I don't want user to see this screen when any error happens. Instead of this I want to route the user to some custom page or my root page. Is it possible?

答:
That is only shown in ionic serve and is a feature of IonicErrorHandler.

The IonicErrorHandler intercepts the default Console error handling and displays runtime errors as an overlay when using Ionic's Dev Build Server.

This is set in ngModule.

```<code>{ provide: ErrorHandler, useClass: IonicErrorHandler },
</code>```

It does not display that page in device or emulator.

You can extend ErrorHandler class and set it to do what you need.

```<code>export declare class MyErrorHandler extends ErrorHandler {
    constructor(){}

    handleError(err: any){
    }
}
</code>```

And in ngModule:

```<code>{ provide: ErrorHandler, useClass: MyErrorHandler },
</code>```

Body:
That is only shown in ionic serve and is a feature of IonicErrorHandler.

The IonicErrorHandler intercepts the default Console error handling and displays runtime errors as an overlay when using Ionic's Dev Build Server.

This is set in ngModule.

{ provide: ErrorHandler, useClass: IonicErrorHandler },

It does not display that page in device or emulator.

You can extend ErrorHandler class and set it to do what you need.

export declare class MyErrorHandler extends ErrorHandler {
    constructor(){}

    handleError(err: any){
    }
}

And in ngModule:

{ provide: ErrorHandler, useClass: MyErrorHandler },


问:
4 weeks or accounting month grouping in postgresql
I have a requirement to group data in transaction table into 4 week groups, or accounting month grouping, any suggestions on how to approach it on postgresql

Regards

答:
use date_trunc
https://www.postgresql.org/docs/9.1/static/functions-datetime.html

Anything more than this will need some more information. copy some examples and anything you have tried already.

```<code>SELECT date_trunc('week', your_date_field)
FROM your_table_name
GROUP BY 1
</code>```

Body:
use date_trunc
https://www.postgresql.org/docs/9.1/static/functions-datetime.html

Anything more than this will need some more information. copy some examples and anything you have tried already.

SELECT date_trunc('week', your_date_field)
FROM your_table_name
GROUP BY 1


问:
Inject database in a ContentProvider with dagger
I want to inject a singleton SqliteOpenHelper in a ContentProvider. However, it seems that the ContentProvider instance is being built before the Application instance is being created (getApplicationContext() returns null). When can I inject the database? I've tried in the constructor and in the onCreate() method of the ContentProvider.

答:
Simple Solution

There is a simple reason for this, onCreate() provider is called
  before the appropriate method in the Application. You can
  make the creation of a component in another method of the
  Application, for example attachBaseContext.

1 Move your logic from onCreate to attachBaseContext in your Application.

@Override
public void attachBaseContext(Context base){

    super.attachBaseContext(base);

    mApplicationComponent = DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .build();
    mApplicationComponent.inject(this);
}
```

<p><kbd>2</kbd> You can now <code>inject</code> in <code>OnCreate</code> in your ContentProvider:</p>

```public boolean onCreate() {

    YourMainApplication.get(getContext()).getComponent().inject(this);

    return true;
}
```

Disclaimer: Full Credits to @LeEnot from this russian blog: Dagger2 Inject in Content Provider. The answer is listed here for convenience as it is not available in English.

Body:
Simple Solution

There is a simple reason for this, onCreate() provider is called
  before the appropriate method in the Application. You can
  make the creation of a component in another method of the
  Application, for example attachBaseContext.

1 Move your logic from onCreate to attachBaseContext in your Application.

@Override
public void attachBaseContext(Context base){

    super.attachBaseContext(base);

    mApplicationComponent = DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .build();
    mApplicationComponent.inject(this);
}

2 You can now inject in OnCreate in your ContentProvider:

public boolean onCreate() {

    YourMainApplication.get(getContext()).getComponent().inject(this);

    return true;
}

Disclaimer: Full Credits to @LeEnot from this russian blog: Dagger2 Inject in Content Provider. The answer is listed here for convenience as it is not available in English.


问:
Append auto-incrementing suffix to duplicated elements of a List
Given the following list :

```<code>val l = List("A", "A", "C", "C", "B", "C")
</code>```

How can I add an auto-incrementing suffix to every elements so that I end up with a list containing no more duplicates, like the following (the ordering doesn't matter) :

```<code>List("A0", "A1", "C0", "C1", "C2", "B0")
</code>```

答:
Perhaps not the most readable solution, but...

```<code>def appendCount(l: List[String]): List[String] = {
  // Since we're doing zero-based counting, we need to use `getOrElse(e, -1) + 1`
  // to indicate a first-time element count as 0.
  val counts =
    l.foldLeft(Map[String, Int]())((acc, e) =>
      acc + (e -> (acc.getOrElse(e, -1) + 1))
    )

  val (appendedList, _) =
    l.foldRight(List[String](), counts){ case (e, (li, m)) =>
      // Prepend the element with its count to the accumulated list.
      // Decrement that element's count within the map of element counts
      (s"$e${m(e)}" :: li, m + (e -> (m(e) - 1)))
    }
  appendedList
}
</code>```

The idea here is that you create a count of each element in the list. You then iterate from the back of the list of original values and append the count to the value while decrementing the count map.

You need to define a helper here because foldRight will require both the new List[String] and the counts as an accumulator (and, as such, will return both). You'll just ignore the counts at the end (they'll all be -1 anyway).

I'd say your way is probably more clear. You'll need to benchmark to see which is faster if that's a concern.

Ideone.

Body:
Given the following list :

val l = List("A", "A", "C", "C", "B", "C")

How can I add an auto-incrementing suffix to every elements so that I end up with a list containing no more duplicates, like the following (the ordering doesn't matter) :

List("A0", "A1", "C0", "C1", "C2", "B0")

Body:
Perhaps not the most readable solution, but...

def appendCount(l: List[String]): List[String] = {
  // Since we're doing zero-based counting, we need to use `getOrElse(e, -1) + 1`
  // to indicate a first-time element count as 0.
  val counts =
    l.foldLeft(Map[String, Int]())((acc, e) =>
      acc + (e -> (acc.getOrElse(e, -1) + 1))
    )

  val (appendedList, _) =
    l.foldRight(List[String](), counts){ case (e, (li, m)) =>
      // Prepend the element with its count to the accumulated list.
      // Decrement that element's count within the map of element counts
      (s"$e${m(e)}" :: li, m + (e -> (m(e) - 1)))
    }
  appendedList
}

The idea here is that you create a count of each element in the list. You then iterate from the back of the list of original values and append the count to the value while decrementing the count map.

You need to define a helper here because foldRight will require both the new List[String] and the counts as an accumulator (and, as such, will return both). You'll just ignore the counts at the end (they'll all be -1 anyway).

I'd say your way is probably more clear. You'll need to benchmark to see which is faster if that's a concern.

Ideone.


问:
Replace the automatic numbering of captions inrmarkdown / knitr / pdf
I am generating a PDF document with Rmarkdown, within which I want to manually define figure numbers.

Below is an example of a chunk:

```<code>```{r chunk26, fig.cap = "Fig. 5.3 My figure caption"}
plot(1, 1)
```
</code>```

I use a special numbering to follow the chapters of my document.

The problem is that when I knit the PDF, "Figure X:" is automatically added before each caption. As a result, my figure captions look like this example:

Note
I have used the following parameters in the beginning of my rmarkdown file:

```<code>output:
  pdf_document:
    fig_caption: yes
</code>```

My question therefore is:

is it possible to remove the automatic generation of "Figure X" before the figure caption, when generating a PDF using rmarkdown/knitr?

答:
You can use:

```<code>header-includes:
\renewcommand{\caption}{Figure}
</code>```

in the YAML header. Then, in the code chunk, use:

```<code>```{r, fig.cap=" 5.3: Response functions"}
...
```
</code>```

Body:
I am generating a PDF document with Rmarkdown, within which I want to manually define figure numbers.

Below is an example of a chunk:

```{r chunk26, fig.cap = "Fig. 5.3 My figure caption"}
plot(1, 1)
```

I use a special numbering to follow the chapters of my document.

The problem is that when I knit the PDF, "Figure X:" is automatically added before each caption. As a result, my figure captions look like this example:

Note
I have used the following parameters in the beginning of my rmarkdown file:

output:
  pdf_document:
    fig_caption: yes

My question therefore is:

is it possible to remove the automatic generation of "Figure X" before the figure caption, when generating a PDF using rmarkdown/knitr?

Body:
You can use:

header-includes:
\renewcommand{\caption}{Figure}

in the YAML header. Then, in the code chunk, use:

```{r, fig.cap=" 5.3: Response functions"}
...
```


问:
Read an array recursively
I am learning how to apply recursion to arrays.

For example, I usually read arrays itiratively, this way:

```<code>void read_array(int *a, int n){
        int i;
        for(i = 0; i < n; ++i)
                scanf("%d", &a[i]);
        return;
}
</code>```

I would like to read an array recursively. I wrote the following function:

```<code>void read_array(int *a, int n){
        int i = n - 1;
        if (n < 0)
                return;
        else{
                if(scanf("%d", &a[n - 1 - i]) == 1){
                        read_array(a, n - 1);
                        return;
                }
        }
}
</code>```

It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.

答:
First, condition n<0 is wrong. Probably this is the cause of segfault.

Also, why even bother about calculating the index? When processing any kind of list recursively it's worth to grasp the concept of head (first element of list) and tail (everything except head) of the list. So, filling an array recursively would be defined as (in pseudo code):

```<code>void read_array() {
   read_head();
   read_tail();
}
</code>```

What is head? It's the first element of current array. What's the tail? The array starting from next element. So, read_tail is equivalent of read_array, but with the beginning moved forward by one element.

And, finally, to gather everything into one place:

```<code>void read_array(int *a, int n) {
   if(n<=0) {
       return;
   } else {
       if(scanf("%d", a) == 1) {
           read_array(a+1,n-1);
       }
   }
}
</code>```

Title: Read an array recursively

Body:
I am learning how to apply recursion to arrays.

For example, I usually read arrays itiratively, this way:

void read_array(int *a, int n){
        int i;
        for(i = 0; i < n; ++i)
                scanf("%d", &a[i]);
        return;
}

I would like to read an array recursively. I wrote the following function:

void read_array(int *a, int n){
        int i = n - 1;
        if (n < 0)
                return;
        else{
                if(scanf("%d", &a[n - 1 - i]) == 1){
                        read_array(a, n - 1);
                        return;
                }
        }
}

It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.

Body:
First, condition n<0 is wrong. Probably this is the cause of segfault.

Also, why even bother about calculating the index? When processing any kind of list recursively it's worth to grasp the concept of head (first element of list) and tail (everything except head) of the list. So, filling an array recursively would be defined as (in pseudo code):

void read_array() {
   read_head();
   read_tail();
}

What is head? It's the first element of current array. What's the tail? The array starting from next element. So, read_tail is equivalent of read_array, but with the beginning moved forward by one element.

And, finally, to gather everything into one place:

void read_array(int *a, int n) {
   if(n<=0) {
       return;
   } else {
       if(scanf("%d", a) == 1) {
           read_array(a+1,n-1);
       }
   }
}


问:
How to call more than one class from a JQuery function?
I am trying to modify html's style when one of several classes is clicked on by .click() function, but I would like not to write one function for each class. Is there any way to put every class as selectors in the same function? And if there is, how would be the sintax?

Here is the piece of my code:

```<code>$(".back").click(function(){
        console.log("widget closed");
        if( !$("body").hasClass('widget-opened')){
            $("html").css("overflow-y","auto");
        }
});
</code>```

In addition to .back, it would be nice to call two more classes (.laptop and .close)

答:
simply use comma separated list:</p>

```<code>$(".back, .laptop, .close").click(function(){
    console.log("widget closed");
    if( !$("body").hasClass('widget-opened')){
        $("html").css("overflow-y","auto");
    }
});
</code>```

Body:
I am trying to modify html's style when one of several classes is clicked on by .click() function, but I would like not to write one function for each class. Is there any way to put every class as selectors in the same function? And if there is, how would be the sintax?

Here is the piece of my code:

$(".back").click(function(){
        console.log("widget closed");
        if( !$("body").hasClass('widget-opened')){
            $("html").css("overflow-y","auto");
        }
});

In addition to .back, it would be nice to call two more classes (.laptop and .close)

Body:
simply use comma separated list:

$(".back, .laptop, .close").click(function(){
    console.log("widget closed");
    if( !$("body").hasClass('widget-opened')){
        $("html").css("overflow-y","auto");
    }
});


问:
Convert binary number 5 into list of intergers (4,1)
I have a configuration value expressed as a binary number to allow several options within the same value.

E.g. the value of 5 would be "101" or both 4 and 1.

Does anyone know of the best/fastest way to "input" the value '5' and get a list of {1,4} back?

答:
Short and fast:</p>

```<code>int input = 5;
var list = new List<int>();

for (int i = 1, j = input; i <= j; i *= 2, input >>= 1){
    if ((input & 1) == 1)
       list.Add(i);
}
</code>```

Body:
Short and fast:

int input = 5;
var list = new List<int>();

for (int i = 1, j = input; i <= j; i *= 2, input >>= 1){
    if ((input & 1) == 1)
       list.Add(i);
}


答:
Separate multiple selectors with a comma like below, to form a Multiple Selector</p>

```<code>$(".back, .laptop, .close").click(function(){
</code>```

Title: How to call more than one class from a JQuery function?

Body:
Separate multiple selectors with a comma like below, to form a Multiple Selector

$(".back, .laptop, .close").click(function(){


问:
Why is my ionic code not working properly
```<code>1. Error: Registry returned 404 for GET on https://registry.npmjs.org/geoloaction--save

2.Error: Cannot find module '@angular/tsc-wrapped/src/tsc'
</code>```

I am not getting solution of this two error plzzz help me..

答:
What npm version do you have? (npm --version)

Try updating npm first (npm install npm@latest -g)

Body:
1. Error: Registry returned 404 for GET on https://registry.npmjs.org/geoloaction--save

2.Error: Cannot find module '@angular/tsc-wrapped/src/tsc'

I am not getting solution of this two error plzzz help me..


问:
is JVM stopped while executing jmap -heap option?
usage) Jmap -heap [PID]

Hello I have jmap question

I want to view only size (-heap option)
   Heap Dump No...

If I run [jmap -heap PID]  running jvm process is STOP THE WORLD?

答:
Yes, jmap -heap will cause stop-the-world pause. Moreover, not only application threads will be stopped, but the whole target process.

jmap -heap works through HotSpot Serviceability Agent which implies that the target process is suspended while a tool is running.

More details about how Serviceability Agent works are in this answer.


答:
```<code>import math
import numpy as np

def print_wall(input, result):

    n = input.shape[0]

    for i in range(n):  # print top outer
        result.append(input[0][i])

    for i in range(n - 1):  # print right outer
        result.append(input[i + 1][n - 1])

    for i in range(n - 1):  # print bottom outer
        result.append(input[n - 1][n - 2 - i])

    for i in range(n - 2):  # print left outer
        result.append(input[n - 2 - i][0])

def clock_wise(input):

    n = input.shape[0]

    result = list()

    for i in range(math.ceil(n / 2)):  # from the outer to the inner

        print_wall(input[i: n - i, i: n - i], result)

    print(result)
</code>```

This method print from the outer of the array to the inner of the array. For example, The array is:

```<code>1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
</code>```

At first, print the outer of the 5x5 array in the clock wise direction, got 1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6;

Then, deal with the inner array(3x3):

```<code>7  8  9
12 13 14
17 18 19
</code>```

print the outer of the 3x3 array in the clock wise direction, got 7 8 9 14 19 18 17 12;

At last, deal with 13.

Title: Python: 2D to 1D list in clockwise direction?

Body:
I am a bit newbie to Python and I am looking for a function that will convert any n x n 2D list to a 1D list in clockwise direction.

For example:

When n = 3

list = [[2, 3, 5],[ 8, 7, 1],[ 0, 4, 6]]

or

list = [[2, 3, 5]
       ,[8, 7, 1]
       ,[0, 4, 6]]

would become

result = [2, 3, 5, 1, 6, 4, 0, 8, 7]

and when n = 5

list = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17, 18, 25], [14, 15, 16, 23, 24]]

or

list = [[  2,  3,  5,  9, 10]
       ,[  8,  7,  1, 11, 13]
       ,[  0,  4,  6, 21, 22]
       ,[ 12, 19, 17, 18, 25]
      , [ 14, 15, 16, 23, 24]]

would become

result = [2, 3, 5, 9, 10, 13, 22, 25, 24, 23, 16, 15, 14, 12, 0, 8, 7, 1, 11, 21, 18, 17, 19, 4, 6]

How can I efficiently do that for any value of nxn ??

Body:
import math
import numpy as np

def print_wall(input, result):

    n = input.shape[0]

    for i in range(n):  # print top outer
        result.append(input[0][i])

    for i in range(n - 1):  # print right outer
        result.append(input[i + 1][n - 1])

    for i in range(n - 1):  # print bottom outer
        result.append(input[n - 1][n - 2 - i])

    for i in range(n - 2):  # print left outer
        result.append(input[n - 2 - i][0])

def clock_wise(input):

    n = input.shape[0]

    result = list()

    for i in range(math.ceil(n / 2)):  # from the outer to the inner

        print_wall(input[i: n - i, i: n - i], result)

    print(result)

This method print from the outer of the array to the inner of the array. For example, The array is:

1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

At first, print the outer of the 5x5 array in the clock wise direction, got 1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6;

Then, deal with the inner array(3x3):

7  8  9
12 13 14
17 18 19

print the outer of the 3x3 array in the clock wise direction, got 7 8 9 14 19 18 17 12;

At last, deal with 13.


问:
Receiving data from sensor via serial port
0x4D – 0x10 – 0x00 – 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF - 0x0A //ROW 0 INFORMATION

I'm supposed to receive data as mentioned above.Actually, I want to extract the 2bytes informations one by one. I'm using python in coding.

```<code>import serial
import array

ser=serial.Serial('/dev/ttyACM0',baudrate=9600)
byte=[]
while 1 :
    c=ser.readline().encode('hex')
        print c
</code>```

答:
<blockquote>
  <p>""Question"":  , I want to extract the 2bytes informations one by one  </p>
</blockquote>

```<code>while True:
    bytes = []
    b = ser.readline()
    for i in range(3, len(b)-1, 2):
        bytes.append( int (b[i:i+2], 16 ) )
</code>```

Body:
0x4D – 0x10 – 0x00 – 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF - 0x0A //ROW 0 INFORMATION

I'm supposed to receive data as mentioned above.Actually, I want to extract the 2bytes informations one by one. I'm using python in coding.

import serial
import array

ser=serial.Serial('/dev/ttyACM0',baudrate=9600)
byte=[]
while 1 :
    c=ser.readline().encode('hex')
        print c

Body:
""Question"":  , I want to extract the 2bytes informations one by one

while True:
    bytes = []
    b = ser.readline()
    for i in range(3, len(b)-1, 2):
        bytes.append( int (b[i:i+2], 16 ) )


问:
Register device id directly with Amazon SNS
I am using the Amazon Web Service to send push notifications directly to a device. After I install the app I get the device id, that I need to manually add to the Amazon SNS. I would like to know if there is anyway to register the device id directly with the amazon server the moment the user starts the application.

I have read this, but found it difficult to understand. Does anyone have any previous experience of how to do this?

EDIT 2 (What I have done so far)

I've followed the instructions from this link

I download the snspobilepush.zip file as instructed and extract and import the project into eclipse. I add the GCM project number, add the jar files and run the application. I get my device registration Id.

I open the Amazon SNS, add my device id and I publish a message. I receive the message on my mobile phone. Works great so far.

MY PROBLEM

I would be having a lot of potential users for my application. So adding every device id manually to the SNS makes no sense. I need the Amazon SNS to directly register my device id when I start the app. Is there any option for me to do that? I couldn't  find any definitive answer in the docs.

This link tells me to Use the "AWS Token Vending Service". However, I could not find any example of how to do that.

答:
This is working for Firebase and Cognito. An AsyncTask is necessary to avoid running on the Main Thread.</p>

```<code>private class RegisterIdForAWS extends AsyncTask<String, Void, Void> {

        private Exception exception;

        protected Void doInBackground(String... urls) {
            try {
                String pushNotificationRegId = FirebaseInstanceId.getInstance().getToken();

                if (pushNotificationRegId != null) {

                    CognitoCachingCredentialsProvider provider = new CognitoCachingCredentialsProvider(
                            getApplicationContext(),
                            "us-west-2:aaaaaaaaa-1234-1234-1234-0bbbbbbbbbbbb",
                            Regions.US_WEST_2);
                    String platformApplicationArn = "arn:aws:sns:us-west-2:123456789:app/GCM/appname";
                    AmazonSNSClient pushClient = new AmazonSNSClient(provider);
                    pushClient.setRegion(Region.getRegion(Regions.US_WEST_2));

                    String customPushData = "";
                    CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
                    platformEndpointRequest.setCustomUserData(customPushData);
                    platformEndpointRequest.setToken(pushNotificationRegId);
                    platformEndpointRequest.setPlatformApplicationArn(platformApplicationArn);
                    CreatePlatformEndpointResult result = pushClient.createPlatformEndpoint(platformEndpointRequest);
                    Log.w(TAG, "Amazon Push reg result: " + result);
                }
            } catch (Exception e) {
                this.exception = e;
            }

            return null;
        }

        protected void onPostExecute(String text) {
            Log.w(TAG, "Amazon Push reg Finished");
        }
    }
</code>```

Body:
This is working for Firebase and Cognito. An AsyncTask is necessary to avoid running on the Main Thread.

private class RegisterIdForAWS extends AsyncTask<String, Void, Void> {

        private Exception exception;

        protected Void doInBackground(String... urls) {
            try {
                String pushNotificationRegId = FirebaseInstanceId.getInstance().getToken();

                if (pushNotificationRegId != null) {

                    CognitoCachingCredentialsProvider provider = new CognitoCachingCredentialsProvider(
                            getApplicationContext(),
                            "us-west-2:aaaaaaaaa-1234-1234-1234-0bbbbbbbbbbbb",
                            Regions.US_WEST_2);
                    String platformApplicationArn = "arn:aws:sns:us-west-2:123456789:app/GCM/appname";
                    AmazonSNSClient pushClient = new AmazonSNSClient(provider);
                    pushClient.setRegion(Region.getRegion(Regions.US_WEST_2));

                    String customPushData = "";
                    CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
                    platformEndpointRequest.setCustomUserData(customPushData);
                    platformEndpointRequest.setToken(pushNotificationRegId);
                    platformEndpointRequest.setPlatformApplicationArn(platformApplicationArn);
                    CreatePlatformEndpointResult result = pushClient.createPlatformEndpoint(platformEndpointRequest);
                    Log.w(TAG, "Amazon Push reg result: " + result);
                }
            } catch (Exception e) {
                this.exception = e;
            }

            return null;
        }

        protected void onPostExecute(String text) {
            Log.w(TAG, "Amazon Push reg Finished");
        }
    }


问:
Constructor chaining in PowerShell - call other constructors in the same class
I was doing some testing and stumbled upon the following:

You can overload methods in PoShv5 as you wish. If you call the method without parameters, it can internally call the method with parameters, to keep your code non-redundant. I expected this to be also true for constructors.

In this example, the last constructor is working as expected. The other constructors only return objects without set values.

```<code>Class car {
    [string]$make
    [string]$model
    [int]$Speed
    [int]$Year

    speedUp (){
        $this.speedUp(5)
    }
    speedUp ([int]$velocity){
        $this.speed += $velocity
    }

    # Constructor
    car () {
        [car]::new('mall', $Null, $null)
    }

    car ([string]$make, [string]$model) {
        [car]::new($make, $model, 2017)
    }

    car ([string]$make, [string]$model, [int]$Year) {
        $this.make = $make
        $this.model = $model
        $this.Year = $year
    }
}

[car]::new() # returns "empty" car
[car]::new('Make', 'Nice model') # returns also an "empty" one
[car]::new( 'make', 'nice model', 2017) # returns a "filled" instance
</code>```

Is there a way to fix this? Did I miss something?

答:
TL;DR: No!

What you're looking for (overloaded constructors calling each other in succession) is also colloquially known as constructor chaining, and looks roughly like this in C#:

```<code>class Car
{
    string Make;
    string Model;
    int Year;

    Car() : this("mall", null)
    {
    }

    Car(string make, string model) : this(make, model, 2017)
    {
    }

    Car(string make, string model, int Year)
    {
        this.Make = make;
        this.Model = model;
        this.Year = year;
    }
}
</code>```

Unfortunately, PowerShell doesn't seem to have any syntax for this - you can't do:

```<code>Car() : $this("Porsche") {}
Car([string]$Make) {}
</code>```

without having the parser throw up at you for missing the body definition of your constructor, and I don't expect to see it anytime soon - the PowerShell team has expressed an explicit desire not to become the maintainers of a new watered down C# - which I can perfectly well understand :-)

You'll just have to re-implement the member assignments in each constructor definition.

Body:
I was doing some testing and stumbled upon the following:

You can overload methods in PoShv5 as you wish. If you call the method without parameters, it can internally call the method with parameters, to keep your code non-redundant. I expected this to be also true for constructors.

In this example, the last constructor is working as expected. The other constructors only return objects without set values.

Class car {
    [string]$make
    [string]$model
    [int]$Speed
    [int]$Year

    speedUp (){
        $this.speedUp(5)
    }
    speedUp ([int]$velocity){
        $this.speed += $velocity
    }

    # Constructor
    car () {
        [car]::new('mall', $Null, $null)
    }

    car ([string]$make, [string]$model) {
        [car]::new($make, $model, 2017)
    }

    car ([string]$make, [string]$model, [int]$Year) {
        $this.make = $make
        $this.model = $model
        $this.Year = $year
    }
}

[car]::new() # returns "empty" car
[car]::new('Make', 'Nice model') # returns also an "empty" one
[car]::new( 'make', 'nice model', 2017) # returns a "filled" instance

Is there a way to fix this? Did I miss something?

Body:
TL;DR: No!

What you're looking for (overloaded constructors calling each other in succession) is also colloquially known as constructor chaining, and looks roughly like this in C#:

class Car
{
    string Make;
    string Model;
    int Year;

    Car() : this("mall", null)
    {
    }

    Car(string make, string model) : this(make, model, 2017)
    {
    }

    Car(string make, string model, int Year)
    {
        this.Make = make;
        this.Model = model;
        this.Year = year;
    }
}

Unfortunately, PowerShell doesn't seem to have any syntax for this - you can't do:

Car() : $this("Porsche") {}
Car([string]$Make) {}

without having the parser throw up at you for missing the body definition of your constructor, and I don't expect to see it anytime soon - the PowerShell team has expressed an explicit desire not to become the maintainers of a new watered down C# - which I can perfectly well understand :-)

You'll just have to re-implement the member assignments in each constructor definition.


问:
How to split the string before the 3rd occurrence of a "/" in Java
I have:

```<code>/xxx/yyy/aaa/bbb/abc.xml (or)
/xxx/yyy/aaa/abc.xml (or)
/xxx/yyy/aaa/bbb/ccc/abc.xml
</code>```

But I need only:

```<code>/xxx/yyyy
</code>```

How do I implement this in Java?
Thanks in advance.

答:
```<code>FilenameUtils.getFullPathNoEndSeparator(str).replaceAll("((/[^/]*){2}).*", "$1")
</code>```

I used this its working fine for me.

Body:
I have:

/xxx/yyy/aaa/bbb/abc.xml (or)
/xxx/yyy/aaa/abc.xml (or)
/xxx/yyy/aaa/bbb/ccc/abc.xml

But I need only:

/xxx/yyyy

How do I implement this in Java?
Thanks in advance.

Body:
FilenameUtils.getFullPathNoEndSeparator(str).replaceAll("((/[^/]*){2}).*", "$1")

I used this its working fine for me.


问:
Kubernetes V1DeleteOptions useless for namespace delete?
Seems like V1DeleteOptions in Kubernetes namespace delete API is useless.

For example,

I created a service in a namespace. Later on, I tried to delete the
namespace and setting V1DeleteOptions.propagationPolicy to false.

But turns out the namespace and the service are both deleted
immediately.

I also tried setting V1DeleteOptions.GracePeriodSeconds to 100 just
to test the grace period. But still, the namespace and the service
are deleted immediately.

So, does the V1DeleteOptions in Kubernetes namespace delete API do anything at all?

答:
look like this flag is used for 'how garbage collection will be performed'

https://github.com/kubernetes-incubator/client-python/blob/master/kubernetes/docs/V1DeleteOptions.md

Note:
when we delete the namespace, it should cleanup the all object inside the name. I think delete command worked properly.


问:
Dependent type or argument in decltype in function definition fails to compile when declared without decltype
I've been playing with deduced return types in definitions that resolve to the same type as the declaration. This works:

```<code>template <typename>
struct Cls {
  static std::size_t f();
};

template <typename T>
decltype(sizeof(int)) Cls<T>::f()  { return 0; }
</code>```

But if I change the definition to something that should be equivalent by replacing sizeof(int) with sizeof(T) it fails

```<code>template <typename T>
decltype(sizeof(T)) Cls<T>::f() { return 0; }
</code>```

gcc's error (clang is almost identical):

```<code>error: prototype for ‘decltype (sizeof (T)) Cls<T>::f()’ does not match any in class ‘Cls<T>’
 decltype(sizeof(T)) Cls<T>::f() { return 0; }
                     ^~~~~~
so.cpp:4:24: error: candidate is: static std::size_t Cls<T>::f()
     static std::size_t f();
                        ^
</code>```

The same problem arises with function parameter types:

```<code>template <typename>
struct Cls {
  static void f(std::size_t);
};

template <typename T>
void Cls<T>::f(decltype(sizeof(T))) { } // sizeof(int) works instead
</code>```

Stranger yet, if the declaration and definition match and both use decltype(sizeof(T)) it compiles successfully, and I can static_assert that the return type is size_t. The following compiles successfully:

```<code>#include <type_traits>

template <typename T>
struct Cls {
  static decltype(sizeof(T)) f();
};

template <typename T>
decltype(sizeof(T)) Cls<T>::f() { return 0; }

static_assert(std::is_same<std::size_t, decltype(Cls<int>::f())>{}, "");
</code>```

Update with another example. This isn't a dependent type but still fails.

```<code>template <int I>
struct Cls {
  static int f();
};

template <int I>
decltype(I) Cls<I>::f() { return I; }
</code>```

If I use decltype(I) in both the definition and declaration it works, if I use int in both the definition and declaration it works, but having the two differ fails.

Update 2:
A similar example. If Cls is changed to not be a class template, it compiles successfully.

```<code>template <typename>
struct Cls {
  static int f();
  using Integer = decltype(Cls::f());
};

template <typename T>
typename Cls<T>::Integer Cls<T>::f() { return I; }
</code>```

Update 3:
Another failing example from M.M. A templated member function of a non-templated class.

```<code>struct S {
  template <int N>
  int f();
};

template <int N>
decltype(N) S::f() {}
</code>```

Why is it illegal for the declaration and definition to disagree with a dependent type only? Why is it affected even when the type itself isn't dependent as with the template <int I> above?

答:
Because when there is a template parameter involved, decltype returns an unqiue dependent type according to the standard, see below. If there is no template parameter then it resolves to an obvious size_t. So in this case you have to choose either both declaration and definition have an independent expression (e.g. size_t/decltype(sizeof(int))), as a return type, or both have dependent expression (e.g. decltype(sizeof(T))), which resolved to an unique dependent type and considered to be equivalent, if their expressions are equivalent (see below).

In this post I am using the C++ standard draft N3337.

§ 7.1.6.2 [dcl.type.simpl]

¶ 4

The type denoted by decltype(e) is defined as follows:
  — if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e)
  is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded func-
  tions, the program is ill-formed;

— otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;

— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;

— otherwise, decltype(e) is the type of e.

This explains what is decltype(sizeof(int)). But for decltype(sizeof(T)) there is another section explaining what it is.

§ 14.4 [temp.type]

¶ 2

If an expression e involves a template parameter, decltype(e) denotes a unique dependent type. Two such
  decltype-specifiers refer to the same type only if their expressions are equivalent (14.5.6.1). [ Note: however,
  it may be aliased, e.g., by a typedef-name. — end note ]

In Clang LLVM sources version 3.9 in file lib/AST/Type.cpp

```<code>DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
  // C++11 [temp.type]p2: "If an expression e involves a template parameter,
  // decltype(e) denotes a unique dependent type." Hence a decltype type is
  // type-dependent even if its expression is only instantiation-dependent.
  : Type(Decltype, can, E->isInstantiationDependent(),
         E->isInstantiationDependent(),
         E->getType()->isVariablyModifiedType(),
         E->containsUnexpandedParameterPack()),
</code>```

The important phrase starts as "Hence a decltype...". It again clarifies the situation.

Again in Clang sources version 3.9 in file lib/AST/ASTContext.cpp

```<code>QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
  DecltypeType *dt;

  // C++11 [temp.type]p2:
  //   If an expression e involves a template parameter, decltype(e) denotes a
  //   unique dependent type. Two such decltype-specifiers refer to the same
  //   type only if their expressions are equivalent (14.5.6.1).
  if (e->isInstantiationDependent()) {
    llvm::FoldingSetNodeID ID;
    DependentDecltypeType::Profile(ID, *this, e);

    void *InsertPos = nullptr;
    DependentDecltypeType *Canon
      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
    if (!Canon) {
      // Build a new, canonical typeof(expr) type.
      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
    }
    dt = new (*this, TypeAlignment)
        DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
  } else {
    dt = new (*this, TypeAlignment)
        DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
  }
  Types.push_back(dt);
  return QualType(dt, 0);
}
</code>```

So you see Clang gathers and picks those unique dependent types of decltype in/from a special set.

Why compiler is so stupid that it does not see that the expression of decltype is sizeof(T) that is always size_t? Yes, this is obvious to a human reader. But when you design and implement a formal grammar and semantic rules, especially for such complicated languages as C++, you have to group problems up and define the rules for them, rather than just come up with a rule for each particular problem, in the latter way you just wont be able to move with your language/compiler design. The same here there is no just rule: if decltype has a function call expression that does not need any template parameters resolution - resolve decltype to the return type of the function. There is more than that, there are so many cases you need to cover, that you come up with a more generic rule, like the quoted above from the standard (14.4[2]).

In addition, a similar non-obvious case with auto, decltype(auto) found by AndyG in C++-14 (N4296, § 7.1.6.4 [dcl.spec.auto] 12/13):

§ 7.1.6.4 [dcl.spec.auto]

¶ 13

Redeclarations or specializations of a function or function template with a declared return type that uses a
  placeholder type shall also use that placeholder, not a deduced type. [ Example:

```<code>auto f();
auto f() { return 42; } // return type is int
auto f();               // OK
int f();                // error, cannot be overloaded with auto f()
decltype(auto) f();     // error, auto and decltype(auto) don’t match
</code>```

Changes in C++17, Document Number >= N4582

Change in the standard draft N4582 from March 2016 (thanks to bogdan) generalizes the statement:

§ 17.4 (old § 14.4) [temp.type]

¶ 2

If an expression e is type-dependent (17.6.2.2), decltype(e) denotes a unique dependent type. Two such
  decltype-specifiers refer to the same type only if their expressions are equivalent (17.5.6.1). [ Note: however,
  such a type may be aliased, e.g., by a typedef-name. — end note ]

This change leads to another section describing the type dependent expression that looks quite strange to our particular case.

§ 17.6.2.2 [temp.dep.expr] (old § 14.6.2.2)

¶ 4

Expressions of the following forms are never type-dependent (because the type of the expression cannot be
  dependent):

```<code>...
sizeof ( type-id )
...
</code>```

There are further sections on value-dependent expressions where sizeof can be value-dependent if the type-id dependent. There is no relation between value-dependent expression and decltype. After some thinking, I did not find any reason why decltype(sizeof(T)) must not or cannot resolve into size_t. And I would assume that was quite sneaky change ("involves a template parameter" to "type-dependent") in the standard that compiler developers did not pay much attention to (maybe overwhelmed by many other changes, maybe did not think that it might actually change something, just a simple formulation improvement). The change does make sense, because sizeof(T) is not type-dependent, it is value-dependent. decltype(e)'s operand is a unevaluated operand, i.e. does not care about value, only about type. That is why decltype returns a unique type only when e is type-dependent. sizeof(e) might be only value-dependent.

I tried the code with clang 5, gcc 8 -std=c++1z - the same result: error. I went further and tried this code:

```<code>template <typename>
struct Cls {
  static std::size_t f();
};

template <typename T>
decltype(sizeof(sizeof(T))) Cls<T>::f() {
  return 0;
}
</code>```

The same error was given, even that sizeof(sizeof(T)) is neither type- or value-dependent (see this post). This gives me a reason to assume that the compilers are working in an old way of C++-11/14 standard (i.e. "involves a template parameter") like in the source snippet above from clang 3.9 source (I can verify that the latest developing clang 5.0 has the same lines, have not found anything related to this new change in the standard), but not type-dependent.

Body:
I've been playing with deduced return types in definitions that resolve to the same type as the declaration. This works:

template <typename>
struct Cls {
  static std::size_t f();
};

template <typename T>
decltype(sizeof(int)) Cls<T>::f()  { return 0; }

But if I change the definition to something that should be equivalent by replacing sizeof(int) with sizeof(T) it fails

template <typename T>
decltype(sizeof(T)) Cls<T>::f() { return 0; }

gcc's error (clang is almost identical):

error: prototype for ‘decltype (sizeof (T)) Cls<T>::f()’ does not match any in class ‘Cls<T>’
 decltype(sizeof(T)) Cls<T>::f() { return 0; }
                     ^~~~~~
so.cpp:4:24: error: candidate is: static std::size_t Cls<T>::f()
     static std::size_t f();
                        ^

The same problem arises with function parameter types:

template <typename>
struct Cls {
  static void f(std::size_t);
};

template <typename T>
void Cls<T>::f(decltype(sizeof(T))) { } // sizeof(int) works instead

Stranger yet, if the declaration and definition match and both use decltype(sizeof(T)) it compiles successfully, and I can static_assert that the return type is size_t. The following compiles successfully:

#include <type_traits>

template <typename T>
struct Cls {
  static decltype(sizeof(T)) f();
};

template <typename T>
decltype(sizeof(T)) Cls<T>::f() { return 0; }

static_assert(std::is_same<std::size_t, decltype(Cls<int>::f())>{}, "");

Update with another example. This isn't a dependent type but still fails.

template <int I>
struct Cls {
  static int f();
};

template <int I>
decltype(I) Cls::f() { return I; }

If I use decltype(I) in both the definition and declaration it works, if I use int in both the definition and declaration it works, but having the two differ fails.

Update 2:
A similar example. If Cls is changed to not be a class template, it compiles successfully.

template <typename>
struct Cls {
  static int f();
  using Integer = decltype(Cls::f());
};

template <typename T>
typename Cls<T>::Integer Cls<T>::f() { return I; }

Update 3:
Another failing example from M.M. A templated member function of a non-templated class.

struct S {
  template <int N>
  int f();
};

template <int N>
decltype(N) S::f() {}

Why is it illegal for the declaration and definition to disagree with a dependent type only? Why is it affected even when the type itself isn't dependent as with the template <int I> above?

Body:
Because when there is a template parameter involved, decltype returns an unqiue dependent type according to the standard, see below. If there is no template parameter then it resolves to an obvious size_t. So in this case you have to choose either both declaration and definition have an independent expression (e.g. size_t/decltype(sizeof(int))), as a return type, or both have dependent expression (e.g. decltype(sizeof(T))), which resolved to an unique dependent type and considered to be equivalent, if their expressions are equivalent (see below).

In this post I am using the C++ standard draft N3337.

§ 7.1.6.2 [dcl.type.simpl]

¶ 4

The type denoted by decltype(e) is defined as follows:
  — if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e)
  is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded func-
  tions, the program is ill-formed;

— otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;

— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;

— otherwise, decltype(e) is the type of e.

This explains what is decltype(sizeof(int)). But for decltype(sizeof(T)) there is another section explaining what it is.

§ 14.4 [temp.type]

¶ 2

If an expression e involves a template parameter, decltype(e) denotes a unique dependent type. Two such
  decltype-specifiers refer to the same type only if their expressions are equivalent (14.5.6.1). [ Note: however,
  it may be aliased, e.g., by a typedef-name. — end note ]

In Clang LLVM sources version 3.9 in file lib/AST/Type.cpp

DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
  // C++11 [temp.type]p2: "If an expression e involves a template parameter,
  // decltype(e) denotes a unique dependent type." Hence a decltype type is
  // type-dependent even if its expression is only instantiation-dependent.
  : Type(Decltype, can, E->isInstantiationDependent(),
         E->isInstantiationDependent(),
         E->getType()->isVariablyModifiedType(),
         E->containsUnexpandedParameterPack()),

The important phrase starts as "Hence a decltype...". It again clarifies the situation.

Again in Clang sources version 3.9 in file lib/AST/ASTContext.cpp

QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
  DecltypeType *dt;

  // C++11 [temp.type]p2:
  //   If an expression e involves a template parameter, decltype(e) denotes a
  //   unique dependent type. Two such decltype-specifiers refer to the same
  //   type only if their expressions are equivalent (14.5.6.1).
  if (e->isInstantiationDependent()) {
    llvm::FoldingSetNodeID ID;
    DependentDecltypeType::Profile(ID, *this, e);

    void *InsertPos = nullptr;
    DependentDecltypeType *Canon
      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
    if (!Canon) {
      // Build a new, canonical typeof(expr) type.
      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
    }
    dt = new (*this, TypeAlignment)
        DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
  } else {
    dt = new (*this, TypeAlignment)
        DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
  }
  Types.push_back(dt);
  return QualType(dt, 0);
}

So you see Clang gathers and picks those unique dependent types of decltype in/from a special set.

Why compiler is so stupid that it does not see that the expression of decltype is sizeof(T) that is always size_t? Yes, this is obvious to a human reader. But when you design and implement a formal grammar and semantic rules, especially for such complicated languages as C++, you have to group problems up and define the rules for them, rather than just come up with a rule for each particular problem, in the latter way you just wont be able to move with your language/compiler design. The same here there is no just rule: if decltype has a function call expression that does not need any template parameters resolution - resolve decltype to the return type of the function. There is more than that, there are so many cases you need to cover, that you come up with a more generic rule, like the quoted above from the standard (14.4[2]).

In addition, a similar non-obvious case with auto, decltype(auto) found by AndyG in C++-14 (N4296, § 7.1.6.4 [dcl.spec.auto] 12/13):

§ 7.1.6.4 [dcl.spec.auto]

¶ 13

Redeclarations or specializations of a function or function template with a declared return type that uses a
  placeholder type shall also use that placeholder, not a deduced type. [ Example:

auto f();
auto f() { return 42; } // return type is int
auto f();               // OK
int f();                // error, cannot be overloaded with auto f()
decltype(auto) f();     // error, auto and decltype(auto) don’t match

Changes in C++17, Document Number >= N4582

Change in the standard draft N4582 from March 2016 (thanks to bogdan) generalizes the statement:

§ 17.4 (old § 14.4) [temp.type]

¶ 2

If an expression e is type-dependent (17.6.2.2), decltype(e) denotes a unique dependent type. Two such
  decltype-specifiers refer to the same type only if their expressions are equivalent (17.5.6.1). [ Note: however,
  such a type may be aliased, e.g., by a typedef-name. — end note ]

This change leads to another section describing the type dependent expression that looks quite strange to our particular case.

§ 17.6.2.2 [temp.dep.expr] (old § 14.6.2.2)

¶ 4

Expressions of the following forms are never type-dependent (because the type of the expression cannot be
  dependent):

...
sizeof ( type-id )
...

There are further sections on value-dependent expressions where sizeof can be value-dependent if the type-id dependent. There is no relation between value-dependent expression and decltype. After some thinking, I did not find any reason why decltype(sizeof(T)) must not or cannot resolve into size_t. And I would assume that was quite sneaky change ("involves a template parameter" to "type-dependent") in the standard that compiler developers did not pay much attention to (maybe overwhelmed by many other changes, maybe did not think that it might actually change something, just a simple formulation improvement). The change does make sense, because sizeof(T) is not type-dependent, it is value-dependent. decltype(e)'s operand is a unevaluated operand, i.e. does not care about value, only about type. That is why decltype returns a unique type only when e is type-dependent. sizeof(e) might be only value-dependent.

I tried the code with clang 5, gcc 8 -std=c++1z - the same result: error. I went further and tried this code:

template <typename>
struct Cls {
  static std::size_t f();
};

template <typename T>
decltype(sizeof(sizeof(T))) Cls<T>::f() {
  return 0;
}

The same error was given, even that sizeof(sizeof(T)) is neither type- or value-dependent (see this post). This gives me a reason to assume that the compilers are working in an old way of C++-11/14 standard (i.e. "involves a template parameter") like in the source snippet above from clang 3.9 source (I can verify that the latest developing clang 5.0 has the same lines, have not found anything related to this new change in the standard), but not type-dependent.


问:
Installing Chinese Language Pack on Linux Red Hat 6.0 Enterprise
I have a Linux Red Hat 6.0 Enterprise server in China and need to install the Chinese language pack on it.  It's current language is English, and I have a progress database that outputs some characters in Chinese, but doesn't render right since I don't have the Chinese language/fonts installed.  How can I get these installed?  I don't have the installation CD, as I inherited this server from my predecessor.</p>

答:
In order to see all language packages available through this interface, you can type the following command:

```<code># yum grouplist
</code>```

This will output all group packages, the last section of which is “Available Language Groups”. Note that some packs may already be installed, in which case, they will be visible under “Installed Language Packs” at the top of the list. In this case, “chinese-fonts” is now “Chinese Support”.

To install chinese package, run the following command:

```<code># yum groupinstall "Chinese Support"
</code>```

Body:
In order to see all language packages available through this interface, you can type the following command:

# yum grouplist

This will output all group packages, the last section of which is “Available Language Groups”. Note that some packs may already be installed, in which case, they will be visible under “Installed Language Packs” at the top of the list. In this case, “chinese-fonts” is now “Chinese Support”.

To install chinese package, run the following command:

# yum groupinstall "Chinese Support"


问:
Apache ActiveMQ Temporary Store limit warning?
I have been facing this below WARN in active.log file very often . Don't understand what exactly every warning means . Can some please help me to understand this and how to fix

1, 2017-06-07 11:11:12,051 | WARN  | Temporary Store limit is 51200 mb
  (current store usage is 0 mb). The data directory:
  /local/apps/apache-activemq-5.14.3/data only has 5924 mb of usable
  space. - resetting to maximum available disk space: 5924 mb |
  org.apache.activemq.broker.BrokerService | main

2, 2017-06-07 11:36:02,358 | WARN  | Transport Connection to: tcp://10.235.454.23:59053 failed: java.io.EOFException |
  org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ
  Transport: tcp:///10.123.343.345:59053@61616
      2017-06-07 11:37:58,441 | WARN  | Transport Connection to: tcp://10.123.345.768:46840 failed: java.io.EOFException |
  org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ
  Transport: tcp:///10.240.123.234:46840@61616

3, 2017-06-07 11:41:54,376 | WARN  | persistent="false", ignoring
  configured persistenceAdapter:
  KahaDBPersistenceAdapter[/local/apps/apache-activemq-5.14.3/data/kahadb]
  | org.apache.activemq.broker.BrokerService | main

答:
To resolve this error/warning you should limit the broker's temporary store limit to a value that is available on disk. This value is set in the broker's system usage configuration by the tempUsage limit in apache-activemq-5.9.0-bin\apache-activemq-5.9.0\conf\activemq.xml:

```<code><systemUsage>
   <systemUsage>
      <memoryUsage>
          <memoryUsage limit="64 mb"/>
      </memoryUsage>
      <storeUsage>
         <storeUsage limit="100 gb"/>
      </storeUsage>
      <tempUsage>
         <tempUsage limit="50 gb"/>
      </tempUsage>
   </systemUsage>
</systemUsage>
</code>```

While the broker may perform ok at first with this condition it has the potential to lead to unexpected results such IOExceptions rather than triggering Producer Flow Control when the resources are exhausted. It is recommend to fix this situation by adjusting the usages limits appropriately.

Root Cause

The broker has requested to allocate more disk resources than what is available.
Please check you disk space memory where activemq is located before setting up the tempusage memory .

ActiveMQ provides mechanism to tune memory usage per destination

```<code><policyEntry queue=">" producerFlowControl="false" memoryLimit="256mb">
</code>```

I have used wild card character in queue name [> is used to recursively match any destination starting from this name] in the above configuration it is for any queues
Anyways for each destnation you can use

Per-destination—to set a memory limit on a destination, For example, to limit the amount of memory on the FOO.BAR.TEST queue to 10 MB, define a policy entry like the following:

```<code><destinationPolicy>
    <policyMap>
        <policyEntries>
            <policyEntry topic="FOO.BAR.TEST" memoryLimit="5MB" />
        </policyEntries>
    </policyMap>
</destinationPolicy>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To resolve this error/warning you should limit the broker's temporary store limit to a value that is available on disk. This value is set in the broker's system usage configuration by the tempUsage limit in apache-activemq-5.9.0-bin\apache-activemq-5.9.0\conf\activemq.xml:

<systemUsage>
   <systemUsage>
      <memoryUsage>
          <memoryUsage limit="64 mb"/>
      </memoryUsage>
      <storeUsage>
         <storeUsage limit="100 gb"/>
      </storeUsage>
      <tempUsage>
         <tempUsage limit="50 gb"/>
      </tempUsage>
   </systemUsage>
</systemUsage>

While the broker may perform ok at first with this condition it has the potential to lead to unexpected results such IOExceptions rather than triggering Producer Flow Control when the resources are exhausted. It is recommend to fix this situation by adjusting the usages limits appropriately.

Root Cause

The broker has requested to allocate more disk resources than what is available.
Please check you disk space memory where activemq is located before setting up the tempusage memory .

ActiveMQ provides mechanism to tune memory usage per destination

<policyEntry queue=">" producerFlowControl="false" memoryLimit="256mb">

I have used wild card character in queue name [> is used to recursively match any destination starting from this name] in the above configuration it is for any queues
Anyways for each destnation you can use

Per-destination—to set a memory limit on a destination, For example, to limit the amount of memory on the FOO.BAR.TEST queue to 10 MB, define a policy entry like the following:

<destinationPolicy>
    <policyMap>
        <policyEntries>
            <policyEntry topic="FOO.BAR.TEST" memoryLimit="5MB" />
        </policyEntries>
    </policyMap>
</destinationPolicy>


问:
Passing data to a bootstrap modal
I've got a couple of hyperlinks that each have an ID attached. When I click on this link, I want to open a modal ( http://twitter.github.com/bootstrap/javascript.html#modals ), and pass this ID to the modal. I searched on google, but I couldn't find anything that could help me.

This is the code:

```<code><a data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog"></a>
</code>```

Which should open:

```<code><div class="modal hide" id="addBookDialog">
    <div class="modal-body">
        <input type="hidden" name="bookId" id="bookId" value=""/>
    </div>
</div>
</code>```

With this piece of code:

```<code>$(document).ready(function () {
    $(".open-AddBookDialog").click(function () {
        $('#bookId').val($(this).data('id'));
        $('#addBookDialog').modal('show');
    });
});
</code>```

However, when I click the hyperlink, nothing happens. When I give the hyperlink , the modal opens just fine, but it does't contain any data.

I followed this example: How to pass values arguments to modal.show() function in Bootstrap

(and I also tried this: href="https://stackoverflow.com/questions/7845866/how-to-set-the-input-value-in-a-modal-dialogue">How to set the input value in a modal dialogue?)

答:
Your code would have worked with correct modal html structure.

$(function(){
  $(".open-AddBookDialog").click(function(){
     $('#bookId').val($(this).data('id'));
    $("#addBookDialog").modal("show");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Open Modal

<div id="addBookDialog" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
       <input type="hidden" name="bookId" id="bookId" value=""/>
      </div>

    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</html></code>```

Title: Passing data to a bootstrap modal

Body:
I've got a couple of hyperlinks that each have an ID attached. When I click on this link, I want to open a modal ( http://twitter.github.com/bootstrap/javascript.html#modals ), and pass this ID to the modal. I searched on google, but I couldn't find anything that could help me.

This is the code:

Which should open:

        <input type="hidden" name="bookId" id="bookId" value=""/>

With this piece of code:

$(document).ready(function () {
    $(".open-AddBookDialog").click(function () {
        $('#bookId').val($(this).data('id'));
        $('#addBookDialog').modal('show');
    });
});

However, when I click the hyperlink, nothing happens. When I give the hyperlink , the modal opens just fine, but it does't contain any data.

I followed this example: How to pass values arguments to modal.show() function in Bootstrap

(and I also tried this: How to set the input value in a modal dialogue?)

Body:
Your code would have worked with correct modal html structure.

$(function(){
  $(".open-AddBookDialog").click(function(){
     $('#bookId').val($(this).data('id'));
    $("#addBookDialog").modal("show");
  });
});

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<a data-id="@book.Id" title="Add this item" class="open-AddBookDialog">Open Modal</a>

<div id="addBookDialog" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
       <input type="hidden" name="bookId" id="bookId" value=""/>
      </div>

    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</html>


问:
Hibernate, dealing with Criteria and left outer join condition
I've an existing piece of code like follow:

```<code>Criteria crit = session.createCriteria(myClass);
crit.createAlias(TAB1, TAB1, JoinType.LEFT_OUTER_JOIN);
crit.createAlias(TAB1 + ".table2", TAB2, JoinType.LEFT_OUTER_JOIN);
crit.add(Restrictions.eq(TAB1 + ".deleted", Boolean.FALSE));
crit.add(Restrictions.eq(TAB2 + ".id", someId));
</code>```

This "generates" a sql query like follow:

```<code>SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id
WHERE tab1_.deleted=0
AND tab2_.id = 1234
</code>```

I need to put filters in the JOIN condition rather than in the WHERE clause.

To be clear, I need to have the following query:

```<code>SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id AND tab1_.deleted=0
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id AND AND tab2_.id = 1234
</code>```

How can I do this?

Thanks

答:
Here is a decent example right from Hibernates confluence page:

```<code>public class PersonDao extends HibernateDaoSupport {
   public List<Person> findByName() {
      Criteria criteria = getSession().createCriteria(Person.class, "p");
      criteria.createCriteria("p.names", "names", JoinType.INNER_JOIN, Restrictions.eq("name", "John"));
      return criteria.list();
   }
}
</code>```

Produces

```<code>select this_.id as y0_ from person this_
inner join debtor_info this_1_ on this_.id=this_1_.id
left outer join person_person_name personname3_ on this_.id=personname3_.person_id and ( name1_.name=? )
left outer join person_name name1_ on personname3_.person_name_id=name1_.id and ( name1_.name=? )
</code>```

With that example I believe your code should look something like

```<code>Criteria crit = session.createCriteria(MyClass.class, "mine");
crit.createAlias("mine.names", "name", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("name", Boolean.FALSE));
crit.createAlias("q.id", "id", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("id", someId));
</code>```

Body:
I've an existing piece of code like follow:

Criteria crit = session.createCriteria(myClass);
crit.createAlias(TAB1, TAB1, JoinType.LEFT_OUTER_JOIN);
crit.createAlias(TAB1 + ".table2", TAB2, JoinType.LEFT_OUTER_JOIN);
crit.add(Restrictions.eq(TAB1 + ".deleted", Boolean.FALSE));
crit.add(Restrictions.eq(TAB2 + ".id", someId));

This "generates" a sql query like follow:

SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id
WHERE tab1_.deleted=0
AND tab2_.id = 1234

I need to put filters in the JOIN condition rather than in the WHERE clause.

To be clear, I need to have the following query:

SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id AND tab1_.deleted=0
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id AND AND tab2_.id = 1234

How can I do this?

Thanks

Body:
Here is a decent example right from Hibernates confluence page:

public class PersonDao extends HibernateDaoSupport {
   public List<Person> findByName() {
      Criteria criteria = getSession().createCriteria(Person.class, "p");
      criteria.createCriteria("p.names", "names", JoinType.INNER_JOIN, Restrictions.eq("name", "John"));
      return criteria.list();
   }
}

Produces

select this_.id as y0_ from person this_
inner join debtor_info this_1_ on this_.id=this_1_.id
left outer join person_person_name personname3_ on this_.id=personname3_.person_id and ( name1_.name=? )
left outer join person_name name1_ on personname3_.person_name_id=name1_.id and ( name1_.name=? )

With that example I believe your code should look something like

Criteria crit = session.createCriteria(MyClass.class, "mine");
crit.createAlias("mine.names", "name", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("name", Boolean.FALSE));
crit.createAlias("q.id", "id", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("id", someId));


问:
JPA AttributeConverter comparison?
I'm looking for an easy way to query a database column of type string in format YYYYMMDD. This could be done with a native query like:

```<code>select * from TPRODUCT where to_date(ENDOFPRODUCTION, 'YYYYMMDD') > CURRENT_DATE;
</code>```

But is there a way to achieve this comparison with an AttributeConverter

```<code>@NamedQuery(name = "product.filterByEOP", query =
    "select p from Product p where p.eop > :currentDate")
</code>```

答:
Well, it turns out you can. In case anyone else is looking into this, after checking the reference I ended up with:

```<code>public class DateConverter implements AttributeConverter<Date, String> {

    private final String DATE_FORMAT = "YYYYMMDD";

    @Override
    public String convertToDatabaseColumn(Date date) {
        return new SimpleDateFormat(DATE_FORMAT).format(date);
    }

    @Override
    public Date convertToEntityAttribute(String dateString) {
        Date converted = null;
        try {
            converted = new SimpleDateFormat(DATE_FORMAT).parse(dateString);
        } catch (ParseException ex) {
        }
        return converted;
    }
}
</code>```

which you can then use on an entity attribute:

```<code>@Column(name = "ENDOFPRODUCTION")
@Convert(converter = DateConverter.class)
private Date eop;
</code>```

and use the query:

```<code>final TypedQuery<Product> query = this.entityManager.createNamedQuery("product.filterByEOP", Product.class);
query.setParameter("currentDate", new Date());
List<Product> models = query.getResultList();
</code>```

Title: JPA AttributeConverter comparison?

Body:
I'm looking for an easy way to query a database column of type string in format YYYYMMDD. This could be done with a native query like:

select * from TPRODUCT where to_date(ENDOFPRODUCTION, 'YYYYMMDD') > CURRENT_DATE;

But is there a way to achieve this comparison with an AttributeConverter

@NamedQuery(name = "product.filterByEOP", query =
    "select p from Product p where p.eop > :currentDate")

Body:
Well, it turns out you can. In case anyone else is looking into this, after checking the reference I ended up with:

public class DateConverter implements AttributeConverter<Date, String> {

    private final String DATE_FORMAT = "YYYYMMDD";

    @Override
    public String convertToDatabaseColumn(Date date) {
        return new SimpleDateFormat(DATE_FORMAT).format(date);
    }

    @Override
    public Date convertToEntityAttribute(String dateString) {
        Date converted = null;
        try {
            converted = new SimpleDateFormat(DATE_FORMAT).parse(dateString);
        } catch (ParseException ex) {
        }
        return converted;
    }
}

which you can then use on an entity attribute:

@Column(name = "ENDOFPRODUCTION")
@Convert(converter = DateConverter.class)
private Date eop;

and use the query:

final TypedQuery<Product> query = this.entityManager.createNamedQuery("product.filterByEOP", Product.class);
query.setParameter("currentDate", new Date());
List<Product> models = query.getResultList();


问:
Select Columns with Multiple Ranges from Excel using OleDb

My current requirement is I need to select multiple ranges from an excel sheet(DUMMY.xls) in a single query and put it into a DataTable(fooData1) :
As you can see from the image above I have columns from A to F.
Therefore I am filtering out the columns from A to B and from D to F into a single dataTable(fooData1).
The content of the resulting datatable should be like:

```<code>NAME    ID     Date     Hobby     COLOR
DEEPAK  1               Coding    Black
ASTHA   2               Singing   Red
GAURAV  3               Dancing   Blue
BHAVESH 4     6/29/2007 Painting  Green
</code>```

My Code goes like this:

and while executing the Query the following error fires up

"Characters found after end of SQL statement."

```<code>     DataTable fooData1 = new DataTable();
                       System.Data.OleDb.OleDbConnection dbConnection =
              new System.Data.OleDb.OleDbConnection
                (@"Provider=Microsoft.Jet.OLEDB.4.0;"
                 + @"Data Source=C:\Dummy.xls;"
                 + @"Extended Properties=""Excel 8.0;HDR=Yes;""");
            dbConnection.Open();
            try
            {
                string strSql = "SELECT * FROM [Sheet1$A:B] ; select * from[Sheet1$D:F]";
                OleDbCommand cmd = new OleDbCommand(strSql);
                cmd.Connection = dbConnection;
                System.Data.OleDb.OleDbDataAdapter dbAdapter1 = new System.Data.OleDb.OleDbDataAdapter(cmd);
                dbAdapter1.Fill(fooData1);
                          }
            finally
            {
                dbConnection.Close();
            }
</code>```

答:
Hey as for your question, you select individual columns by using the F and the column number. For example, "SELECT * FROM [Sheet1$A:B] ; select * from[Sheet1$D:F]"; could be re-write as:</p>

```<code>"SELECT F1,F2,F4,F5 FROM [Sheet1$];"
</code>```

Body:
My current requirement is I need to select multiple ranges from an excel sheet(DUMMY.xls) in a single query and put it into a DataTable(fooData1) :
As you can see from the image above I have columns from A to F.
Therefore I am filtering out the columns from A to B and from D to F into a single dataTable(fooData1).
The content of the resulting datatable should be like:

NAME    ID     Date     Hobby     COLOR
DEEPAK  1               Coding    Black
ASTHA   2               Singing   Red
GAURAV  3               Dancing   Blue
BHAVESH 4     6/29/2007 Painting  Green

My Code goes like this:

and while executing the Query the following error fires up

"Characters found after end of SQL statement."

     DataTable fooData1 = new DataTable();
                       System.Data.OleDb.OleDbConnection dbConnection =
              new System.Data.OleDb.OleDbConnection
                (@"Provider=Microsoft.Jet.OLEDB.4.0;"
                 + @"Data Source=C:\Dummy.xls;"
                 + @"Extended Properties=""Excel 8.0;HDR=Yes;""");
            dbConnection.Open();
            try
            {
                string strSql = "SELECT * FROM [Sheet1$A:B] ; select * from[Sheet1$D:F]";
                OleDbCommand cmd = new OleDbCommand(strSql);
                cmd.Connection = dbConnection;
                System.Data.OleDb.OleDbDataAdapter dbAdapter1 = new System.Data.OleDb.OleDbDataAdapter(cmd);
                dbAdapter1.Fill(fooData1);
                          }
            finally
            {
                dbConnection.Close();
            }

Body:
Hey as for your question, you select individual columns by using the F and the column number. For example, "SELECT * FROM [Sheet1$A:B] ; select * from[Sheet1$D:F]"; could be re-write as:

"SELECT F1,F2,F4,F5 FROM [Sheet1$];"


问:
FHIR Questionnaire - questions order
In my application I want to use FHIR Questionnaire resource.
On the server side I am trying to generate questionnaire with different types of questions and send it to the application where user (patient) can fill in answers and send them back.
However in some cases I would like from user to answer only specific questions of the questionnaire and not all of them. For example if questionnaire consists of two questions:

Do you smoke or drink alcohol?

Measure your heart rate.

I would like that user answers second question only if he has answered on the first question with 'yes'. The second question is skipped if he has answered 'no'.

The problem is that I do not know how to add these rules, which will tell which question is next, inside the Questionnaire resource.
I came along to some extensions like ordinalValue, but I couldn't find out how/where to use them and where to define if user's answer must be equal / less / greater than some value.

So I would like to know which extension i need to use (and how) to achieve what I've written before? Is this even possible with existing extensions or I would have to define a new one?

I am adding simple representation (with only relevant data) of mentioned questionnaire in the JSON form:

```<code>{
  "resourceType": "Questionnaire",
  ...
  "item": [
    {
      "linkId": "1",
      "text": "Do you smoke or drink alcohol?",
      "type": "boolean"
      << ??? extension ???>>
    },
    {
      "linkId": "2",
      "text": "Measure your heart rate.",
      "type": "integer"
    }]
}
</code>```

答:
You could use the Questionnaire.item.enableWhen element for this:</p>

```<code>{
    "linkId": "2",
    "text": "Measure your heart rate.",
    "type": "integer"
    "enableWhen": [{
            "question": "1",
            "answerBoolean": "true",
        }
    ],
}
</code>```

Title: FHIR Questionnaire - questions order

Body:
In my application I want to use FHIR Questionnaire resource.
On the server side I am trying to generate questionnaire with different types of questions and send it to the application where user (patient) can fill in answers and send them back.
However in some cases I would like from user to answer only specific questions of the questionnaire and not all of them. For example if questionnaire consists of two questions:

Do you smoke or drink alcohol?

Measure your heart rate.

I would like that user answers second question only if he has answered on the first question with 'yes'. The second question is skipped if he has answered 'no'.

The problem is that I do not know how to add these rules, which will tell which question is next, inside the Questionnaire resource.
I came along to some extensions like ordinalValue, but I couldn't find out how/where to use them and where to define if user's answer must be equal / less / greater than some value.

So I would like to know which extension i need to use (and how) to achieve what I've written before? Is this even possible with existing extensions or I would have to define a new one?

I am adding simple representation (with only relevant data) of mentioned questionnaire in the JSON form:

{
  "resourceType": "Questionnaire",
  ...
  "item": [
    {
      "linkId": "1",
      "text": "Do you smoke or drink alcohol?",
      "type": "boolean"
      << ??? extension ???>>
    },
    {
      "linkId": "2",
      "text": "Measure your heart rate.",
      "type": "integer"
    }]
}

Body:
You could use the Questionnaire.item.enableWhen element for this:

{
    "linkId": "2",
    "text": "Measure your heart rate.",
    "type": "integer"
    "enableWhen": [{
            "question": "1",
            "answerBoolean": "true",
        }
    ],
}


问:
awk match command and memory usage
I realised that my awk script was using more and more memory as time goes, when I wasn't supposed to store anything in memory so I decided to do some tests.

This is a very simple script (mine is bigger, but I reproduce the problem on a very basic one). My awk script is used inside a bash script, the $file variable is the file on which the awk runs.

```<code>awk '
{
    if(match($0,"word"))
    {
        line=substr($0, RSTART - 20, RLENGTH + 20)
        print line
    }
}
' "$file"
</code>```

If I execute this script on a big file, in which each line contains word, the memory usage of the awk script is raising super fast, even faster if I print to a file. I have to stop it before it freezes my computer. Do you have an idea what is causing this big memory usage ?
In my real script, the files are usually smaller and the match function is not triggered every line like in this function, but I would prefer to be sure nothing wrong  will happen.

EDIT : This problem doesn't seem to appear while using mawk, only with GNU awk, I have no idea why.

答:
The problem doesn't seem to appear while using mawk, only with GNU awk.

I solve the problem by using LC_ALL=C before the awk script, like this :

```<code>LC_ALL=C awk '
{
    if(match($0,"word"))
    {
        line=substr($0, RSTART - 20, RLENGTH + 20)
        print line
    }
}
' "$file"
</code>```

EDIT : The problem doesn't appear on GNU awk 4.1.4. This seems to happen only on older version (mine was 3.1.3)

Title: awk match command and memory usage

Body:
I realised that my awk script was using more and more memory as time goes, when I wasn't supposed to store anything in memory so I decided to do some tests.

This is a very simple script (mine is bigger, but I reproduce the problem on a very basic one). My awk script is used inside a bash script, the $file variable is the file on which the awk runs.

awk '
{
    if(match($0,"word"))
    {
        line=substr($0, RSTART - 20, RLENGTH + 20)
        print line
    }
}
' "$file"

If I execute this script on a big file, in which each line contains word, the memory usage of the awk script is raising super fast, even faster if I print to a file. I have to stop it before it freezes my computer. Do you have an idea what is causing this big memory usage ?
In my real script, the files are usually smaller and the match function is not triggered every line like in this function, but I would prefer to be sure nothing wrong  will happen.

EDIT : This problem doesn't seem to appear while using mawk, only with GNU awk, I have no idea why.

Body:
The problem doesn't seem to appear while using mawk, only with GNU awk.

I solve the problem by using LC_ALL=C before the awk script, like this :

LC_ALL=C awk '
{
    if(match($0,"word"))
    {
        line=substr($0, RSTART - 20, RLENGTH + 20)
        print line
    }
}
' "$file"

EDIT : The problem doesn't appear on GNU awk 4.1.4. This seems to happen only on older version (mine was 3.1.3)