问:
Microsoft SQL Server Create a session specific synonym
I am working on a database that hold specific session data in separate tables for each session. e.g. I'd have a table called ProductsABCD, which holds products visible to that session, where ABCD is the session Id.  Not graceful, but what I've got to work with. Currently I would access this data in the format:

```<code>DECLARE @Session AS VARCHAR(MAX) = 'ABCD'
DECLARE @strSQL AS VARCHAR(MAX)

SET @strSQL = 'SELECT * FROM Products' + @Session
EXEC (@strSQL)
</code>```

A very simplified version, but anyone who has ever used Dynamic SQL will tell you how quickly this becomes very ugly. I am currently looking into the option of using Synonyms.  I can set these up in Dynamic SQL and then Access the synonym without dynamic. e.g.

```<code>DECLARE @Session AS VARCHAR(MAX) = 'ABCD'
DECLARE @strSQL AS VARCHAR(MAX)

SET @strSQL = 'CREATE SYNONYM myProducts FOR Products' + @Session
EXEC (@strSQL)

SELECT  *
FROM    myProducts

DROP SYNONYM myProducts
</code>```

While this works when only a single user is testing, its not a viable option when multiple users are online as the synonym is globally accessible. Does anyone know of a way to create a synonym that is only accessible to a single session at a time? Similar to how a temp table can only be accessed by a single session.

Many thanks.

Additional info:

The circumstances here are that there is some business logic at play here that defines what products are visible, what prices are displayed, what stock levels are accessible etc. Each of these is stored in global tables created upon session start up, and then cleaned up either at session dispose or on a timer.

These cannot be stored in temp tables, because the lifetime expires when the setup stored proc finishes. Cannot be held in a single table with a session parameter as a field because of the high number of sessions/qty of data that is available in the system. This was developed before partitioning was really an option. Would also require major reworking of stored procedures - please remember this is an inherited existing system.

A db session here is an IIS session that opens a single connection to the database and holds that session open.  This is then cleared down by a dispose session sent on log out, or via a timer that clears any old sessions that were not disposed of properly.

I would be looking for a synonym that is unique either for the period of the connection, or only during the specific call to a stored procedure.  Either would work, provided the synonym is not available to another session or stored procedure.

答: Possible way to circumvent this quest is to create per-session user, put all tables in per-session schema, make this schema default to this user, run everything with execute as <session-user> and without specifying schemas before tables. Could do the thing - to keep tables with same name (but in different schemas). But you better have hothing in dbo schema in this case. And maybe try to rethink whole solution someday.

Body:
I am working on a database that hold specific session data in separate tables for each session. e.g. I'd have a table called ProductsABCD, which holds products visible to that session, where ABCD is the session Id.  Not graceful, but what I've got to work with. Currently I would access this data in the format:

DECLARE @Session AS VARCHAR(MAX) = 'ABCD'
DECLARE @strSQL AS VARCHAR(MAX)

SET @strSQL = 'SELECT * FROM Products' + @Session
EXEC (@strSQL)

A very simplified version, but anyone who has ever used Dynamic SQL will tell you how quickly this becomes very ugly. I am currently looking into the option of using Synonyms.  I can set these up in Dynamic SQL and then Access the synonym without dynamic. e.g.

DECLARE @Session AS VARCHAR(MAX) = 'ABCD'
DECLARE @strSQL AS VARCHAR(MAX)

SET @strSQL = 'CREATE SYNONYM myProducts FOR Products' + @Session
EXEC (@strSQL)

SELECT  *
FROM    myProducts

DROP SYNONYM myProducts

While this works when only a single user is testing, its not a viable option when multiple users are online as the synonym is globally accessible. Does anyone know of a way to create a synonym that is only accessible to a single session at a time? Similar to how a temp table can only be accessed by a single session.

Many thanks.

Additional info:

The circumstances here are that there is some business logic at play here that defines what products are visible, what prices are displayed, what stock levels are accessible etc. Each of these is stored in global tables created upon session start up, and then cleaned up either at session dispose or on a timer.

These cannot be stored in temp tables, because the lifetime expires when the setup stored proc finishes. Cannot be held in a single table with a session parameter as a field because of the high number of sessions/qty of data that is available in the system. This was developed before partitioning was really an option. Would also require major reworking of stored procedures - please remember this is an inherited existing system.

A db session here is an IIS session that opens a single connection to the database and holds that session open.  This is then cleared down by a dispose session sent on log out, or via a timer that clears any old sessions that were not disposed of properly.

I would be looking for a synonym that is unique either for the period of the connection, or only during the specific call to a stored procedure.  Either would work, provided the synonym is not available to another session or stored procedure.


来源: stackexchange

问:
How to subscribe to a specific child route parameter?
I have these two route definitions, product list and product detail:

```<code>const routes: Routes = [
    ...
    {
        path: 'product',
        component: ProductListComponent,
        resolve: {
            products: ProductListResolverService
        },
        children: [
            {
                path: ':productcode',
                component: ProductDetailComponent,
                resolve: {
                    product: ProductDetailResolverService
                }
            },
            ...
        ]
    }
    ...
</code>```

Inside the product list component I have a set of radio buttons to indicate which product is selected, while the router outlet displays the product detail component:

```<code><div *ngFor="let product of Products" class="radio">
    <label>
        <input [(ngModel)]="SelectedProduct"
            [value]="product"
            (change)="RefreshDetail()"
            name="selectedProduct"
            type="radio">
            {{product.Name}} {{product.Code}}
    </label>
</div>
<router-outlet></router-outlet>
</code>```

When the user clicks the radio button, the URL, the product detail component, and the radio button are synchronized correctly.

But when the user goes directly to a certain product URL, the URL and product detail component display the correct product, but the radio button doesn't. What I mean by going directly to a certain product URL is the user inputs the URL to the browser address bar and press enter.

I tried to get the value of :productcode from ActivatedRoute but it didn't work:

```<code>this.route.paramMap.subscribe(params => {
  let productcode = params.get("productcode");

  let product = this.Products.find(product => product.Code == productcode);

  if (!!product) {
    this.SelectedProduct = product;
  }
});
</code>```

The paramMap.get("productcode") is always null. Probably because it is not available in the product list route, but in the child route, the product detail route.

I haven't found a way to subscribe to product detail route from product list component. Besides product detail route is not the only child of product list route.

How do I subscribe to a specific child route parameter?

答:
try like this :</p>

```<code>this.route.params.subscribe((params) => {

    let productcode = params['productcode'];

    let product = this.Products.find(product => product.Code == productcode);

    if (!!product) {
       this.SelectedProduct = product;
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have these two route definitions, product list and product detail:

const routes: Routes = [
    ...
    {
        path: 'product',
        component: ProductListComponent,
        resolve: {
            products: ProductListResolverService
        },
        children: [
            {
                path: ':productcode',
                component: ProductDetailComponent,
                resolve: {
                    product: ProductDetailResolverService
                }
            },
            ...
        ]
    }
    ...

Inside the product list component I have a set of radio buttons to indicate which product is selected, while the router outlet displays the product detail component:

        <input [(ngModel)]="SelectedProduct"
            [value]="product"
            (change)="RefreshDetail()"
            name="selectedProduct"
            type="radio">
            {{product.Name}} {{product.Code}}

<router-outlet></router-outlet>

When the user clicks the radio button, the URL, the product detail component, and the radio button are synchronized correctly.

But when the user goes directly to a certain product URL, the URL and product detail component display the correct product, but the radio button doesn't. What I mean by going directly to a certain product URL is the user inputs the URL to the browser address bar and press enter.

I tried to get the value of :productcode from ActivatedRoute but it didn't work:

this.route.paramMap.subscribe(params => {
  let productcode = params.get("productcode");

  let product = this.Products.find(product => product.Code == productcode);

  if (!!product) {
    this.SelectedProduct = product;
  }
});

The paramMap.get("productcode") is always null. Probably because it is not available in the product list route, but in the child route, the product detail route.

I haven't found a way to subscribe to product detail route from product list component. Besides product detail route is not the only child of product list route.

How do I subscribe to a specific child route parameter?

Body:
try like this :

this.route.params.subscribe((params) => {

    let productcode = params['productcode'];

    let product = this.Products.find(product => product.Code == productcode);

    if (!!product) {
       this.SelectedProduct = product;
    }
});


问:
Very high cost for low limit LIMIT / high OFFSET
I'm having very large table with products. I need to select several products at very high offset (example below). Postgresql manual on indexes and performance suggests to create index on column that's used by ORDER BY + eventual conditions. Everything is peachy, no sort is used. but for high offset values LIMIT is very costly. Anyone have any idea what might be a cause for that?

Following query can run for minutes.

```<code>Indexes:
"product_slugs_pkey" PRIMARY KEY, btree (id)
"index_for_listing_by_default_active" btree (priority DESC, name, active)
"index_for_listing_by_name_active" btree (name, active)
"index_for_listing_by_price_active" btree (master_price, active)
"product_slugs_product_id" btree (product_id)

EXPLAIN SELECT * FROM "product_slugs" WHERE ("product_slugs"."active" = 1) ORDER BY product_slugs.name ASC LIMIT 10 OFFSET 14859;
                                                       QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=26571.55..26589.43 rows=10 width=1433)
   ->  Index Scan using index_for_listing_by_name_active on product_slugs  (cost=0.00..290770.61 rows=162601 width=1433)
         Index Cond: (active = 1)
(3 rows)
</code>```

答:
The index_for_listing_by_name_active index you have here isn't going to help much, since the products in the result set aren't necessarily going to be contiguous in the index. Try creating a conditional index by name on only those products which are active:

```<code>CREATE INDEX index_for_listing_active_by_name
  ON product_slugs (name)
  WHERE product_slugs.active = 1;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm having very large table with products. I need to select several products at very high offset (example below). Postgresql manual on indexes and performance suggests to create index on column that's used by ORDER BY + eventual conditions. Everything is peachy, no sort is used. but for high offset values LIMIT is very costly. Anyone have any idea what might be a cause for that?

Following query can run for minutes.

Indexes:
"product_slugs_pkey" PRIMARY KEY, btree (id)
"index_for_listing_by_default_active" btree (priority DESC, name, active)
"index_for_listing_by_name_active" btree (name, active)
"index_for_listing_by_price_active" btree (master_price, active)
"product_slugs_product_id" btree (product_id)

EXPLAIN SELECT * FROM "product_slugs" WHERE ("product_slugs"."active" = 1) ORDER BY product_slugs.name ASC LIMIT 10 OFFSET 14859;
                                                       QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=26571.55..26589.43 rows=10 width=1433)
   ->  Index Scan using index_for_listing_by_name_active on product_slugs  (cost=0.00..290770.61 rows=162601 width=1433)
         Index Cond: (active = 1)
(3 rows)

Body:
The index_for_listing_by_name_active index you have here isn't going to help much, since the products in the result set aren't necessarily going to be contiguous in the index. Try creating a conditional index by name on only those products which are active:

CREATE INDEX index_for_listing_active_by_name
  ON product_slugs (name)
  WHERE product_slugs.active = 1;


问:
IBM BPM same flowObjectId / guid
What could be the reason for getting the same guid from tw.system.step.guid.
Whenever I initiate the step/task I am getting the same guid?</p>

答:
So the question is: I have a loop in the diagram [...] I want to determine the "BPM taskId" from the tw.system.step.id

I assume here you are referring to multi-instance-loop (MIL) instead of looped flow on process diagram. This is because using tw.system.step namespace is used in most cases in context of its tw.system.step.counter used to distribute data to instance of specific number based on that counter.

JavaScript server-side API does not provide utility to do this while REST API does. REST approach may be feasible unless you want stick to JS API only. Otherwise you may need to redesign your approach. Without real goal you want to achieve I cannot suggest any other approach.

How to do it with REST? You need to make one call to get process instance details operation under /rest/bpm/wle/v1/process/{pid}?parts=executionTree
where pid is process instance id that you are running (obtained from tw.system.currentProcessInstance.id). In REST API Tester tool you can find this operation under “Business Process Manager REST APIs / Process API / Current State”.

Data returned is a tree that you need to travers. Starting from data.executionTree.root you walk over all children and its children etc. looking for tokenId attribute that keeps value of tw.system.step.id. Matching node will have createdTaskIDs array that is either null if no tasks associated or it will keep task IDs.

For instance under
data.executionTree.root.children[0].children[1].tokenId
there is step number I am interested in, and therefore data.executionTree.root.children[0].children[1].createdTaskIDs[0]
has task ID I can use to retrieve full task.

From the same single REST call you can also get task details. Use parts=executionTree,header query param and result will hold list of tasks as well under data.tasks array, with tkiid having task ID.

Title: IBM BPM same flowObjectId / guid


问:
Array of function pointers as a member of a C struct
I have built the following C example trying to simulate simplistic generic driver code which can be used in small ARM micro-controllers:

```<code>#include <stdio.h>
#include <string.h>

typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);

typedef struct {
        generic_func_t init;
        generic_func_t open;
        generic_func_t read;
        generic_func_t write;
        generic_func_t close;
        generic_func_t exit;
} driver_t;

void USB_init(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

void USB_open(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

void USB_read(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_read 0x%x\n", x);
}

void USB_write(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_write 0x%x\n", x);
}

void USB_close(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_close 0x%x\n", x);
}

void USB_exit(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_close 0x%x\n", x);
}

typedef struct driver_t USB_driver;

#if 1
        USB_driver.init = &USB_init;
        USB_driver.open = &USB_open;
        USB_driver.read  = &USB_read;
        USB_driver.write = &USB_write;
        USB_driver.close = &USB_close;
        USB_driver.exit  = &USB_exit;
#endif

#if 1
void main(void) {}
#endif
#if 0
void main(void) {
        USB_driver.init(0x01);
        USB_driver.open(0x02);
        USB_driver.read(0x03);
        USB_driver.write(0x04);
        USB_driver.close(0x05);
        USB_driver.exit(0x06);
}
#endif
</code>```

The following error appears:

```<code>[user@localhost fn-ptr]$ emacs fn-ptr.c

(emacs:4983): Gtk-WARNING **: Allocating size to Emacs 0xdb4270 without calling gtk_widget_get_preferred_width/height(). How does the code know the size to allocate?
[user@localhost fn-ptr]$ gcc fn-ptr.c
fn-ptr.c:78:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.init = &USB_init;
           ^
fn-ptr.c:79:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.open = &USB_open;
           ^
fn-ptr.c:80:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.read  = &USB_read;
           ^
fn-ptr.c:81:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.write = &USB_write;
           ^
fn-ptr.c:82:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.close = &USB_close;
           ^
fn-ptr.c:83:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.exit  = &USB_exit;
           ^
[user@localhost fn-ptr]$
</code>```

The question here is: what should I do to make this code to work, since the following single function pointer example, upon which this code is built, works perfectly:

```<code>typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);

generic_func_t init;

void USB_init(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

init = &USB_init;
</code>```

答:
Make USB_driver a variable by just removing the typedef struct from typedef struct driver_t USB_driver; and use the code in the main to init it.

Like this:

```<code>driver_t USB_driver;

int main(void) {
    USB_driver.init = &USB_init;
    USB_driver.open = &USB_open;
    USB_driver.read  = &USB_read;
    USB_driver.write = &USB_write;
    USB_driver.close = &USB_close;
    USB_driver.exit  = &USB_exit;

    USB_driver.init(0x01);
    USB_driver.open(0x02);
    USB_driver.read(0x03);
    USB_driver.write(0x04);
    USB_driver.close(0x05);
    USB_driver.exit(0x06);

    return 0;
}
</code>```

Or better yet make new create function:

```<code>void USB_Driver_create(driver_t *driver)
{
    driver->init = &USB_init;
    driver->open = &USB_open;
    driver->read  = &USB_read;
    driver->write = &USB_write;
    driver->close = &USB_close;
    driver->exit  = &USB_exit;
}
</code>```

Body:
I have built the following C example trying to simulate simplistic generic driver code which can be used in small ARM micro-controllers:

#include <stdio.h>
#include <string.h>

typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);

typedef struct {
        generic_func_t init;
        generic_func_t open;
        generic_func_t read;
        generic_func_t write;
        generic_func_t close;
        generic_func_t exit;
} driver_t;

void USB_init(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

void USB_open(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

void USB_read(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_read 0x%x\n", x);
}

void USB_write(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_write 0x%x\n", x);
}

void USB_close(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_close 0x%x\n", x);
}

void USB_exit(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_close 0x%x\n", x);
}

typedef struct driver_t USB_driver;

#if 1
        USB_driver.init = &USB_init;
        USB_driver.open = &USB_open;
        USB_driver.read  = &USB_read;
        USB_driver.write = &USB_write;
        USB_driver.close = &USB_close;
        USB_driver.exit  = &USB_exit;
#endif

#if 1
void main(void) {}
#endif
#if 0
void main(void) {
        USB_driver.init(0x01);
        USB_driver.open(0x02);
        USB_driver.read(0x03);
        USB_driver.write(0x04);
        USB_driver.close(0x05);
        USB_driver.exit(0x06);
}
#endif

The following error appears:

[user@localhost fn-ptr]$ emacs fn-ptr.c

(emacs:4983): Gtk-WARNING **: Allocating size to Emacs 0xdb4270 without calling gtk_widget_get_preferred_width/height(). How does the code know the size to allocate?
[user@localhost fn-ptr]$ gcc fn-ptr.c
fn-ptr.c:78:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.init = &USB_init;
           ^
fn-ptr.c:79:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.open = &USB_open;
           ^
fn-ptr.c:80:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.read  = &USB_read;
           ^
fn-ptr.c:81:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.write = &USB_write;
           ^
fn-ptr.c:82:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.close = &USB_close;
           ^
fn-ptr.c:83:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.exit  = &USB_exit;
           ^
[user@localhost fn-ptr]$

The question here is: what should I do to make this code to work, since the following single function pointer example, upon which this code is built, works perfectly:

typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);

generic_func_t init;

void USB_init(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

init = &USB_init;

Body:
Make USB_driver a variable by just removing the typedef struct from typedef struct driver_t USB_driver; and use the code in the main to init it.

Like this:

driver_t USB_driver;

int main(void) {
    USB_driver.init = &USB_init;
    USB_driver.open = &USB_open;
    USB_driver.read  = &USB_read;
    USB_driver.write = &USB_write;
    USB_driver.close = &USB_close;
    USB_driver.exit  = &USB_exit;

    USB_driver.init(0x01);
    USB_driver.open(0x02);
    USB_driver.read(0x03);
    USB_driver.write(0x04);
    USB_driver.close(0x05);
    USB_driver.exit(0x06);

    return 0;
}

Or better yet make new create function:

void USB_Driver_create(driver_t *driver)
{
    driver->init = &USB_init;
    driver->open = &USB_open;
    driver->read  = &USB_read;
    driver->write = &USB_write;
    driver->close = &USB_close;
    driver->exit  = &USB_exit;
}


问:
linked list add at position
im having trouble adding nodes in between nodes in a link list....my code is as follows

```<code>public class Node {
    int data;
    int count;
    Node prev,next;
    public Node(int x){
        data=x;
        next=null;
        count=count++;
    }
}
</code>```

insert at position function

```<code>public void insertAtPos(int x ,int pos){

    if (start==null) {
        Node p=new Node(x);
        start=p;
        NodeCount=NodeCount+1;
    } else {
        int i=1;
        Node current=start;
        if (pos>0){
            if (pos>NodeCount){
                System.out.println("The position exceeds the nodes in Linked List");
            }
             while (current!=null){
                 if (i==pos-1){
                     Node p=new Node(x);
                     p.next=current.next;
                     current.next=p;
                     return ;
                 }else{
                     current=current.next;
                     i++;
                 }
                 NodeCount=NodeCount+1;

             }
        }else{

            System.out.println("The position exceeds the nodes in LL");
        }
    }
}
</code>```

Main

```<code>public static void main(String[]args){
        LinkedList s=new LinkedList();
        s.insertFront(55);
        s.insertFront(33);
        s.insertFront(75);
        s.insertFront(83);
        s.insertEnd(59);

        s.display();

        s.insertAtPos(44,2);
        System.out.println("  ");
        s.display();
    }
</code>```

The result I get replaces the Node with the one I provide...So my question is how do I modify the function to add the node in between

答:
Change this part:</p>

```<code> if (i==pos-2){//stopping in previous node where you have to insert
       Node p=new Node(x);
       p.next=current.next;
       current.next=p;
       return ;
 }
</code>```

Title: linked list add at position

Body:
im having trouble adding nodes in between nodes in a link list....my code is as follows

public class Node {
    int data;
    int count;
    Node prev,next;
    public Node(int x){
        data=x;
        next=null;
        count=count++;
    }
}

insert at position function

public void insertAtPos(int x ,int pos){

    if (start==null) {
        Node p=new Node(x);
        start=p;
        NodeCount=NodeCount+1;
    } else {
        int i=1;
        Node current=start;
        if (pos>0){
            if (pos>NodeCount){
                System.out.println("The position exceeds the nodes in Linked List");
            }
             while (current!=null){
                 if (i==pos-1){
                     Node p=new Node(x);
                     p.next=current.next;
                     current.next=p;
                     return ;
                 }else{
                     current=current.next;
                     i++;
                 }
                 NodeCount=NodeCount+1;

             }
        }else{

            System.out.println("The position exceeds the nodes in LL");
        }
    }
}

Main

public static void main(String[]args){
        LinkedList s=new LinkedList();
        s.insertFront(55);
        s.insertFront(33);
        s.insertFront(75);
        s.insertFront(83);
        s.insertEnd(59);

        s.display();

        s.insertAtPos(44,2);
        System.out.println("  ");
        s.display();
    }

The result I get replaces the Node with the one I provide...So my question is how do I modify the function to add the node in between

Body:
Change this part:

 if (i==pos-2){//stopping in previous node where you have to insert
       Node p=new Node(x);
       p.next=current.next;
       current.next=p;
       return ;
 }


问:
C# - SetupDiGetDeviceInterfaceDetail will get the strange String
Recently, I want to use C# to get the HID device. But I meet some trouble.

When I use SetupDiGetDeviceInterfaceDetail() function, I will get the wrong path.

My code of get path function as below.

```<code>private string GetDevicePath(IntPtr hDeviceInfo, ref SP_DEVICE_INTERFACE_DATA devInterfaceData)
    {
        uint nRequiredSize = 0;
        //basically, the first device detailed will return the false... it the really thing.
        if (!SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData, IntPtr.Zero, (uint)0, ref nRequiredSize, IntPtr.Zero))
        {

            ///Declare Sample 3:
            SP_DEVICE_INTERFACE_DETAIL_DATA oDevInterfaceDetailedData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            //Create Buffer to save the path detailed.
            oDevInterfaceDetailedData.cbSize = 5; //=5

            ///With Sample 3:
            if (SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData,ref oDevInterfaceDetailedData, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
            {
                //FIXME: Problem 1: The CreateFile will return 123. its means The filename, directory name, or volume label syntax is incorrect.
                //https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

                ///With Sample 3:
                Log.Text += ("Acutal Path = "+ oDevInterfaceDetailedData.DevicePath + "\n");
                return oDevInterfaceDetailedData.DevicePath;
            }
        }
        return null;
    }
</code>```

The question is here: oDevInterfaceDetailedData.DevicePath

The string variable will shows the message as below.

```<code>Acutal Path = 屜尿楨⍤楶彤㌰て瀦摩ㅟ㐰⌱☶㐱㡡㈶搷〦〦〰⌰㑻㕥戵ⴲㅦ昶ㄭ挱ⵦ㠸扣〭㄰ㄱ〱〰㌰細
</code>```

My declare of function/structure as below

```<code>    [DllImport("setupapi.dll", SetLastError = true)]
    protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);

    [DllImport("setupapi.dll", SetLastError = true)]
    protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    public struct SP_DEVICE_INTERFACE_DETAIL_DATA
    {
        public uint cbSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DevicePath;
    }
</code>```

My platform is 64 bits Windows OS.
I use the VS2017 IDE to build a WPF project in C#.

Does someone could help me to figure out the question is..... Thanks a lot

答:
Thanks Hans Passant.

I finally modify the SP_DEVICE_INTERFACE_DETAIL_DATA structure.

```<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct SP_DEVICE_INTERFACE_DETAIL_DATA
    {
        public uint cbSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DevicePath;
    }
</code>```

The CharSet need to use ansi instead of auto...

Body:
Recently, I want to use C# to get the HID device. But I meet some trouble.

When I use SetupDiGetDeviceInterfaceDetail() function, I will get the wrong path.

My code of get path function as below.

private string GetDevicePath(IntPtr hDeviceInfo, ref SP_DEVICE_INTERFACE_DATA devInterfaceData)
    {
        uint nRequiredSize = 0;
        //basically, the first device detailed will return the false... it the really thing.
        if (!SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData, IntPtr.Zero, (uint)0, ref nRequiredSize, IntPtr.Zero))
        {

            ///Declare Sample 3:
            SP_DEVICE_INTERFACE_DETAIL_DATA oDevInterfaceDetailedData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            //Create Buffer to save the path detailed.
            oDevInterfaceDetailedData.cbSize = 5; //=5

            ///With Sample 3:
            if (SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData,ref oDevInterfaceDetailedData, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
            {
                //FIXME: Problem 1: The CreateFile will return 123. its means The filename, directory name, or volume label syntax is incorrect.
                //https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

                ///With Sample 3:
                Log.Text += ("Acutal Path = "+ oDevInterfaceDetailedData.DevicePath + "\n");
                return oDevInterfaceDetailedData.DevicePath;
            }
        }
        return null;
    }

The question is here: oDevInterfaceDetailedData.DevicePath

The string variable will shows the message as below.

Acutal Path = 屜尿楨⍤楶彤㌰て瀦摩ㅟ㐰⌱☶㐱㡡㈶搷〦〦〰⌰㑻㕥戵ⴲㅦ昶ㄭ挱ⵦ㠸扣〭㄰ㄱ〱〰㌰細

My declare of function/structure as below

    [DllImport("setupapi.dll", SetLastError = true)]
    protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);

    [DllImport("setupapi.dll", SetLastError = true)]
    protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

    public struct SP_DEVICE_INTERFACE_DETAIL_DATA
    {
        public uint cbSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DevicePath;
    }

My platform is 64 bits Windows OS.
I use the VS2017 IDE to build a WPF project in C#.

Does someone could help me to figure out the question is..... Thanks a lot

Body:
Thanks Hans Passant.

I finally modify the SP_DEVICE_INTERFACE_DETAIL_DATA structure.

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct SP_DEVICE_INTERFACE_DETAIL_DATA
    {
        public uint cbSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DevicePath;
    }

The CharSet need to use ansi instead of auto...


问:
My modal content does't show until i inspect the browser
Modal without inspecting

Modal After inspect the browser window

答:
Its working fine in codepen link: https://codepen.io/kalaiselvan/pen/POKyKw

 $('#exampleModal').on('show.bs.modal', function(e) {
      $(window).resize();
      $(window).resize();
    });
    $('#lightSlider').lightSlider({
      gallery: true,
      item: 1,
      loop: true,
      slideMargin: 0,
      thumbItem: 9
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .demo {
      width: 450px;
    }

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

    li {
      display: block;
      float: left;
      margin-right: 6px;
      cursor: pointer;
    }

    img {
      display: block;
      height: auto;
      max-width: 100%;
    }</code>```

 <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/lightslider/1.1.3/css/lightslider.min.css" rel="stylesheet" />

    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
      Launch demo modal
    </button>

Modal title

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
            </button>

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>

```

Body:
Its working fine in codepen link: https://codepen.io/kalaiselvan/pen/POKyKw

 $('#exampleModal').on('show.bs.modal', function(e) {
      $(window).resize();
      $(window).resize();
    });
    $('#lightSlider').lightSlider({
      gallery: true,
      item: 1,
      loop: true,
      slideMargin: 0,
      thumbItem: 9
    });

 .demo {
      width: 450px;
    }

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

    li {
      display: block;
      float: left;
      margin-right: 6px;
      cursor: pointer;
    }

    img {
      display: block;
      height: auto;
      max-width: 100%;
    }

 <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/lightslider/1.1.3/css/lightslider.min.css" rel="stylesheet" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lightslider/1.1.3/js/lightslider.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
      Launch demo modal
    </button>

    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="col-md-12">
              <div class="demo">
                <ul id="lightSlider">
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-1.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-1.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-2.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-2.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-3.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-3.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-4.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-4.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-5.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-5.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-6.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-6.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-7.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-7.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-8.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-8.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-9.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-9.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-10.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-10.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-11.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-12.jpg" />
                  </li>
                  <li data-thumb="https://sachinchoolur.github.io/lightslider/img/thumb/cS-13.jpg">
                    <img src="https://sachinchoolur.github.io/lightslider/img/cS-13.jpg" />
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>


问:
Conversion failed in procedure
I am getting the error while executing  below code
   The dates are coming like below

```<code>   Where (EndDate >= '13 Nov 2017 0:0:00PM' and
   EndDate < Convert(DateTime, '13 Nov 2017 0:0:00PM')+1)
</code>```

The above is coming as a param value in the procedure
   Basically need to convert '13 Nov 2017 0:0:00PM' to datetime
   in the query.This is a enter code herefilter condition in SP

```<code>@Filter=N'(EndDate >= ''13 Nov 2017 0:0:00PM'' and  EndDate <
   Convert(DateTime, ''13 Nov 2017 0:0:00PM'')+1)
</code>```

Is the dates coming wrong in SP or can I change it to datetime inside
   SP body.

答:
Try the following Answer:</p>

```<code>@Filter=N'(EndDate >= CAST(LEFT(''13 Nov 2017 00:00:00PM'',11) AS DATETIME) and  EndDate <
   CAST(LEFT(''13 Nov 2017 00:00:00PM'',11) AS DATETIME)+1)'
</code>```

Title: Conversion failed in procedure

Body:
I am getting the error while executing  below code
   The dates are coming like below

   Where (EndDate >= '13 Nov 2017 0:0:00PM' and
   EndDate < Convert(DateTime, '13 Nov 2017 0:0:00PM')+1)

The above is coming as a param value in the procedure
   Basically need to convert '13 Nov 2017 0:0:00PM' to datetime
   in the query.This is a enter code herefilter condition in SP

@Filter=N'(EndDate >= ''13 Nov 2017 0:0:00PM'' and  EndDate <
   Convert(DateTime, ''13 Nov 2017 0:0:00PM'')+1)

Is the dates coming wrong in SP or can I change it to datetime inside
   SP body.

Body:
Try the following Answer:

@Filter=N'(EndDate >= CAST(LEFT(''13 Nov 2017 00:00:00PM'',11) AS DATETIME) and  EndDate <
   CAST(LEFT(''13 Nov 2017 00:00:00PM'',11) AS DATETIME)+1)'


问:
How can I cluster/group the output of a supervised classifier?
This is a model of my problem:

I start with a list of datapoints

```<code>X = ['Apple','Peach','Orange','Dog','Elephant','Fox','Cat','Mango']
</code>```

Then I have the output of a supervised classifier which leads me to classes such as:

```<code>Y = clf.predict(X) # 'FRUIT','FRUIT','FRUIT','ANIMAL','0','ANIMAL','ANIMAL','FRUIT'
</code>```

Even in a perfect world where my classifier has no FN I'd like to be able to group my classes into higher order classes

```<code>Z = cluster(Y)  # 'LIST_OF_FRUITS','LIST_OF_ANIMALS','LIST_OF_FRUITS'
</code>```

I'm struggling to find something which can do something like this, with or without labeled examples because without defining how large the group I cant see how this could be done.

Also an extension of this which is what I'm actually trying to solve is what if the desired groupings are containing of a few classes of different types not just a concurrent list of "FRUIT" but say a "DINNER" which often will be 0+ "MEATS", 0+ "VEG" etc the ideal solution would be one that knows the atypical dinner and could deduce/correct false negatives and find a dinner grouping from the classified data i.e:

```<code>Y = ['MEAT','0','0','0','0','MEAT','0','VEG','MEAT'] -> ['DINNER'] (1 instance)
</code>```

Some bag of words encoding of the problem should work but I don't get how to partition the output of classifier 1 such that partitions aren't forced to be a certain size

Is there something that I could use for this?

答:
I don't see clustering here.

If I understand right, you want to partition

```<code>[Fruit, Meat, Fruit]
</code>```

Into two sets

```<code>[Fruit, Fruit] and [Meat]
</code>```

At which point you will probably use the cardinality? Then just use a dictionary for counting. I.e. aggregate this into

```<code>{ Fruit: 2, Meat: 1 }
</code>```

Also, a lot of languages have some syntax to iterate over unique values, and subset operators, so that you can write

```<code>for x in unique(classification):
  subsets[x] = inputdata[classification == x]
</code>```

Either way, don't look into clustering for this. There is no advanced statistical analysis happening here. It's just counting and selecting?

Body:
This is a model of my problem:

I start with a list of datapoints

X = ['Apple','Peach','Orange','Dog','Elephant','Fox','Cat','Mango']

Then I have the output of a supervised classifier which leads me to classes such as:

Y = clf.predict(X) # 'FRUIT','FRUIT','FRUIT','ANIMAL','0','ANIMAL','ANIMAL','FRUIT'

Even in a perfect world where my classifier has no FN I'd like to be able to group my classes into higher order classes

Z = cluster(Y)  # 'LIST_OF_FRUITS','LIST_OF_ANIMALS','LIST_OF_FRUITS'

I'm struggling to find something which can do something like this, with or without labeled examples because without defining how large the group I cant see how this could be done.

Also an extension of this which is what I'm actually trying to solve is what if the desired groupings are containing of a few classes of different types not just a concurrent list of "FRUIT" but say a "DINNER" which often will be 0+ "MEATS", 0+ "VEG" etc the ideal solution would be one that knows the atypical dinner and could deduce/correct false negatives and find a dinner grouping from the classified data i.e:

Y = ['MEAT','0','0','0','0','MEAT','0','VEG','MEAT'] -> ['DINNER'] (1 instance)

Some bag of words encoding of the problem should work but I don't get how to partition the output of classifier 1 such that partitions aren't forced to be a certain size

Is there something that I could use for this?

Body:
I don't see clustering here.

If I understand right, you want to partition

[Fruit, Meat, Fruit]

Into two sets

[Fruit, Fruit] and [Meat]

At which point you will probably use the cardinality? Then just use a dictionary for counting. I.e. aggregate this into

{ Fruit: 2, Meat: 1 }

Also, a lot of languages have some syntax to iterate over unique values, and subset operators, so that you can write

for x in unique(classification):
  subsets[x] = inputdata[classification == x]

Either way, don't look into clustering for this. There is no advanced statistical analysis happening here. It's just counting and selecting?


问:
How to implement LLL Lattice Reduction in NTL using c++?
I am using C++ to do a research. And I am interested to know how to use the LLL function in NTL to find the shortest vector. My code is as follow;

```<code>#include <NTL/ZZ.h>
#include <NTL/matrix.h>
#include <NTL/mat_ZZ.h>
#include <NTL/vector.h>

using namespace std;
using namespace NTL;

int main()
{
    Mat<ZZ> B;
    cin >> B;
    cout << B << "\n";
    long LLL(ZZ& det2, mat_ZZ& B, long verbose = 0);
    cout << B << "\n";
}
</code>```

However, the matrix I enter into B is not reduced. What is wrong?

答:
I realise I have forgotten to include the correct library and implementation of LLL is not correct.

This is the library that I have forgotten to include.

```<code>#include <NTL/LLL/h>
</code>```

To execute LLL algorithm, do as follow

```<code>LLL_XD(B);
</code>```

Body:
I am using C++ to do a research. And I am interested to know how to use the LLL function in NTL to find the shortest vector. My code is as follow;

#include <NTL/ZZ.h>
#include <NTL/matrix.h>
#include <NTL/mat_ZZ.h>
#include <NTL/vector.h>

using namespace std;
using namespace NTL;

int main()
{
    Mat<ZZ> B;
    cin >> B;
    cout << B << "\n";
    long LLL(ZZ& det2, mat_ZZ& B, long verbose = 0);
    cout << B << "\n";
}

However, the matrix I enter into B is not reduced. What is wrong?

Body:
I realise I have forgotten to include the correct library and implementation of LLL is not correct.

This is the library that I have forgotten to include.

#include <NTL/LLL/h>

To execute LLL algorithm, do as follow

LLL_XD(B);


问:
What is the $scenario variable in Codeception?
I am learning to use Codeception. In the Writing a Sample Scenario documentation, one mentions a $scenario variable.

Say I implement a MyAcceptanceTester class, is this some kind of parameters variable I can use to control the behavior of my Actor? Or is this a reserved variable in the Codeception paradigm? If so, how does it work?

My testing need is the following: I need to run the same sequence of actions on several domain names. It's a case where one domain name is used per language, but all code is in the same code base and is delivered by the same Apache server. Each domain may have its own PHP code, but also shares common code with other domains. Hence, Codeception testing code will be located in the unique code base.

I was thinking about passing each URL/URI to test in MyAcceptanceTester via the $scenario variable. Is this the right way to proceed? Or should I subclass MyAcceptanceTester for each domain, because $scenario is reserved?

答:
The $scenario variable on your *Cept.php file actually an variable assigned to construct the AcceptanceTester class. To inspect how it's work you may open AcceptanceTester class file in test/_support/AcceptanceTester.php. If you see AcceptanceTester class is extended from Codeception\Actor class. Follow this source to read how $scenario variable used by the Actor.

About your case.

I need to run the same sequence of actions on several domain names.

You can implement a technic called StepObject (documentation). So the test for each website will extend from StepObjet that you recently created.

Hope it helps.

ContentLicense: CC BY-SA 4.0


问:
Spring data rest status 500 for entity with relation
I have two entities with a relation one to many

```<code>public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String userName;

    private String company;

    @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name="ORDER_ID")
    private List<Item> items;
}

public class Item {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String name;

    private Long quantity;
}
</code>```

Both entities have a @RepositoryRestResrouce and when I try to post in the /orders collction a new Order with Items like:

```<code>{
  "userName":"Marco",
  "company":"MP",
  "items":[
        {"name":"CD","quantity":"10"},
        {"name":"DVD","quantity":"5"}
   ]
 }
</code>```

I have an internal server error:

```<code>org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Failed to convert from type [java.net.URI] to type [com.example.springdatarest.domain.entity.Item] for value 'name'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable.; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type [java.net.URI] to type [com.example.springdatarest.domain.entity.Item] for value 'name'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.example.springdatarest.domain.entity.Order["items"]->java.util.ArrayList[1])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:238) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readInternal(AbstractJackson2HttpMessageConverter.java:215) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:193) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.read(PersistentEntityResourceHandlerMethodArgumentResolver.java:236) ~[spring-data-rest-webmvc-2.6.8.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.read(PersistentEntityResourceHandlerMethodArgumentResolver.java:193) ~[spring-data-rest-webmvc-2.6.8.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.resolveArgument(PersistentEntityResourceHandlerMethodArgumentResolver.java:141) ~[spring-data-rest-webmvc-2.6.8.RELEASE.jar:na]
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110) [spring-boot-actuator-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) [spring-boot-actuator-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_102]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_102]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_102]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type [java.net.URI] to type [com.example.springdatarest.domain.entity.Item] for value 'name'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.example.springdatarest.domain.entity.Order["items"]->java.util.ArrayList[1])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:388) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:360) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:308) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2938) ~[jackson-databind-2.8.10.jar:2.8.10]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:235) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 68 common frames omitted
Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.net.URI] to type [com.example.springdatarest.domain.entity.Item] for value 'name'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable.
    at org.springframework.data.rest.core.UriToEntityConverter.convert(UriToEntityConverter.java:119) ~[spring-data-rest-core-2.6.8.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$UriStringDeserializer.deserialize(PersistentEntityJackson2Module.java:518) ~[spring-data-rest-webmvc-2.6.8.RELEASE.jar:na]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287) ~[jackson-databind-2.8.10.jar:2.8.10]
    ... 77 common frames omitted
Caused by: java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable.
    ... 80 common frames omitted
</code>```

I know that I can use the association resource but I would like to know how I can create an Order with Items in one single POST.

答:
Just add parameter exported=false to @RepositoryRestResrouce annotation in your Item repo. Then you can create Order with Item in one request:

```<code>{
    "userName": "Marco",
    "company": "MP",
    "items": [
        {
             "name": "CD",
             "quantity": "10"
        },
        {
             "name": "DVD",
             "quantity": "5"
        }
    ]
}
</code>```

I recommend you to add cascade = CascadeType.ALL, orphanRemoval = true to items in Order to make items fully managed by Order.

Additional info.

If you want to work with Order and Item independently you can leave all as is but first create you items:

```<code>POST http://localhost:8080/items
{
        {
             "name": "CD",
             "quantity": "10"
        },
        {
             "name": "DVD",
             "quantity": "5"
        }
}
</code>```

then create Order that contains them:

```<code>POST http://localhost:8080/orders
{
    {
        "userName": "Marco",
        "company": "MP",
        "items": [
            "http://localhost:8080/items/1",
            "http://localhost:8080/items/2"
        ]
    }
}
</code>```

You use @JoinColumn annotation with items - so I think you must implement synchronization between Order and Items in that case...

And please don't post JSON in one line ))

Body:
I have two entities with a relation one to many

public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String userName;

    private String company;

    @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name="ORDER_ID")
    private List<Item> items;
}

public class Item {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String name;

    private Long quantity;
}

Both entities have a @RepositoryRestResrouce and when I try to post in the /orders collction a new Order with Items like:

{
  "userName":"Marco",
  "company":"MP",
  "items":[
        {"name":"CD","quantity":"10"},
        {"name":"DVD","quantity":"5"}
   ]
 }

I have an internal server error:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Failed to convert from type [java.net.URI] to type [com.example.springdatarest.domain.entity.Item] for value 'name'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable.; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type [java.net.URI] to type [com.example.springdatarest.domain.entity.Item] for value 'name'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.example.springdatarest.domain.entity.Order["items"]->java.util.ArrayList[1])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:238) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readInternal(AbstractJackson2HttpMessageConverter.java:215) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:193) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.read(PersistentEntityResourceHandlerMethodArgumentResolver.java:236) ~[spring-data-rest-webmvc-2.6.8.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.read(PersistentEntityResourceHandlerMethodArgumentResolver.java:193) ~[spring-data-rest-webmvc-2.6.8.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.resolveArgument(PersistentEntityResourceHandlerMethodArgumentResolver.java:141) ~[spring-data-rest-webmvc-2.6.8.RELEASE.jar:na]
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110) [spring-boot-actuator-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) [spring-boot-actuator-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_102]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_102]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_102]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type [java.net.URI] to type [com.example.springdatarest.domain.entity.Item] for value 'name'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.example.springdatarest.domain.entity.Order["items"]->java.util.ArrayList[1])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:388) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:360) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:308) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2938) ~[jackson-databind-2.8.10.jar:2.8.10]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:235) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 68 common frames omitted
Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.net.URI] to type [com.example.springdatarest.domain.entity.Item] for value 'name'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable.
    at org.springframework.data.rest.core.UriToEntityConverter.convert(UriToEntityConverter.java:119) ~[spring-data-rest-core-2.6.8.RELEASE.jar:na]
    at org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$UriStringDeserializer.deserialize(PersistentEntityJackson2Module.java:518) ~[spring-data-rest-webmvc-2.6.8.RELEASE.jar:na]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287) ~[jackson-databind-2.8.10.jar:2.8.10]
    ... 77 common frames omitted
Caused by: java.lang.IllegalArgumentException: Cannot resolve URI name. Is it local or remote? Only local URIs are resolvable.
    ... 80 common frames omitted

I know that I can use the association resource but I would like to know how I can create an Order with Items in one single POST.

Body:
Just add parameter exported=false to @RepositoryRestResrouce annotation in your Item repo. Then you can create Order with Item in one request:

{
    "userName": "Marco",
    "company": "MP",
    "items": [
        {
             "name": "CD",
             "quantity": "10"
        },
        {
             "name": "DVD",
             "quantity": "5"
        }
    ]
}

I recommend you to add cascade = CascadeType.ALL, orphanRemoval = true to items in Order to make items fully managed by Order.

Additional info.

If you want to work with Order and Item independently you can leave all as is but first create you items:

POST http://localhost:8080/items
{
        {
             "name": "CD",
             "quantity": "10"
        },
        {
             "name": "DVD",
             "quantity": "5"
        }
}

then create Order that contains them:

POST http://localhost:8080/orders
{
    {
        "userName": "Marco",
        "company": "MP",
        "items": [
            "http://localhost:8080/items/1",
            "http://localhost:8080/items/2"
        ]
    }
}

You use @JoinColumn annotation with items - so I think you must implement synchronization between Order and Items in that case...

And please don't post JSON in one line ))


问:
Programmatically add appender in logback
I am trying to add an appender dynamically in logback. Here is my code.

```<code>LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
ple.setContext(lc);
ple.start();
FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
String logFile = "new.log";
fileAppender.setFile(logFile);
fileAppender.setEncoder(ple);
fileAppender.setContext(lc);
fileAppender.start();

ch.qos.logback.classic.Logger logbackLogger =
                (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ModuleMessageHandler.class);
logbackLogger.addAppender(fileAppender);
logbackLogger.setLevel(Level.DEBUG);
logbackLogger.setAdditive(false);
</code>```

It works ok but works only for the specific logger on which the appender is added. Is there a way to get this to work for all loggers in the application? I am looking for a way to dynamically add and remove appenders.

答:
This section of your code:

```<code>LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
ple.setContext(lc);
ple.start();
FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
String logFile = "new.log";
fileAppender.setFile(logFile);
fileAppender.setEncoder(ple);
fileAppender.setContext(lc);
fileAppender.start();
</code>```

... creates and starts the file appender.

This section of your code ...

```<code>ch.qos.logback.classic.Logger logbackLogger =
                (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ModuleMessageHandler.class);
logbackLogger.addAppender(fileAppender);
logbackLogger.setLevel(Level.DEBUG);
logbackLogger.setAdditive(false);
</code>```

... associates the file appender with the logger instance for ModuleMessageHandler.

If, instead, you want the file appender to be associated with all logger instances in your application then (as @BillO'Neil) suggested you must associate the file appender with the root logger:

```<code>ch.qos.logback.classic.Logger logbackLogger =
                (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logbackLogger.addAppender(fileAppender);
</code>```

Body:
I am trying to add an appender dynamically in logback. Here is my code.

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
ple.setContext(lc);
ple.start();
FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
String logFile = "new.log";
fileAppender.setFile(logFile);
fileAppender.setEncoder(ple);
fileAppender.setContext(lc);
fileAppender.start();

ch.qos.logback.classic.Logger logbackLogger =
                (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ModuleMessageHandler.class);
logbackLogger.addAppender(fileAppender);
logbackLogger.setLevel(Level.DEBUG);
logbackLogger.setAdditive(false);

It works ok but works only for the specific logger on which the appender is added. Is there a way to get this to work for all loggers in the application? I am looking for a way to dynamically add and remove appenders.

Body:
This section of your code:

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
ple.setContext(lc);
ple.start();
FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
String logFile = "new.log";
fileAppender.setFile(logFile);
fileAppender.setEncoder(ple);
fileAppender.setContext(lc);
fileAppender.start();

... creates and starts the file appender.

This section of your code ...

ch.qos.logback.classic.Logger logbackLogger =
                (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ModuleMessageHandler.class);
logbackLogger.addAppender(fileAppender);
logbackLogger.setLevel(Level.DEBUG);
logbackLogger.setAdditive(false);

... associates the file appender with the logger instance for ModuleMessageHandler.

If, instead, you want the file appender to be associated with all logger instances in your application then (as @BillO'Neil) suggested you must associate the file appender with the root logger:

ch.qos.logback.classic.Logger logbackLogger =
                (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logbackLogger.addAppender(fileAppender);


问:
Coalesce over Rows in MSSQL 2008,
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

```<code>TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null
</code>```

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

```<code>SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active
</code>```

Here would be the results:

```<code>TransDate  Id  Active
---------------------
1/18 6pm   5   0
</code>```

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

答:
I created a temp table named #temp to test my solution, and here is what I came up with:

```<code>transdate              id  active
1/1/2011 12:00:00 AM    5   1
1/2/2011 12:00:00 AM    5   0
1/3/2011 12:00:00 AM    5   null
1/4/2011 12:00:00 AM    5   1
1/5/2011 12:00:00 AM    5   0
1/6/2011 12:00:00 AM    5   null
1/1/2011 12:00:00 AM    6   2
1/2/2011 12:00:00 AM    6   3
1/3/2011 12:00:00 AM    6   null
1/4/2011 12:00:00 AM    6   2
1/5/2011 12:00:00 AM    6   null
</code>```

This query...

```<code>select max(a.transdate) as transdate, a.id, (
  select top (1) b.active
  from #temp b
  where b.active is not null
  and b.id = a.id
  order by b.transdate desc
) as active
from #temp a
group by a.id
</code>```

Returns these results.

```<code>transdate              id  active
1/6/2011 12:00:00 AM    5   0
1/5/2011 12:00:00 AM    6   2
</code>```

Title: Coalesce over Rows in MSSQL 2008,

Body:
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active

Here would be the results:

TransDate  Id  Active
---------------------
1/18 6pm   5   0

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

Body:
I created a temp table named #temp to test my solution, and here is what I came up with:

transdate              id  active
1/1/2011 12:00:00 AM    5   1
1/2/2011 12:00:00 AM    5   0
1/3/2011 12:00:00 AM    5   null
1/4/2011 12:00:00 AM    5   1
1/5/2011 12:00:00 AM    5   0
1/6/2011 12:00:00 AM    5   null
1/1/2011 12:00:00 AM    6   2
1/2/2011 12:00:00 AM    6   3
1/3/2011 12:00:00 AM    6   null
1/4/2011 12:00:00 AM    6   2
1/5/2011 12:00:00 AM    6   null

This query...

select max(a.transdate) as transdate, a.id, (
  select top (1) b.active
  from #temp b
  where b.active is not null
  and b.id = a.id
  order by b.transdate desc
) as active
from #temp a
group by a.id

Returns these results.

transdate              id  active
1/6/2011 12:00:00 AM    5   0
1/5/2011 12:00:00 AM    6   2


问:
Xamarin.Forms Shared Project's Localization for UWP, iOS & Android
While I try to manually add Resx files in the shared project of a Xamarin.Forms app that has UWP, Android & iOS, I get an error that the resx files  aren't getting embedded.

There is a shared project sample at https://github.com/xamarin/xamarin-forms-samples/tree/master/TodoLocalized/SharedProject/ but it doesn't cover UWP.

Do we have any localization solution for a SHARED project that covers UWP, iOS & Android, that I could refer to?

Thanks and regards,

John

答: Well, I couldn't get the resx solution working for all three together (UWP, iOS & Android) for a shared project type, hence, I resorted to a .NET standard library as a shared project. It worked!


问:
Convert List<int[]> to int[,]
How to convert List<int[]> to int[,]  where all arrays in the list are int[2]?

I'm trying:

```<code>List<int[]> list = new List<int[]>();
list.Add(new int[2] { 3, 4 });
int[,] arr = list.ToArray();
</code>```

答:
You can't convert List to int[,] via LINQ.

You need to create new array [N, 2] and fill in a loop:

```<code>var arr = new int[list.Count, 2];

for (var i = 0; i < list.Count; i++)
{
    arr[i, 0] = list[i][0];
    arr[i, 1] = list[i][1];
}
</code>```

Title: Convert List<int[]> to int[,]

Body:
How to convert List<int[]> to int[,]  where all arrays in the list are int[2]?

I'm trying:

List<int[]> list = new List<int[]>();
list.Add(new int[2] { 3, 4 });
int[,] arr = list.ToArray();

Body:
You can't convert List to int[,] via LINQ.

You need to create new array [N, 2] and fill in a loop:

var arr = new int[list.Count, 2];

for (var i = 0; i < list.Count; i++)
{
    arr[i, 0] = list[i][0];
    arr[i, 1] = list[i][1];
}