问:
Can't add custom object into mongoDB Document Array
I'm trying to add a new object to my mongodb document inside an array.

I have a NodeJS project using MongoDB which has a collection called "Teste" where i'm saving some random data.

Amongst that data is an array called "ArrayTeste". Currently it is only saving multiple strings because I named my inputs the same thing, so it automatically does it for me.

But I don't want to save each element as an individual string, i need to get these informations, group them in an object and then add it to the array.

Here is my code snippet in NodeJS:

```<code>ServicosModel.prototype.Teste = function (req, res) {
console.log("Metodo Teste");
var query =
    {
        $push:
        {
            ArrayTeste:
            {
                Dado1: req.body.Dado1,
                Dado2: req.body.Dado2
            }
        }
    }

console.log(query)

this._connection.open(function (errConn, mongoClient) {
    console.log("Entrou open")
    if (errConn) {
        res.end("Deu erro" + errConn);
    }
    mongoClient.collection("teste", function (errColl, collection) {
        if (errColl) {
            res.end("Deu erro" + errColl);
        }
        console.log("Entrou collection")
        collection.update(query, function (errUpdate, result) {
            console.log("Entrou update")
            if (errUpdate) {
                res.end("Deu erro" + errUpdate);
            } else {
                res.end("Deu certo " + result);
            }
        });
    });
});

}
</code>```

And here is the mongoDB document structure:

```<code>{
"_id" : ObjectId("595bf19febbf3c14e481bc28"),
"id" : "2",
"Titulo" : "TItulo do negocio",
"ArrayTeste" : [
    "dado1",
    "dado2"
]
</code>```

}

The "id" parameter is one created by me to easy the $elemMatch used in previous tests, so I don't have to search for the _id of the document.

When I run the code and insert stuff into the inputs, I am presented with this error:

(node:8712) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): MongoError: document must be a valid
  JavaScript object

and I have absolutely no idea of what is happening. the application simply freezes. I have searched through the posts and tried some stuff with $set and $addToSet, but the same error persists.

Any help is appreciated, thanks in advance!

答:
To update a document you need two mandatory parameters:

criteria - to select documents to update

update - to modify selected documents

Here is the driver documentation: https://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html#update.

The error says that collection.update expects an object (the second parameter) and it is receiving a function (your callback function).

To get your code working:

```<code>var select = {id: '2'};  // Here we are choosing the document

collection.update(select, query, function (errUpdate, result) {
    if (errUpdate) {
        res.end("Deu erro" + errUpdate);
    } else {
        res.end("Deu certo " + result);
    }
});
</code>```

Body:
I'm trying to add a new object to my mongodb document inside an array.

I have a NodeJS project using MongoDB which has a collection called "Teste" where i'm saving some random data.

Amongst that data is an array called "ArrayTeste". Currently it is only saving multiple strings because I named my inputs the same thing, so it automatically does it for me.

But I don't want to save each element as an individual string, i need to get these informations, group them in an object and then add it to the array.

Here is my code snippet in NodeJS:

ServicosModel.prototype.Teste = function (req, res) {
console.log("Metodo Teste");
var query =
    {
        $push:
        {
            ArrayTeste:
            {
                Dado1: req.body.Dado1,
                Dado2: req.body.Dado2
            }
        }
    }

console.log(query)

this._connection.open(function (errConn, mongoClient) {
    console.log("Entrou open")
    if (errConn) {
        res.end("Deu erro" + errConn);
    }
    mongoClient.collection("teste", function (errColl, collection) {
        if (errColl) {
            res.end("Deu erro" + errColl);
        }
        console.log("Entrou collection")
        collection.update(query, function (errUpdate, result) {
            console.log("Entrou update")
            if (errUpdate) {
                res.end("Deu erro" + errUpdate);
            } else {
                res.end("Deu certo " + result);
            }
        });
    });
});

}

And here is the mongoDB document structure:

{
"_id" : ObjectId("595bf19febbf3c14e481bc28"),
"id" : "2",
"Titulo" : "TItulo do negocio",
"ArrayTeste" : [
    "dado1",
    "dado2"
]

}

The "id" parameter is one created by me to easy the $elemMatch used in previous tests, so I don't have to search for the _id of the document.

When I run the code and insert stuff into the inputs, I am presented with this error:

(node:8712) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): MongoError: document must be a valid
  JavaScript object

and I have absolutely no idea of what is happening. the application simply freezes. I have searched through the posts and tried some stuff with $set and $addToSet, but the same error persists.

Any help is appreciated, thanks in advance!

Body:
To update a document you need two mandatory parameters:

criteria - to select documents to update

update - to modify selected documents

Here is the driver documentation: https://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html#update.

The error says that collection.update expects an object (the second parameter) and it is receiving a function (your callback function).

To get your code working:

var select = {id: '2'};  // Here we are choosing the document

collection.update(select, query, function (errUpdate, result) {
    if (errUpdate) {
        res.end("Deu erro" + errUpdate);
    } else {
        res.end("Deu certo " + result);
    }
});


来源: stackexchange

答:
No, group by is the wrong approach.  Simply use a comparison to the most recent time stamp:

```<code>select h.*
from heats h
where h.race_id = 189 and
      h.last_updated = (select max(h2.last_updated)
                        from heats
                        where h2.race_id = h.race_id and h2.heat = h.heat
                       )
order by heat asc;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Grouping and filtering by newest timestamp

Body:
I have a table like this:

-------------------------------------------------
id   | race_id | heat | updated_at
-------------------------------------------------
28952   189        1    2017-06-24 19:57:44.433431
28956   189        1    2017-06-24 20:33:49.984958
28958   189        1    2017-06-24 21:43:59.538041
28953   189        2    2017-06-24 19:57:45.309102
28957   189        2    2017-06-24 20:36:41.725912
28961   189        2    2017-06-24 21:46:39.677080
28954   189        3    2017-06-24 19:57:46.142353
28959   189        3    2017-06-24 21:44:00.651232
28964   189        3    2017-06-24 23:13:24.172765
28969   189        3    2017-06-25 01:01:25.445597
28955   189        4    2017-06-24 19:57:47.056272
28962   189        4    2017-06-24 21:46:40.839643
28965   189        4    2017-06-25 01:00:44.736679
28966   189        4    2017-06-25 01:01:04.010346
28960   189        5    2017-06-24 21:44:02.443140
28963   189        5    2017-06-24 21:46:41.861473
28968   189        6    2017-06-25 01:01:06.028000
28971   189        6    2017-06-25 01:01:28.445862
28967   189        8    2017-06-25 01:01:05.198073
28970   189        8    2017-06-25 01:01:27.533253

But I am trying to group by race_id and heat with the newest time stamp for each group. I expect to see something like this:

-------------------------------------------------
id   | race_id | heat | updated_at
-------------------------------------------------
28958   189       1     2017-06-24 21:43:59.538041
28961   189       2     2017-06-24 21:46:39.677080
28969   189       3     2017-06-25 01:01:25.445597
28966   189       4     2017-06-25 01:01:04.010346
28963   189       5     2017-06-24 21:46:41.861473
28971   189       6     2017-06-25 01:01:28.445862
28970   189       8     2017-06-25 01:01:27.533253

I am trying to use

select
    id,
    race_id,
    heat,
    updated_at
from
    heats
where
    race_id = 189
group by
    race_id,
    heat
having
    updated_at = max(updated_at)
order by
    heat asc;

 but I am not getting any result back.

Body:
No, group by is the wrong approach.  Simply use a comparison to the most recent time stamp:

select h.*
from heats h
where h.race_id = 189 and
      h.last_updated = (select max(h2.last_updated)
                        from heats
                        where h2.race_id = h.race_id and h2.heat = h.heat
                       )
order by heat asc;


问:
Compare two .jpg files: checksum or byte to byte or other suggestion?
I have C# program which compare 2 .jpg files,

I was using this function I found in the internet to do that, it’s working well but it’s very slow ( takes more than a second to compare )

```<code>public static bool ImageCompareString(Bitmap firstImage, Bitmap secondImage)
{
 MemoryStream ms = new MemoryStream();
 firstImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
 String firstBitmap = Convert.ToBase64String(ms.ToArray());
 ms.Position = 0;

 secondImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
 String secondBitmap = Convert.ToBase64String(ms.ToArray());

 if (firstBitmap.Equals(secondBitmap))
 {
     return true;
 }
 else
 {
     return false;
 }
}
</code>```

Now I was wondering why not use checksum which is faster to do the compare ?

Does the results byte to byte comparison are more accurate ?

The reason I need to compare jpg file:

On my PC I have thousands of jpg files taken from my Camera and Smartphone but many of them are duplicated (Identical pictures with same name exists on different sub folders and some having the same name but are not same pictures)

I want to move all the unique pictures to a new folder and delete those that are duplicate so in case I have 2 pictures that have the same name I need to compare them.

答:
With such a prototype, the function does not compare JPEG image files but decompressed bitmaps, wherever they are coming from. Pixel-by-pixel comparison will be efficient (using LockBits, as advised by Franck). Computing and comparing checksums can be faster, as this is a branchless operation, but be sure to use a fast formula.

If your goal is to compare files, not images, avoid loading the files as bitmaps, as this involves costly decompression and increases the memory footprint. Anyway this will also detect differences in tags/file organization even if the images are the same.

Last but not least, comparing images for similarity is yet a completely different story.

Body:
I have C# program which compare 2 .jpg files,

I was using this function I found in the internet to do that, it’s working well but it’s very slow ( takes more than a second to compare )

public static bool ImageCompareString(Bitmap firstImage, Bitmap secondImage)
{
 MemoryStream ms = new MemoryStream();
 firstImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
 String firstBitmap = Convert.ToBase64String(ms.ToArray());
 ms.Position = 0;

 secondImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
 String secondBitmap = Convert.ToBase64String(ms.ToArray());

 if (firstBitmap.Equals(secondBitmap))
 {
     return true;
 }
 else
 {
     return false;
 }
}

Now I was wondering why not use checksum which is faster to do the compare ?

Does the results byte to byte comparison are more accurate ?

The reason I need to compare jpg file:

On my PC I have thousands of jpg files taken from my Camera and Smartphone but many of them are duplicated (Identical pictures with same name exists on different sub folders and some having the same name but are not same pictures)

I want to move all the unique pictures to a new folder and delete those that are duplicate so in case I have 2 pictures that have the same name I need to compare them.


问:
HTML anchor href using # hash to an id on another page when id present on first page
I'm struggling to get anchor tags with # fragments in to navigate to a new page when the id is found in the current page.

PAGE 1 on url /page1

I have HTML:

```<code><a href="/page2#bananas">go to bananas on page 2</a>
<div id="bananas">bananas on page 1</div>
</code>```

PAGE 2 on url /page2

I have HTML:

```<code><div id="bananas">bananas on page 2</div>
</code>```

When one clicks the link, the browser just scrolls to the
 with id="bananas" on page 1 and doesn't go to page 2. How can make it go to page 2 instead?

If I right click and choose open in new tab it works fine and goes to /page2#bananas as I want. Interestingly, target="_blank" doesn't work on left mouse click, and it doesn't even open a new tab in Chrome!

答:
Div ID is correct.

For the anchor add the .html extension:

```<code><a href="page2.html#bananas">go to bananas on page 2</a>
</code>```

Body:
I'm struggling to get anchor tags with # fragments in to navigate to a new page when the id is found in the current page.

PAGE 1 on url /page1

I have HTML:

go to bananas on page 2

bananas on page 1

PAGE 2 on url /page2

I have HTML:

bananas on page 2

When one clicks the link, the browser just scrolls to the
 with id="bananas" on page 1 and doesn't go to page 2. How can make it go to page 2 instead?

If I right click and choose open in new tab it works fine and goes to /page2#bananas as I want. Interestingly, target="_blank" doesn't work on left mouse click, and it doesn't even open a new tab in Chrome!

Body:
Div ID is correct.

For the anchor add the .html extension:

<a href="page2.html#bananas">go to bananas on page 2</a>


问:
how to delete or add column in grid panel
grid.getcolumnModel().setHidden(0,true) will be effected for column menu
 and not grid panel. In column menu u can enable or disable the column. How do we add or remove the column in grid panel dynamically?</p>

答:
maybe try

store.add(new_record);
store.commitChanges();

or store.remove() and store.commitChanges()

ContentLicense: CC BY-SA 2.5


问:
Chrome remote debugging port usage for chrome profiling using Webdriverio
I am currently using the Chrome profiling APIs to get the code coverage as below.

But whenever I try to run the tests, I get the following error:

Error: unexpected server response (404)
       at ClientRequest.response (/Users/svg7/projects/examples/build/js/testSuites.js:8419:16)
       at ClientRequest.g (events.js:291:16)
       at emitOne (events.js:96:13)
       at ClientRequest.emit (events.js:188:7)
       at HTTPParser.parserOnIncomingClient (_http_client.js:472:21)
       at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
       at Socket.socketOnData (_http_client.js:361:20)
       at emitOne (events.js:96:13)
       at Socket.emit (events.js:188:7)
       at readableAddChunk (_stream_readable.js:176:18)

My code is as follows:

```<code>import * as fs from "fs";
import {createSession} from "chrome-debugging-client";

describe("Functional Coverage example", function() {
this.timeout(880000);
it("Get the coverage", () => {
    createSession(async (session) => {
        const api = await session.createAPIClient("localhost", 6813);
        console.dir(api);
        const tabs = await api.listTabs();
        const tab = tabs[0];
        console.log("====>");
        console.log(tab.webSocketDebuggerUrl);
        // browser.stop();
        let client = await session.openDebuggingProtocol("http://localhost:6813");
        await client.send("Profiler.enable");
        await client.send("Page.enable");
        await client.send("Profiler.startPrecisionCoverage", {callCount: true});
        await client.send("Page.navigate", {url: "https://www.microsoft.com"});
        await new Promise((resolve) => client.on("Page.loadEventFired", resolve));
        await new Promise((resolve) => setTimeout(resolve, 10000));
        let result = await
client.send("Profiler.takePrecisionCoverage");
        fs.writeFileSync("coverage.json", JSON.stringify(result, null, 2));
    }). catch(err => {
        console.error(err);
    });
});

    after(() => {
    });
});
</code>```

Steps I am taking:

Start the browser via ./chrome --remote-debugging-port=6813;

Run the test.

答:
I just got the same issue.
It seems there is one debugger link by tabs, so just replace :

session.openDebuggingProtocol("http://localhost:6813")

by

session.openDebuggingProtocol(tab.webSocketDebuggerUrl);

Body:
I am currently using the Chrome profiling APIs to get the code coverage as below.

But whenever I try to run the tests, I get the following error:

Error: unexpected server response (404)
       at ClientRequest.response (/Users/svg7/projects/examples/build/js/testSuites.js:8419:16)
       at ClientRequest.g (events.js:291:16)
       at emitOne (events.js:96:13)
       at ClientRequest.emit (events.js:188:7)
       at HTTPParser.parserOnIncomingClient (_http_client.js:472:21)
       at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
       at Socket.socketOnData (_http_client.js:361:20)
       at emitOne (events.js:96:13)
       at Socket.emit (events.js:188:7)
       at readableAddChunk (_stream_readable.js:176:18)

My code is as follows:

import * as fs from "fs";
import {createSession} from "chrome-debugging-client";

describe("Functional Coverage example", function() {
this.timeout(880000);
it("Get the coverage", () => {
    createSession(async (session) => {
        const api = await session.createAPIClient("localhost", 6813);
        console.dir(api);
        const tabs = await api.listTabs();
        const tab = tabs[0];
        console.log("====>");
        console.log(tab.webSocketDebuggerUrl);
        // browser.stop();
        let client = await session.openDebuggingProtocol("http://localhost:6813");
        await client.send("Profiler.enable");
        await client.send("Page.enable");
        await client.send("Profiler.startPrecisionCoverage", {callCount: true});
        await client.send("Page.navigate", {url: "https://www.microsoft.com"});
        await new Promise((resolve) => client.on("Page.loadEventFired", resolve));
        await new Promise((resolve) => setTimeout(resolve, 10000));
        let result = await
client.send("Profiler.takePrecisionCoverage");
        fs.writeFileSync("coverage.json", JSON.stringify(result, null, 2));
    }). catch(err => {
        console.error(err);
    });
});

    after(() => {
    });
});

Steps I am taking:

Start the browser via ./chrome --remote-debugging-port=6813;

Run the test.


问:
Rx.js can't get past values
I am trying to get the last 3 values emitted, with the code bellow I am expecting that after populating uiOrder and calling cancelOrderItem() for few times I can get access to last 3 revisions of the order with getHistory(), but I am actually getting the last (current) value 3 times, i have tried replaySubject(3) with the same results.
this is my code:

```<code>export class OrdersService {

  public readonly orders: Observable<Order[]>;
  public readonly uiOrder: Observable<Order>;

  private _orders: BehaviorSubject<Order[]>;
  private _uiOrder: BehaviorSubject<Order>;

  private dataStore: {
    uiOrder: Order,
    orders: Order[]
 };

  constructor() {

    this.dataStore = {
      uiOrder: null,
      orders: []
    };

    this._orders = <BehaviorSubject<Order[]>>new BehaviorSubject([]);
    this._uiOrder = <BehaviorSubject<Order>>new BehaviorSubject({});
    this.orders = this._orders.asObservable();
    this.uiOrder = this._uiOrder.asObservable();
  }

  getOrder(orderId: number | string) {
    for (let i = 0; i < this.dataStore.orders.length; i++) {
      if (this.dataStore.orders[i].id == orderId) {
        this.dataStore.orders[i].lastAccess = moment().format().slice(0, 19) + 'Z';
        this.dataStore.uiOrder = this.dataStore.orders[i];
        this.updateUiOrder();
      }
    }
  }

  cancelOrderItem(action) {
    this.dataStore.uiOrder.sections[action.sectionIndex].orderDetails.splice(action.orderDetailsIndex, 1);
    this.updateUiOrder()
  }

  getHistory() {
    this.uiOrder.take(3).subscribe((res) => {
      console.log('uiOrder', res);
    }).unsubscribe()
  }

  updateUiOrder() {
    console.log('updating ui order');
    this._uiOrder.next(this.dataStore.uiOrder);
  }

}
</code>```

what am I doing wrong?

答:
The operator you are looking for is bufferCount(3,1) which creates a sliding window of the last 3 values emitted. Downside: it will only start emitting after 3 values have been accumulated. If you want to have the first value you can do something like this:

```<code>Rx.Observable.from([null,null])
  .concat(this.uiOrder)
  .bufferCount(3,1)
  .subscribe(uiOrderHistory => ... );
</code>```

That way your marble diagram will look as follows:

```<code>---Order1-----------------Order2--------------------Order3
bufferCount(3,1)
---[null,null,Order1]-----[null,Order1,Order2]------[Order1,Order2,Order3]
</code>```

Title: Rx.js can't get past values

Body:
I am trying to get the last 3 values emitted, with the code bellow I am expecting that after populating uiOrder and calling cancelOrderItem() for few times I can get access to last 3 revisions of the order with getHistory(), but I am actually getting the last (current) value 3 times, i have tried replaySubject(3) with the same results.
this is my code:

export class OrdersService {

  public readonly orders: Observable<Order[]>;
  public readonly uiOrder: Observable<Order>;

  private _orders: BehaviorSubject<Order[]>;
  private _uiOrder: BehaviorSubject<Order>;

  private dataStore: {
    uiOrder: Order,
    orders: Order[]
 };

  constructor() {

    this.dataStore = {
      uiOrder: null,
      orders: []
    };

    this._orders = <BehaviorSubject<Order[]>>new BehaviorSubject([]);
    this._uiOrder = <BehaviorSubject<Order>>new BehaviorSubject({});
    this.orders = this._orders.asObservable();
    this.uiOrder = this._uiOrder.asObservable();
  }

  getOrder(orderId: number | string) {
    for (let i = 0; i < this.dataStore.orders.length; i++) {
      if (this.dataStore.orders[i].id == orderId) {
        this.dataStore.orders[i].lastAccess = moment().format().slice(0, 19) + 'Z';
        this.dataStore.uiOrder = this.dataStore.orders[i];
        this.updateUiOrder();
      }
    }
  }

  cancelOrderItem(action) {
    this.dataStore.uiOrder.sections[action.sectionIndex].orderDetails.splice(action.orderDetailsIndex, 1);
    this.updateUiOrder()
  }

  getHistory() {
    this.uiOrder.take(3).subscribe((res) => {
      console.log('uiOrder', res);
    }).unsubscribe()
  }

  updateUiOrder() {
    console.log('updating ui order');
    this._uiOrder.next(this.dataStore.uiOrder);
  }

}

what am I doing wrong?

Body:
The operator you are looking for is bufferCount(3,1) which creates a sliding window of the last 3 values emitted. Downside: it will only start emitting after 3 values have been accumulated. If you want to have the first value you can do something like this:

Rx.Observable.from([null,null])
  .concat(this.uiOrder)
  .bufferCount(3,1)
  .subscribe(uiOrderHistory => ... );

That way your marble diagram will look as follows:

---Order1-----------------Order2--------------------Order3
bufferCount(3,1)
---[null,null,Order1]-----[null,Order1,Order2]------[Order1,Order2,Order3]


问:
Should CodeContracts replace the regular ArgumentExceptions?
Could I start using CodeContracts instead of:

```<code>if (XXX == Y)
    throw new ArgumentException("bla bla");
</code>```

How does it work if I develop a library and my library users do not use CodeContracts?

答:
To the point: It's possible to write statements like this

```<code>Contract.Requires<ArgumentNullException>(argumentToCheck, "argumentToCheck");
</code>```

If you enable the Runtime checker in your build configuration, the rewriter will rewrite preconditions like this to an ordinary ArgumentNullException.

Callers of your code will be shown an ArgumentNullException, or whatever exception you provide, regardless of whether or not they have Code Contracts installed.

Body:
Could I start using CodeContracts instead of:

if (XXX == Y)
    throw new ArgumentException("bla bla");

How does it work if I develop a library and my library users do not use CodeContracts?

Body:
To the point: It's possible to write statements like this

Contract.Requires<ArgumentNullException>(argumentToCheck, "argumentToCheck");

If you enable the Runtime checker in your build configuration, the rewriter will rewrite preconditions like this to an ordinary ArgumentNullException.

Callers of your code will be shown an ArgumentNullException, or whatever exception you provide, regardless of whether or not they have Code Contracts installed.


问:
How should I amend my base case to avoid stack overflow in my recursive code?
Basically my code needs to calculate the sum of the path in an nxn matrix ( starts at 0,0), and adds up the smallest sum where I'm only allowed to move right or downwards.

For example the matrix below should output 18 because the min path is 5 1 2 4 6, but I don't know how should my base case be here. I know I should stop the recursion once I reach array [n][n] though..in my code below I'm getting a stackoverflow error.

```<code>512
234
566
</code>```

```<code>import java.util.*;

public class shortestpath {

    public static int findminpath(int [][]c,int x,int y,int n) {
        if (x==n-1 && y==n-1) {
            return c[x][y];
        } else {
            int path1 = findminpath(c,x+1,y,n);
            int path2 = findminpath (c,x,y+1,n);
            return c[x][y] + Math.min(path1,path2);
        }
    }

    public static void main (String [] args) {
        Scanner sc = new Scanner (System.in);
        int[][] array = new int[3][3];
        for (int i=0; i<array.length; i++){
            for (int j=0; j<array.length; j++){
                array[i][j] = sc.nextInt();
            }
        }
        System.out.println(findminpath(array,0,0,array.length));
    }
}
</code>```

答:
The issue comes from your if statement.

```<code>if (x==n-1 && y==n-1)
</code>```

Note that if you trace through your code by hand, you will have the following method calls on your stack.

```<code>findminpath(array, 0, 0, 3)
findminpath(array, 1, 0, 3)
findminpath(array, 2, 0, 3)
findminpath(array, 3, 0, 3)
findminpath(array, 4, 0, 3)
findminpath(array, 5, 0, 3)
findminpath(array, 6, 0, 3)
findminpath(array, 7, 0, 3)
....
</code>```

The reason is because of the && you have in the if statement. y hasn't incremented yet, and it will never increment from this recursion because you will go until x reaches the maximum int value.

ContentLicense: CC BY-SA 4.0

Body:
Basically my code needs to calculate the sum of the path in an nxn matrix ( starts at 0,0), and adds up the smallest sum where I'm only allowed to move right or downwards.

For example the matrix below should output 18 because the min path is 5 1 2 4 6, but I don't know how should my base case be here. I know I should stop the recursion once I reach array [n][n] though..in my code below I'm getting a stackoverflow error.

512
234
566

import java.util.*;

public class shortestpath {

    public static int findminpath(int [][]c,int x,int y,int n) {
        if (x==n-1 && y==n-1) {
            return c[x][y];
        } else {
            int path1 = findminpath(c,x+1,y,n);
            int path2 = findminpath (c,x,y+1,n);
            return c[x][y] + Math.min(path1,path2);
        }
    }

    public static void main (String [] args) {
        Scanner sc = new Scanner (System.in);
        int[][] array = new int[3][3];
        for (int i=0; i<array.length; i++){
            for (int j=0; j<array.length; j++){
                array[i][j] = sc.nextInt();
            }
        }
        System.out.println(findminpath(array,0,0,array.length));
    }
}

Body:
The issue comes from your if statement.

if (x==n-1 && y==n-1)

Note that if you trace through your code by hand, you will have the following method calls on your stack.

findminpath(array, 0, 0, 3)
findminpath(array, 1, 0, 3)
findminpath(array, 2, 0, 3)
findminpath(array, 3, 0, 3)
findminpath(array, 4, 0, 3)
findminpath(array, 5, 0, 3)
findminpath(array, 6, 0, 3)
findminpath(array, 7, 0, 3)
....

The reason is because of the && you have in the if statement. y hasn't incremented yet, and it will never increment from this recursion because you will go until x reaches the maximum int value.


问:
excel vba copy value from a column and paste value in a cell
I have data like below. First column belongs to column A and second column belongs to column B.

```<code>1   q
1   q
2   q
2   q
2   q
3   q
</code>```

I would like to insert empty rows whenever values in column A change. To insert rows I am using the macro from this site.

```<code>'select column a before running the macro
Sub InsertRowsAtValueChange()
'Update 20140716
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

Application.ScreenUpdating = False
For i = WorkRng.Rows.Count To 2 Step -1
    If WorkRng.Cells(i, 1).Value <> WorkRng.Cells(i - 1, 1).Value Then
        WorkRng.Cells(i, 1).EntireRow.Insert
    End If
Next
Application.ScreenUpdating = True
End Sub
</code>```

After that I would like to copy each set of values from column A and paste in a cell in column C. While pasting them, I would like to paste values in a cell in a row format (by concatenating them) and separating them by a space. In below case, cells c1 should have 1 1, cell c4 should have 2 2 2 and cell c8 should have 3

How to do this? I tried to record macro using first copying each set of values then pasting them after transposing into a row. But I am having hard time copying values again and pasting them within a single cell

答:
The Before and After for code bellow:

```<code>Option Explicit

Sub InsertRowsAtValueChange()
    Dim rng As Range, itms As Variant, cel As Range, i As Long, firstRow As Long

    Set rng = Range("A3:A1000")
    firstRow = rng.Row - 1

    Application.ScreenUpdating = False
    For i = rng.Rows.Count To 1 Step -1
        If rng.Cells(i, 1).Value2 <> rng.Cells(i - 1, 1).Value2 Then
            If i < rng.Row - 1 Then
                Set cel = rng(i, 1)
            Else
                rng.Cells(i, 1).EntireRow.Insert
                Set cel = rng(i + 1, 1)
            End If
            With cel.CurrentRegion
                itms = .Columns(1)
                If .Columns(1).Rows.Count > 1 Then itms = Join(Application.Transpose(itms))
                cel.Offset(0, 2) = itms
            End With
        End If
        If i = 1 Then Exit For
    Next
    Application.ScreenUpdating = True
End Sub
</code>```

Body:
I have data like below. First column belongs to column A and second column belongs to column B.

1   q
1   q
2   q
2   q
2   q
3   q

I would like to insert empty rows whenever values in column A change. To insert rows I am using the macro from this site.

'select column a before running the macro
Sub InsertRowsAtValueChange()
'Update 20140716
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

Application.ScreenUpdating = False
For i = WorkRng.Rows.Count To 2 Step -1
    If WorkRng.Cells(i, 1).Value <> WorkRng.Cells(i - 1, 1).Value Then
        WorkRng.Cells(i, 1).EntireRow.Insert
    End If
Next
Application.ScreenUpdating = True
End Sub

After that I would like to copy each set of values from column A and paste in a cell in column C. While pasting them, I would like to paste values in a cell in a row format (by concatenating them) and separating them by a space. In below case, cells c1 should have 1 1, cell c4 should have 2 2 2 and cell c8 should have 3

How to do this? I tried to record macro using first copying each set of values then pasting them after transposing into a row. But I am having hard time copying values again and pasting them within a single cell

Body:
The Before and After for code bellow:

Option Explicit

Sub InsertRowsAtValueChange()
    Dim rng As Range, itms As Variant, cel As Range, i As Long, firstRow As Long

    Set rng = Range("A3:A1000")
    firstRow = rng.Row - 1

    Application.ScreenUpdating = False
    For i = rng.Rows.Count To 1 Step -1
        If rng.Cells(i, 1).Value2 <> rng.Cells(i - 1, 1).Value2 Then
            If i < rng.Row - 1 Then
                Set cel = rng(i, 1)
            Else
                rng.Cells(i, 1).EntireRow.Insert
                Set cel = rng(i + 1, 1)
            End If
            With cel.CurrentRegion
                itms = .Columns(1)
                If .Columns(1).Rows.Count > 1 Then itms = Join(Application.Transpose(itms))
                cel.Offset(0, 2) = itms
            End With
        End If
        If i = 1 Then Exit For
    Next
    Application.ScreenUpdating = True
End Sub


问:
Angular 2 - select binding
I want to select in <select> an option which I defined in component. But when I want to print this in console I get undefined. My code:

component.html:

```<code><div class="row">
    <div class="form-group col-md-6">
        <label>Select option:</label>
        <select class="form-control" [(ngModel)]="selectedOption">
            <option *ngFor="let item of options" [value]="item">{{ item.display }}</option>
        </select>
    </div>
</div>

<button type="button" (click)="showOption()">Show selected option</button>
</code>```

component.ts:

```<code>selectedOption: any;

sortOptions = [
    {
        value: 'option1',
        display: 'First option'
    },
    {
        value: 'option2',
        display: 'Second option'
    }
];

showOption(): void {
    console.log(this.selectedOption.value);
}
</code>```

When I try print console.log(this.selectedOption.value); I get "undefined" and when I try to print console.log(this.selectedOption) I get "[option Option]"

I don't know how to resole it.

答:
Try with [ngValue] instead [value]:

```<code><select [(ngModel)]="selectedOption">
   <option value=""></option>
   <option *ngFor="let item of options" [ngValue]="item">
     {{item.display}}
   </option>
</select>
</code>```

Title: Angular 2 - select binding

Body:
I want to select in <select> an option which I defined in component. But when I want to print this in console I get undefined. My code:

component.html:

        Select option:
        <select class="form-control" [(ngModel)]="selectedOption">
            <option *ngFor="let item of options" [value]="item">{{ item.display }}</option>
        </select>

<button type="button" (click)="showOption()">Show selected option</button>

component.ts:

selectedOption: any;

sortOptions = [
    {
        value: 'option1',
        display: 'First option'
    },
    {
        value: 'option2',
        display: 'Second option'
    }
];

showOption(): void {
    console.log(this.selectedOption.value);
}

When I try print console.log(this.selectedOption.value); I get "undefined" and when I try to print console.log(this.selectedOption) I get "[option Option]"

I don't know how to resole it.

Body:
Try with [ngValue] instead [value]:

<select [(ngModel)]="selectedOption">
   <option value=""></option>
   <option *ngFor="let item of options" [ngValue]="item">
     {{item.display}}
   </option>
</select>


问:
Why isn't the CSS from my JsFiddle working the same way in my server?
I have the following JSFiddle, which positions an "X" to the left of a pop-out window: http://jsfiddle.net/XDaEk/601/

CSS:

```<code>.x {
    display: none;
   position: fixed;
    top: 25%;
    left:60px;
    transition: transform .25s ease-in-out;
}

.x:before {
    content: "";
    position: absolute;
    display: block;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 32px;
    height: 0;
    border-top: 3px solid black;
    transform: rotate(45deg);
    transform-origin: center;
}
.x:after {
    content: "";
    position: absolute;
    display: block;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 32px;
    height: 0;
    border-top: 3px solid black;
    transform: rotate(-45deg);
    transform-origin: center;
}

.alert-div {
  display:none;
    position: fixed;
    top: 0%;
    left: 0%;
    height: 100%;
    width: 100%;
    padding-left: 50px;
    padding-bottom: 50px;
    padding-right: 50px;
    padding-top: 50px;
    background-color: white;
    color: white;
    opacity:0.7;
    overflow-y: auto;
}
</code>```

HTML

```<code>  <div class="alert-div2"> <div class="x"></div>Sed ut perspiciatis, unde omnis …</div>
</code>```

If I copy this exact same CSS & HTML into my file on byethost.com, the "x" appears in the center of the screen. I surrounded the CSS with  in the head. The HTML is in the body. I've tried copying this CSS & HTML into another JSFiddle and it works, so it seems to have something to do with Byethost.

There are no console errors related to this.

Here's the actual site. The button to show pop out is at the very bottom. It says "Post Message"  http://carouseltest.byethost8.com/aplayground.php    (Neither of the 2 errors on the console have to do with this code. They were there before I added this.)

Here's a photo of how it appears on Byethost: http://imgur.com/a/BSzER

答:
Looks like position: fixed is being overridden (although it's difficult to be certain when it's not reproducible). Try updating to:

```<code>.x {
    display: none;

    /* add !important in case this is what's getting zapped and affecting layout */
    position: fixed !important;

    top: 25%;
    left:60px;
    transition: transform .25s ease-in-out;
}
</code>```

Body:
I have the following JSFiddle, which positions an "X" to the left of a pop-out window: http://jsfiddle.net/XDaEk/601/

CSS:

.x {
    display: none;
   position: fixed;
    top: 25%;
    left:60px;
    transition: transform .25s ease-in-out;
}

.x:before {
    content: "";
    position: absolute;
    display: block;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 32px;
    height: 0;
    border-top: 3px solid black;
    transform: rotate(45deg);
    transform-origin: center;
}
.x:after {
    content: "";
    position: absolute;
    display: block;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 32px;
    height: 0;
    border-top: 3px solid black;
    transform: rotate(-45deg);
    transform-origin: center;
}

.alert-div {
  display:none;
    position: fixed;
    top: 0%;
    left: 0%;
    height: 100%;
    width: 100%;
    padding-left: 50px;
    padding-bottom: 50px;
    padding-right: 50px;
    padding-top: 50px;
    background-color: white;
    color: white;
    opacity:0.7;
    overflow-y: auto;
}

HTML

Sed ut perspiciatis, unde omnis …

If I copy this exact same CSS & HTML into my file on byethost.com, the "x" appears in the center of the screen. I surrounded the CSS with  in the head. The HTML is in the body. I've tried copying this CSS & HTML into another JSFiddle and it works, so it seems to have something to do with Byethost.

There are no console errors related to this.

Here's the actual site. The button to show pop out is at the very bottom. It says "Post Message"  http://carouseltest.byethost8.com/aplayground.php    (Neither of the 2 errors on the console have to do with this code. They were there before I added this.)

Here's a photo of how it appears on Byethost: http://imgur.com/a/BSzER

Body:
Looks like position: fixed is being overridden (although it's difficult to be certain when it's not reproducible). Try updating to:

.x {
    display: none;

    /* add !important in case this is what's getting zapped and affecting layout */
    position: fixed !important;

    top: 25%;
    left:60px;
    transition: transform .25s ease-in-out;
}


问:
Assignment using an object and input data JAVA
so my assignment is to create an object named city and have the longitude, latitude and name of the city and then ask for the number of cities, then the users input of the name, longitude, and latitude into an array for access. How would i accomplish this with what i have now?

```<code>import java.util.Scanner;

public class Assignment3 {

    public static void main(String[] args) {

        Scanner lat = new Scanner(System.in);  //for double data
        Scanner lon = new Scanner(System.in);  //for double data
        Scanner city = new Scanner(System.in); //for string data
        Scanner in = new Scanner(System.in);  //for int

        System.out.print("How many cities? ");
        int number = in.nextInt();

        City [] cities = new City [number];

        for(int i = 1; i <= number; i++){

            System.out.println("City # " + i);
            System.out.print("Enter name: " );
            String name = city.Next();
            System.out.print("Enter longitude: ");
            double longitude = lon.nextDouble();
            System.out.println("Enter latitude: ");
            double latitude = lat.nextDouble();

        }

    }

}

public class City {

    String name;      //name of cities
    double lon, lat;  //longitude & latitude

    City(String name, double lon, double lat)
    {
        this.name = name;
        this.lon = lon;
        this.lat = lat;
    }

    public void report(){    //should report current position of a city

        System.out.println("City: " + this.name); // displays city name
        System.out.println("Longitude: " + this.lon);  //displays longitude
        System.out.println("Latitude: " + this.lat);    //displays latitude
    }

    public double distanceFrom(City otherCity){  //should calculate the distance
        return 0;
    }
}
</code>```

The point is so that you can then ask for the cities direct location and then the distance between them. Any help is greatly appreciated thank you

答:
Not sure if I understood your question but you need to create a city object with the current information you've collected in the for loop. Then save it in your cities array.

```<code>for(int i = 0; i < number; i++){

    System.out.println("City # " + (i+1));
    System.out.print("Enter name: " );
    String name = city.Next();
    System.out.print("Enter longitude: ");
    double longitude = lon.nextDouble();
    System.out.println("Enter latitude: ");
    double latitude = lat.nextDouble();

    City a_city = new City(name,longitude,latitude);
    cities[i] = a_city;

}
</code>```

I changed your for loop from i=1 to i=0

To find the distance between two cities you might want to look at this post
Calculate distance between two latitude-longitude points? (Haversine formula)

Body:
so my assignment is to create an object named city and have the longitude, latitude and name of the city and then ask for the number of cities, then the users input of the name, longitude, and latitude into an array for access. How would i accomplish this with what i have now?

import java.util.Scanner;

public class Assignment3 {

    public static void main(String[] args) {

        Scanner lat = new Scanner(System.in);  //for double data
        Scanner lon = new Scanner(System.in);  //for double data
        Scanner city = new Scanner(System.in); //for string data
        Scanner in = new Scanner(System.in);  //for int

        System.out.print("How many cities? ");
        int number = in.nextInt();

        City [] cities = new City [number];

        for(int i = 1; i <= number; i++){

            System.out.println("City # " + i);
            System.out.print("Enter name: " );
            String name = city.Next();
            System.out.print("Enter longitude: ");
            double longitude = lon.nextDouble();
            System.out.println("Enter latitude: ");
            double latitude = lat.nextDouble();

        }

    }

}

public class City {

    String name;      //name of cities
    double lon, lat;  //longitude & latitude

    City(String name, double lon, double lat)
    {
        this.name = name;
        this.lon = lon;
        this.lat = lat;
    }

    public void report(){    //should report current position of a city

        System.out.println("City: " + this.name); // displays city name
        System.out.println("Longitude: " + this.lon);  //displays longitude
        System.out.println("Latitude: " + this.lat);    //displays latitude
    }

    public double distanceFrom(City otherCity){  //should calculate the distance
        return 0;
    }
}

The point is so that you can then ask for the cities direct location and then the distance between them. Any help is greatly appreciated thank you

Body:
Not sure if I understood your question but you need to create a city object with the current information you've collected in the for loop. Then save it in your cities array.

for(int i = 0; i < number; i++){

    System.out.println("City # " + (i+1));
    System.out.print("Enter name: " );
    String name = city.Next();
    System.out.print("Enter longitude: ");
    double longitude = lon.nextDouble();
    System.out.println("Enter latitude: ");
    double latitude = lat.nextDouble();

    City a_city = new City(name,longitude,latitude);
    cities[i] = a_city;

}

I changed your for loop from i=1 to i=0

To find the distance between two cities you might want to look at this post
Calculate distance between two latitude-longitude points? (Haversine formula)


问:
Haskell function definition not working as expected
I am new to functional programming and Haskell. Trying to learn it. Not sure what is wrong with the following definition:

Function definition in test.h

```<code>drop5 [a]  = drop 5 [a]
</code>```

Trying to use this function I get Program error

```<code>$:load test.h
$drop5 [2,3,4,5,6,7,8]
Program error: pattern match failure: drop5 [2,3,4,5,6,7,8]
$:t drop5
drop5 :: [a] -> [a]
</code>```

When I change the definition to following it works; meaning it takes a list and drops first 5 elements of the list

```<code>drop5 ns = drop 5 ns
</code>```

And in this case when print type I see:

```<code>$:t drop5
drop5 :: [a] -> [a]
</code>```

I am not sure why is the first definition different than second? And what does the error "Program error: pattern match failure means"?

答:
[a] is telling Haskell that there is only one element in a list, while ns tells Haskell that it could be anything (even a boolean if you want) until you finish the function and it identifies the output and input type. You could also explicitly tell Haskell what the input and output type is by adding this above that line:

```<code>drop5 :: [Integer] -> [Integer]
</code>```

Which could be found by doing :t drop5 in GHCI.

Also, on a side note, this code can be reduced. By changing it to:

```<code>drop5 = drop 5
</code>```

This may not make sense to you right now, but as you learn more you should learn that all Haskell functions take one argument.

Body:
I am new to functional programming and Haskell. Trying to learn it. Not sure what is wrong with the following definition:

Function definition in test.h

drop5 [a]  = drop 5 [a]

Trying to use this function I get Program error

$:load test.h
$drop5 [2,3,4,5,6,7,8]
Program error: pattern match failure: drop5 [2,3,4,5,6,7,8]
$:t drop5
drop5 :: [a] -> [a]

When I change the definition to following it works; meaning it takes a list and drops first 5 elements of the list

drop5 ns = drop 5 ns

And in this case when print type I see:

$:t drop5
drop5 :: [a] -> [a]

I am not sure why is the first definition different than second? And what does the error "Program error: pattern match failure means"?

Body:
[a] is telling Haskell that there is only one element in a list, while ns tells Haskell that it could be anything (even a boolean if you want) until you finish the function and it identifies the output and input type. You could also explicitly tell Haskell what the input and output type is by adding this above that line:

drop5 :: [Integer] -> [Integer]

Which could be found by doing :t drop5 in GHCI.

Also, on a side note, this code can be reduced. By changing it to:

drop5 = drop 5

This may not make sense to you right now, but as you learn more you should learn that all Haskell functions take one argument.


问:
Fetch and Update Nested JSON attribute value
I have a nested JSON which looks like this.

```<code>{
"eventId" : "12345",
"eventName" : "carnival",
"object": {
    "objectId" : "5678",
    "objectFiles" : [{"fileName":"text.txt", "fileContent":"This is a test file."},
                    {"fileName":"text2.txt", "fileContent":"This is a test2 file."}]
    }
}
</code>```

Here I have to fetch the eventFiles key, replace the fileContent value with Base64Encoded String and place it back to the same eventFiles attribute. I know that I can use Jackson Mapper to convert it into Map and iterate them one by one, untill I find eventFiles key, then fetch and replace the value and store it back again. I tried to convert it as a Map using TypeReference<String, Object> or even TypeReference<Map<String, Map<String, Object>>> but the problem here is the nested JSON where ultimately it would become Map inside of a Map inside of a Map which would become pretty complex to handle.

Is there any other simpler way to accomplish this? Any suggestions would be really helpful. Thanks in advance.

答:
If your Json has a fixed format you can use Gson (https://github.com/google/gson) and convert it to an Object that represent your json.

It would look something like this:

```<code>public class CustomEvent {
    String eventId;
    String eventName;
    CustomObject object;
}

public class CustomObject {
    String objectId;
    List<CustomFile> objectFiles;
}

public class CustomFile {
    String fileName;
    String fileContent;
}
</code>```

And you could use it like this:

```<code>Gson gson = new Gson();
CustomEvent event = gson.fromJson(yourString, Event.class)
// Do whatever you want with the event

String modifiedJson = gson.toJson(event);
</code>```

Hope it helped

Body:
I have a nested JSON which looks like this.

{
"eventId" : "12345",
"eventName" : "carnival",
"object": {
    "objectId" : "5678",
    "objectFiles" : [{"fileName":"text.txt", "fileContent":"This is a test file."},
                    {"fileName":"text2.txt", "fileContent":"This is a test2 file."}]
    }
}

Here I have to fetch the eventFiles key, replace the fileContent value with Base64Encoded String and place it back to the same eventFiles attribute. I know that I can use Jackson Mapper to convert it into Map and iterate them one by one, untill I find eventFiles key, then fetch and replace the value and store it back again. I tried to convert it as a Map using TypeReference<String, Object> or even TypeReference<Map<String, Map<String, Object>>> but the problem here is the nested JSON where ultimately it would become Map inside of a Map inside of a Map which would become pretty complex to handle.

Is there any other simpler way to accomplish this? Any suggestions would be really helpful. Thanks in advance.

Body:
If your Json has a fixed format you can use Gson (https://github.com/google/gson) and convert it to an Object that represent your json.

It would look something like this:

public class CustomEvent {
    String eventId;
    String eventName;
    CustomObject object;
}

public class CustomObject {
    String objectId;
    List<CustomFile> objectFiles;
}

public class CustomFile {
    String fileName;
    String fileContent;
}

And you could use it like this:

Gson gson = new Gson();
CustomEvent event = gson.fromJson(yourString, Event.class)
// Do whatever you want with the event

String modifiedJson = gson.toJson(event);

Hope it helped


问:
Getting thread access exceptions on OnCollectionChanged after Creators Update
In my program, I have an abstract class ObservableKeyedCollection<TKey, TItem> that inherits from KeyedCollection<TKey, TItem> and also implements INotifyCollectionChanged.

A realisation of this abstract class is bound to a ListBox. In this ListBox, I edit items on double click, and upon acceptance, I remove the old instance of the edited item from this ObservableKeyedCollection<TKey, TItem> realisation, and add the new instance that has been modified.

It all worked well before Windows 10 Creators Update (1703, build number 15063.250). Since the update, ObservableKeyedCollection<TKey, TItem> started throwing InvalidOperationExceptions with the following message:

The calling thread cannot access this object because a different thread owns it.

I do not use any async operations in this region of the code.

The whole stack trace would be too long but here is the top part starting with OnCollectionChanged:

at System.Windows.Threading.Dispatcher.VerifyAccess()
     at System.Windows.Threading.DispatcherObject.VerifyAccess()
     at System.Windows.DependencyObject.GetValue(DependencyProperty dp)
     at System.Windows.Controls.Primitives.Selector.GetIsSelected(DependencyObject element)
     at System.Windows.Controls.Primitives.Selector.ItemSetIsSelected(ItemInfo info, Boolean value)
     at System.Windows.Controls.Primitives.Selector.SelectionChanger.CreateDeltaSelectionChange(List'1 unselectedItems, List'1 selectedItems)
     at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
     at System.Windows.Controls.Primitives.Selector.RemoveFromSelection(NotifyCollectionChangedEventArgs e)
     at System.Windows.Controls.Primitives.Selector.OnItemsChanged(NotifyCollectionChangedEventArgs e)
     at System.Windows.Controls.ItemsControl.OnItemCollectionChanged2(Object sender, NotifyCollectionChangedEventArgs e)
     at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
     at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
     at System.Windows.Controls.ItemCollection.OnViewCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
     at System.Windows.WeakEventManager.ListenerList'1.DeliverEvent(Object sender, EventArgs e, Type managerType)
     at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list)
     at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args)
     at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
     at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
     at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args, Int32 adjustedOldIndex, Int32 adjustedNewIndex)
     at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)
     at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
     at TetheredSun.ObservableKeyedCollection'2.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at e:\Phil\Programozás\Modulok\TetheredSun.1.0\TetheredSun\ObservableKeyedCollection.cs, line number: 68
     at TetheredSun.ObservableKeyedCollection`2.RemoveItem(Int32 index) at [...]

Edit 1:

Here is the offending code section that worked all right before Creators Update (an override of KeyedCollection<TKey, TItem>.RemoveItem(int index)
) :

```<code>protected override void RemoveItem(int index)
{
    TItem item = this[index];
    base.RemoveItem(index);
    if (deferNotifyCollectionChanged) return;
    if (item is IList) {
        // Listeners do not support multiple item changes, and our item happens to be an IList, so we must raise NotifyCollectionChangedAction.Reset.
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    } else {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
    }
    OnPropertyChanged(new PropertyChangedEventArgs("Count"));
}
</code>```

The problem seems to occur only if I invoke OnCollectionChanged with the NotifyCollectionChangedAction.Remove action. Replacing it with NotifyCollectionChangedAction.Reset seems to avert the exception:

```<code>protected override void RemoveItem(int index)
{
    TItem item = this[index];
    base.RemoveItem(index);
    if (deferNotifyCollectionChanged) return;
    // No exception thrown so far if I stick to NotifyCollectionChangedAction.Reset:
    OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    OnPropertyChanged(new PropertyChangedEventArgs("Count"));
}
</code>```

I have tried to solve the problem with a Dispatcher as seen here: https://stackoverflow.com/a/22026686/2659699 but though my dispatcher is not null, its CheckAccess() evaluates to true, and I keep getting the same exception upon NotifyCollectionChangedEventHandler.Invoke().

Your thoughts and assistance are greatly appreciated.

答:
I had a similar problem and also after Win 10 creators update.

This wrapper class using BindingOperations.EnableCollectionSynchronization worked for me:

```<code>public class SynchronizedObservableCollection<T> : ObservableCollection<T>
{
    private readonly object _lockObject = new object();

    public SynchronizedObservableCollection()
    {
        Init();
    }

    public SynchronizedObservableCollection(List<T> list) : base(list)
    {
        Init();
    }

    public SynchronizedObservableCollection(IEnumerable<T> collection) : base(collection)
    {
        Init();
    }

    private void Init()
    {
        BindingOperations.EnableCollectionSynchronization(this, _lockObject);
    }
}
</code>```

Body:
In my program, I have an abstract class ObservableKeyedCollection<TKey, TItem> that inherits from KeyedCollection<TKey, TItem> and also implements INotifyCollectionChanged.

A realisation of this abstract class is bound to a ListBox. In this ListBox, I edit items on double click, and upon acceptance, I remove the old instance of the edited item from this ObservableKeyedCollection<TKey, TItem> realisation, and add the new instance that has been modified.

It all worked well before Windows 10 Creators Update (1703, build number 15063.250). Since the update, ObservableKeyedCollection<TKey, TItem> started throwing InvalidOperationExceptions with the following message:

The calling thread cannot access this object because a different thread owns it.

I do not use any async operations in this region of the code.

The whole stack trace would be too long but here is the top part starting with OnCollectionChanged:

at System.Windows.Threading.Dispatcher.VerifyAccess()
     at System.Windows.Threading.DispatcherObject.VerifyAccess()
     at System.Windows.DependencyObject.GetValue(DependencyProperty dp)
     at System.Windows.Controls.Primitives.Selector.GetIsSelected(DependencyObject element)
     at System.Windows.Controls.Primitives.Selector.ItemSetIsSelected(ItemInfo info, Boolean value)
     at System.Windows.Controls.Primitives.Selector.SelectionChanger.CreateDeltaSelectionChange(List'1 unselectedItems, List'1 selectedItems)
     at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
     at System.Windows.Controls.Primitives.Selector.RemoveFromSelection(NotifyCollectionChangedEventArgs e)
     at System.Windows.Controls.Primitives.Selector.OnItemsChanged(NotifyCollectionChangedEventArgs e)
     at System.Windows.Controls.ItemsControl.OnItemCollectionChanged2(Object sender, NotifyCollectionChangedEventArgs e)
     at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
     at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
     at System.Windows.Controls.ItemCollection.OnViewCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
     at System.Windows.WeakEventManager.ListenerList'1.DeliverEvent(Object sender, EventArgs e, Type managerType)
     at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list)
     at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args)
     at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
     at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
     at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args, Int32 adjustedOldIndex, Int32 adjustedNewIndex)
     at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)
     at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
     at TetheredSun.ObservableKeyedCollection'2.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at e:\Phil\Programozás\Modulok\TetheredSun.1.0\TetheredSun\ObservableKeyedCollection.cs, line number: 68
     at TetheredSun.ObservableKeyedCollection`2.RemoveItem(Int32 index) at [...]

Edit 1:

Here is the offending code section that worked all right before Creators Update (an override of KeyedCollection<TKey, TItem>.RemoveItem(int index)
) :

protected override void RemoveItem(int index)
{
    TItem item = this[index];
    base.RemoveItem(index);
    if (deferNotifyCollectionChanged) return;
    if (item is IList) {
        // Listeners do not support multiple item changes, and our item happens to be an IList, so we must raise NotifyCollectionChangedAction.Reset.
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    } else {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
    }
    OnPropertyChanged(new PropertyChangedEventArgs("Count"));
}

The problem seems to occur only if I invoke OnCollectionChanged with the NotifyCollectionChangedAction.Remove action. Replacing it with NotifyCollectionChangedAction.Reset seems to avert the exception:

protected override void RemoveItem(int index)
{
    TItem item = this[index];
    base.RemoveItem(index);
    if (deferNotifyCollectionChanged) return;
    // No exception thrown so far if I stick to NotifyCollectionChangedAction.Reset:
    OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    OnPropertyChanged(new PropertyChangedEventArgs("Count"));
}

I have tried to solve the problem with a Dispatcher as seen here: https://stackoverflow.com/a/22026686/2659699 but though my dispatcher is not null, its CheckAccess() evaluates to true, and I keep getting the same exception upon NotifyCollectionChangedEventHandler.Invoke().

Your thoughts and assistance are greatly appreciated.

Body:
I had a similar problem and also after Win 10 creators update.

This wrapper class using BindingOperations.EnableCollectionSynchronization worked for me:

public class SynchronizedObservableCollection<T> : ObservableCollection<T>
{
    private readonly object _lockObject = new object();

    public SynchronizedObservableCollection()
    {
        Init();
    }

    public SynchronizedObservableCollection(List<T> list) : base(list)
    {
        Init();
    }

    public SynchronizedObservableCollection(IEnumerable<T> collection) : base(collection)
    {
        Init();
    }

    private void Init()
    {
        BindingOperations.EnableCollectionSynchronization(this, _lockObject);
    }
}


问:
Issues with Kivy Scatter, Image size and position
I am having alot of issues trying to add an image to Scatter in Kivy. I want the image to first appear the same height as the boxlayout. Then I would like to be able to move and scale it (this does work currently). When I run the code the image shows up very small. I would also like the image to resize itself if the size of the window is changed. I am new to kivy so any help would be great. Thanks!</p>

```<code><MyGridLayout>:
rows: 1

BoxLayout:
    id:layout1
    orientation: 'vertical'

    BoxLayout:
        id: box1
        size_hint : [1,0.5]

        StencilView:
            ScatterLayout:
                center_x: box1.center_x
                center_y: box1.center_y

                Image:
                    source: 'histo_test.png'
                    size_hint_y: None
                    size_hint_x: None
                    width: self.parent.width
                    height: self.parent.width/self.image_ratio
                    center: self.parent.center
                    allow_stretch: True
                    keep_ratio: True

    BoxLayout:
        size_hint : [1,0.5]
        id:box2

        StencilView:
            ScatterLayout:
                center_x: box2.center_x
                center_y: box2.center_y

                Image:
                    source: 'flower.png'
                    size_hint_y: None
                    size_hint_x: None
                    width: self.parent.width
                    height: self.parent.width/self.image_ratio
                    center: self.parent.center
                    allow_stretch: True
                    keep_ratio: True
</code>```

答:
The size of the image must be the size of the StencilView, so:

```<code>size: stencil.width, stencil.height
</code>```

or

```<code>width: stencil.width
height: stencil.width/self.image_ratio
</code>```

(stencil is the id of the StencilView)

And the size of the ScatterLayout must be the size of the image:

```<code>size: my_image.size
</code>```

(my_image is the id of the image)

Also you can set the position of the ScatterLayout with the position of the StencilView:

```<code>pos: stencil.pos
</code>```

instead of this:

```<code>center_x: box1.center_x
center_y: box1.center_y
</code>```

Watch this video for more info.

I wrote this code which does almost the same

```<code><MyGridLayout>:
    orientation: 'vertical'
    StencilView:
        id: stencil1
        Scatter:
            pos: stencil1.pos
            size: my_image1.size
            Image:
                id: my_image1
                size: stencil1.width, stencil1.height
                source: 'dog.jpg'
                allow_stretch: True
                keep_ratio: False
    StencilView:
        id: stencil2
        Scatter:
            pos: stencil2.pos
            size: my_image2.size
            Image:
                id: my_image2
                size: stencil2.width, stencil2.height
                source: 'flower.jpg'
                allow_stretch: True
                keep_ratio: False
</code>```

Sorry if my english isn't clear

Body:
I am having alot of issues trying to add an image to Scatter in Kivy. I want the image to first appear the same height as the boxlayout. Then I would like to be able to move and scale it (this does work currently). When I run the code the image shows up very small. I would also like the image to resize itself if the size of the window is changed. I am new to kivy so any help would be great. Thanks!

<MyGridLayout>:
rows: 1

BoxLayout:
    id:layout1
    orientation: 'vertical'

    BoxLayout:
        id: box1
        size_hint : [1,0.5]

        StencilView:
            ScatterLayout:
                center_x: box1.center_x
                center_y: box1.center_y

                Image:
                    source: 'histo_test.png'
                    size_hint_y: None
                    size_hint_x: None
                    width: self.parent.width
                    height: self.parent.width/self.image_ratio
                    center: self.parent.center
                    allow_stretch: True
                    keep_ratio: True

    BoxLayout:
        size_hint : [1,0.5]
        id:box2

        StencilView:
            ScatterLayout:
                center_x: box2.center_x
                center_y: box2.center_y

                Image:
                    source: 'flower.png'
                    size_hint_y: None
                    size_hint_x: None
                    width: self.parent.width
                    height: self.parent.width/self.image_ratio
                    center: self.parent.center
                    allow_stretch: True
                    keep_ratio: True

Body:
The size of the image must be the size of the StencilView, so:

size: stencil.width, stencil.height

or

width: stencil.width
height: stencil.width/self.image_ratio

(stencil is the id of the StencilView)

And the size of the ScatterLayout must be the size of the image:

size: my_image.size

(my_image is the id of the image)

Also you can set the position of the ScatterLayout with the position of the StencilView:

pos: stencil.pos

instead of this:

center_x: box1.center_x
center_y: box1.center_y

Watch this video for more info.

I wrote this code which does almost the same

<MyGridLayout>:
    orientation: 'vertical'
    StencilView:
        id: stencil1
        Scatter:
            pos: stencil1.pos
            size: my_image1.size
            Image:
                id: my_image1
                size: stencil1.width, stencil1.height
                source: 'dog.jpg'
                allow_stretch: True
                keep_ratio: False
    StencilView:
        id: stencil2
        Scatter:
            pos: stencil2.pos
            size: my_image2.size
            Image:
                id: my_image2
                size: stencil2.width, stencil2.height
                source: 'flower.jpg'
                allow_stretch: True
                keep_ratio: False

Sorry if my english isn't clear


问:
Anyone has created c#.NET application to login into SAML 2.0 SSO configured salesforce org from Windows server 2012 with ADFS 2.0
I have configured Salesforce (SAML 2.0 based) SSO with ADFS 2.0 in windows server 2012 R2. I want to create a c#.NET desktop application in which user should be automatically login into Salesforce org (via his domain credentials) and fetch some org's standard object metadata.

I have googled for it and found 2 separate solutions:

1. Configure SSO in Salesforce with ADFS 2.0

2. .NET utility to login with domain (ADFS 2.0) credentials.

But I am not able to find combined solution of the same. If anybody has any idea on this or has implemented such setup (SAML based SSO in Salesforce with ADFS 2.0 & c#.NET utility to auto login to Salesforce org through domain credentials), then please share your knowledge.

Thanks in advance.

答:
ADFS 2.0 supports WS-Fed and SAML 2.0.

It sounds like you have federated ADFS and Salesforce.

So with an ASP MVC application (i.e. browser based) that uses e.g. WIF to connect to ADFS, you could connect because these protocols are all browser based.

For WS-Fed, this is called the passive profile.

You cannot use the passive profile for a desktop application as it has no browser support.

You need to use the active profile which is based on WCF and is supported by ADFS.


问:
Qt, cmake and qhelpgenerator
Is there any automatism in cmake to run qhelpgenerator and get out of it the compressed manual to be included in the executable?

cmake already takes care of a lot of things. As an example, resources files (.qrc) are gracefully handled by adding them to the list of source files of a project. The same applies for the moc generated by qmoc and so on.

I was wondering if there exists something similar to elaborate automatically .qph files. So far, I only found online projects that use custom targets to run qhelpgenerator and set dependencies between targets.

It isn't a problem for itself, I want only to know if there exists a nicer way to do it. That's all.

答:
(Turning comment into answer)

The upcoming CMake 3.9 release has upgraded support for doxygen. It will provide a new doxygen_add_docs() function which makes running doxygen trivial and doxygen has direct support for running qhelpgenerator and friends. You just need to set a few doxygen-specific variables like DOXYGEN_GENERATE_QHP and then call that function (prefix each of doxygen's variables with DOXYGEN_ to set them in CMake). The function takes care of setting up all the custom target gadgetry.

Title: Qt, cmake and qhelpgenerator


问:
Scala: Why is an abstract type member equal to a type parameter by =:= not equal in use?
I am starting to embrace abstract type members over type parameters - mainly because they seem to work better with type inference for me. However, I am still struggling to understand how to use them from outside of the types they are defined in. For example, I cannot understand why the following Scala program should not compile:

```<code>trait Thing

trait Describer {
  type X<:Thing
  def describe(x:X) = println(x)
}

object Program extends App {

  def print[T <: Thing, D <: Describer]
    (describer: D, thing:T)
    (implicit ev: D#X =:= T)
    = describer.describe(thing)

}
</code>```

Intuitively, I would expect that the requirement D#X =:= T would guarantee that the two types are indeed equal and hence that instances of two could be used interchangeably, but I get this compilation error:

```<code>error: type mismatch;
 found   : thing.type (with underlying type T)
 required: describer.X
    = describer.describe(thing)
</code>```

What have I misunderstood? Is there another way to do what I want to do? Or failing that, is it safe to cast thing to the required type (describer.X)?

答:
The type of the parameter of describer.describe is actually describer.X and not D#X. Another thing you have to know is that A =:= B also functions as a conversion from A to B but (at least currently) not the other way around. So the following should work.

```<code>def print[T <: Thing]
  (describer: Describer, thing: T)
  (implicit ev: T =:= describer.X)
  = describer.describe(thing)
</code>```

Body:
I am starting to embrace abstract type members over type parameters - mainly because they seem to work better with type inference for me. However, I am still struggling to understand how to use them from outside of the types they are defined in. For example, I cannot understand why the following Scala program should not compile:

trait Thing

trait Describer {
  type X<:Thing
  def describe(x:X) = println(x)
}

object Program extends App {

  def print[T <: Thing, D <: Describer]
    (describer: D, thing:T)
    (implicit ev: D#X =:= T)
    = describer.describe(thing)

}

Intuitively, I would expect that the requirement D#X =:= T would guarantee that the two types are indeed equal and hence that instances of two could be used interchangeably, but I get this compilation error:

error: type mismatch;
 found   : thing.type (with underlying type T)
 required: describer.X
    = describer.describe(thing)

What have I misunderstood? Is there another way to do what I want to do? Or failing that, is it safe to cast thing to the required type (describer.X)?

Body:
The type of the parameter of describer.describe is actually describer.X and not D#X. Another thing you have to know is that A =:= B also functions as a conversion from A to B but (at least currently) not the other way around. So the following should work.

def print[T <: Thing]
  (describer: Describer, thing: T)
  (implicit ev: T =:= describer.X)
  = describer.describe(thing)


问:
Can I bind python-2.7's `print` in python-3.x, allowing me to use `print` without parenthesis in python-3.x?
I like python 2's print "TEXT" which does not use without parenthesis, compared to print("TEXT") in python 3.

Can I keep the python 2 print around to use by binding it to something like pr?

I understand has been discussed in this thread, but this wasn't mentioned as one of the solutions:
Python 3 print without parenthesis

(By the way, the issue for me is typing and escaping the brackets. The keys ( and ) harder to press than a space bar. Also, because my IDE puts them in automatically, I then need to move my cursor out of it.)

EDIT: This is neither a duplicate of the question as indicated NOR am I asking how to use python-3.x's print without parenthesis. Instead, I'm specifically asking if I can bind a python 2 function (presumably after importing it). If the answer is no, that is new information.

答: In order to achieve what you want you need to define your own keyword, but you can't do this as you can't define or redefine language keywords without rewriting a compiler/interpreter/etc.</p>


问:
How to make numbers backwards in notepad++
So, I have a lot of numbers in lines like so

```<code>rocket123
firefly1000
attack577
</code>```

Is there any regex to make the numbers reversed?

```<code>rocket321
firefly0001
attack775
</code>```

答:
This is feasible with a little trick.

Step 1. Add a marker for the not-yet-inverted digits.

Find:

```<code>\b(\w+?)(\d+)\b
</code>```

Replace:

```<code>$1§$2
</code>```

You can choose other marker instead of §.

Step 2. Do Replace all enough times with these settings:

Find:

```<code>\b(\w+)§(\d*)(\d)\b
</code>```

Replace:

```<code>$1$3§$2
</code>```

Step 3. Delete all markers.

Find:

```<code>\b(\w+\d)§
</code>```

Replace:

```<code>$1
</code>```

Hope this helps.

Body:
So, I have a lot of numbers in lines like so

rocket123
firefly1000
attack577

Is there any regex to make the numbers reversed?

rocket321
firefly0001
attack775

Body:
This is feasible with a little trick.

Step 1. Add a marker for the not-yet-inverted digits.

Find:

\b(\w+?)(\d+)\b

Replace:

$1§$2

You can choose other marker instead of §.

Step 2. Do Replace all enough times with these settings:

Find:

\b(\w+)§(\d*)(\d)\b

Replace:

$1$3§$2

Step 3. Delete all markers.

Find:

\b(\w+\d)§

Replace:

$1

Hope this helps.


问:
C# How I can make a sum wih Console.Readline
The idea that I have is:

Set some variables with its numbers like int a=15, b=10, c=1

Then with the use of Console.Readline be able to do the sum, for example a+a+b wrote on the console must show 40.

I tried Console.WriteLine("sum: {0}",Console.Readline()); I could upload a image with the idea if this it's not enought sorry for my english.

答:
Basic procedure if you only wanted to do additions: split the input string and then iterate through said output while adding all the numbers together. Output will be in string format so a cast must be supplied.

Full code:

```<code>string[] tmp_out = Console.ReadLine().Split('+');
int tmp_sum = 0;
foreach (string tmp_number in tmp_out)
{
    tmp_sum += int.Parse(tmp_number); // consider using TryParse if you are not sure if the input format is correct
}
Console.WriteLine("Sum=" + tmp_sum);
</code>```

If you need further computing power, look into CSharpCorner

Body:
Basic procedure if you only wanted to do additions: split the input string and then iterate through said output while adding all the numbers together. Output will be in string format so a cast must be supplied.

Full code:

string[] tmp_out = Console.ReadLine().Split('+');
int tmp_sum = 0;
foreach (string tmp_number in tmp_out)
{
    tmp_sum += int.Parse(tmp_number); // consider using TryParse if you are not sure if the input format is correct
}
Console.WriteLine("Sum=" + tmp_sum);

If you need further computing power, look into CSharpCorner


问:
Is it possible to get duplicates in query?
i'm building user application with backend and i want to know something

datastore query use indexes to retrieve data

if a user have data in this index and in multiple entries of this index
would the query return him multiple times

say i have a user entity with a list this list is a list of multiple string representing locations like user is in location [A,AB,ABG,ABGJ,ABGJC]

if i query if a user in location A or AB

the query will return the user 2 times ?

cause it will look for all the user in location A then look for all the user in location AB and the same user is in two location A and AB

the user will return 2 times?

答:
A datastore query will never return the same entity twice.

In your case, if you are modelling a collection with a user and different locations, you have to do multiple entries of the same user with different locations, with the indexing on user and locations. This will allow you to query on it and will return multiple results as there are multiple entries. But if u add an array of locations as a field of a user and you only have one entry per user, you cannot query using a single location even if the array of locations is indexed.

Alternative is to model it in parent and child, and to use ancestor queries.


问:
ASP.Net MVC: How to associate a role with action from my custom UI
often we attach role with action like below way

```<code>[Authorize(Roles = "Admin, SuperUser")]

[Authorize(Users="Jacquo, Steve", Roles="Admin, SuperUser")]
</code>```

Users : Comma-separated list of usernames that are allowed to access the action method.

Roles : Comma-separated list of role names. To Access the action method, users must be in at least one of these roles.

```<code>[Authorize(Roles = "Producer")]
[Authorize(Roles = "Admin")]
public ActionResult Details(int id) {
    // Only available to users who are Producers AND Editors
}
</code>```

now see authorize and role name is hard coded with action method. suppose action Details is associated with admin role which is hard coded but how could i attach more role to details action or remove any role from details action at run time. i guess it is not possible because asp.net mvc not providing anything built in.

i search google to see that anyone does it anything such as what i am looking for. unfortunately found no similar write up.

so i need some guidance that how could i develop a UI from where admin can associate role with action instead of hard coding at development time.

so tell me your think how could i associate a role or multiple roles with action from a custom UI.

also tell me how could i check at run time that user has that role when user try to access a specific action.

please discuss in details for designing this part what i am looking for. still it is not clear to you what i am looking for then tell me i will try to explain the same in more details.

thanks

答:
First: in every controller you should create a user object in controller constructor. like this:

```<code>public class MyController : Controller
{
    ApplicationUser user;
    public MyController ()
    {
        user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
    }
</code>```

Then you could use user object anywhere in your controller methods.
"how could i develop a UI from where admin can associate role": in razor view use :

```<code>@if (User.IsInRole("Admin"))
                    {}
</code>```

"how could i associate a role or multiple roles with action from a custom UI":
No need to that. When you create user in controller, you have access user all roles in controller methods.
"how could i check at run time that user has that role":
Use

```<code>if(user.IsInRole("Admin"))
</code>```

Body:
often we attach role with action like below way

[Authorize(Roles = "Admin, SuperUser")]

[Authorize(Users="Jacquo, Steve", Roles="Admin, SuperUser")]

Users : Comma-separated list of usernames that are allowed to access the action method.

Roles : Comma-separated list of role names. To Access the action method, users must be in at least one of these roles.

[Authorize(Roles = "Producer")]
[Authorize(Roles = "Admin")]
public ActionResult Details(int id) {
    // Only available to users who are Producers AND Editors
}

now see authorize and role name is hard coded with action method. suppose action Details is associated with admin role which is hard coded but how could i attach more role to details action or remove any role from details action at run time. i guess it is not possible because asp.net mvc not providing anything built in.

i search google to see that anyone does it anything such as what i am looking for. unfortunately found no similar write up.

so i need some guidance that how could i develop a UI from where admin can associate role with action instead of hard coding at development time.

so tell me your think how could i associate a role or multiple roles with action from a custom UI.

also tell me how could i check at run time that user has that role when user try to access a specific action.

please discuss in details for designing this part what i am looking for. still it is not clear to you what i am looking for then tell me i will try to explain the same in more details.

thanks

Body:
First: in every controller you should create a user object in controller constructor. like this:

public class MyController : Controller
{
    ApplicationUser user;
    public MyController ()
    {
        user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
    }

Then you could use user object anywhere in your controller methods.
"how could i develop a UI from where admin can associate role": in razor view use :

@if (User.IsInRole("Admin"))
                    {}

"how could i associate a role or multiple roles with action from a custom UI":
No need to that. When you create user in controller, you have access user all roles in controller methods.
"how could i check at run time that user has that role":
Use

if(user.IsInRole("Admin"))


问:
CSS: How do I stop hover effects from pushing my text?
I hope you understood the question, you can see an example here:

http://jsfiddle.net/nFbJY/

When you scroll over any of the links they move :(

Any advice on how to solve this issue?

HTML:

```<code><div class="links">
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="pricing.html">Pricing</a></li>
<li><a href="faq.html">FAQ</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</code>```

CSS:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left; margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC;          border-radius: 5px; -moz-border-radius: 5px;}
a:hover { border: 1px solid blue; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}
```

答:
Check this one http://jsfiddle.net/huhu/Tn2HV/

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li { float:left; }
li a { margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC; border-radius: 5px; -moz-border-radius: 5px; }
li a:hover { background-color:yellow;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="links">
    <ul>
    <li>Home</li>
    <li>Pricing</li>
    <li>FAQ</li>
    <li>About</li>
    <li>Contact</li>
    </ul>
 </div></code>```

Body:
I hope you understood the question, you can see an example here:

http://jsfiddle.net/nFbJY/

When you scroll over any of the links they move :(

Any advice on how to solve this issue?

HTML:

Home

Pricing

FAQ

About

Contact

CSS:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left; margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC;          border-radius: 5px; -moz-border-radius: 5px;}
a:hover { border: 1px solid blue; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}

Body:
Check this one http://jsfiddle.net/huhu/Tn2HV/

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li { float:left; }
li a { margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC; border-radius: 5px; -moz-border-radius: 5px; }
li a:hover { background-color:yellow;}

<div class="links">
    <ul>
    <li><a href="home.html">Home</a></li>
    <li><a href="pricing.html">Pricing</a></li>
    <li><a href="faq.html">FAQ</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="contact.html">Contact</a></li>
    </ul>
 </div>


问:
java - JTextArea expands dynamically (undesired)
Something strange occured. I have a text area and a button. When I type text into the area, the button starts moving! Please see attached code. I tried adding more layers of panels and setting component alignments, but it still happens.

```<code>class MyFrame extends JFrame {
...
public MyFrame() {
    super("example");
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    add(panel);

    JTextArea _textArea = new JTextArea();
    _textArea.setSize(800, 600);
    panel.add(_textArea);

    JButton btn = new JButton("Send");
    panel.add(btn);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(1000, 800);
    setVisible(true);
    }
}
</code>```

whats the mystery all about?  how does one component affects the other?

答:
BoxLayout is a lot more complicated than BorderLayout, which is what you need. BorderLayout uses general directions like NORTH, EAST, SOUTH, and WEST, which is very simple. Here's the easy way to get what you're looking for:

```<code>class MyFrame extends JFrame {
    //...
    public MyFrame() {
        super("Example");
        JTextArea textArea = new JTextArea();
        textArea.setSize(800, 600);
        add(textArea, BorderLayout.CENTER);

        JButton btn = new JButton("Send");
        add(btn, BorderLayout.SOUTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 800);
        setVisible(true);
    }
}
</code>```

A lot shorter too.

Body:
Something strange occured. I have a text area and a button. When I type text into the area, the button starts moving! Please see attached code. I tried adding more layers of panels and setting component alignments, but it still happens.

class MyFrame extends JFrame {
...
public MyFrame() {
    super("example");
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    add(panel);

    JTextArea _textArea = new JTextArea();
    _textArea.setSize(800, 600);
    panel.add(_textArea);

    JButton btn = new JButton("Send");
    panel.add(btn);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(1000, 800);
    setVisible(true);
    }
}

whats the mystery all about?  how does one component affects the other?

Body:
BoxLayout is a lot more complicated than BorderLayout, which is what you need. BorderLayout uses general directions like NORTH, EAST, SOUTH, and WEST, which is very simple. Here's the easy way to get what you're looking for:

class MyFrame extends JFrame {
    //...
    public MyFrame() {
        super("Example");
        JTextArea textArea = new JTextArea();
        textArea.setSize(800, 600);
        add(textArea, BorderLayout.CENTER);

        JButton btn = new JButton("Send");
        add(btn, BorderLayout.SOUTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 800);
        setVisible(true);
    }
}

A lot shorter too.


答:
This line:

```<code>_textArea.setSize(800, 600);
</code>```

is ignored, because the LayoutManager of a component’s parent decides what the size will be.  In your case, that LayoutManager is your BoxLayout.

LayoutManagers determine the positions and sizes of the components they manage.  That’s their job.  They use each component’s minimum size, preferred size, and maximum size to decide the actual size.  If you want to know the exact algorithm, read BoxLayout’s documentation.

Generally, you set a JTextArea’s preferred size by setting its rows and columns:

```<code>JTextArea _textArea = new JTextArea(20, 40);
</code>```

JTextArea is designed to be placed in a JScrollPane.  If you don’t put it in a JScrollPane, it may not act as you expect, especially if the user types more text than can fit in it:

```<code>panel.add(new JScrollPane(_textArea));
</code>```

You should probably read through JTextArea’s documentation to understand it better.

Title: java - JTextArea expands dynamically (undesired)

Body:
This line:

_textArea.setSize(800, 600);

is ignored, because the LayoutManager of a component’s parent decides what the size will be.  In your case, that LayoutManager is your BoxLayout.

LayoutManagers determine the positions and sizes of the components they manage.  That’s their job.  They use each component’s minimum size, preferred size, and maximum size to decide the actual size.  If you want to know the exact algorithm, read BoxLayout’s documentation.

Generally, you set a JTextArea’s preferred size by setting its rows and columns:

JTextArea _textArea = new JTextArea(20, 40);

JTextArea is designed to be placed in a JScrollPane.  If you don’t put it in a JScrollPane, it may not act as you expect, especially if the user types more text than can fit in it:

panel.add(new JScrollPane(_textArea));

You should probably read through JTextArea’s documentation to understand it better.


问:
Json to Java List: Removing space between Objects outside the quotes
I am trying to use an online API to retrieve data.

After I get the result in JSON format I tried to convert it into a Java List, but the output I want is not coming as I desire.

Can someone help me out in this task?

答:
I am a new developer but I can suggest since you are not getting the desired output maybe you can use a stringbuilder and a buffered reader to read the JSON and turn it into a string.

I hope that helps I am not sure this is the right answer but I can only think of this.


问:
multiple promises running in parallel, $q.all needs chaining?
I have 3 parallel promises or api requests once all teh three are done, I need to call another api request based on the second promise and then finally call .then( of $q.all

Here is the code

```<code> getAllLocations() {
    //make a promise call for all here .
    var promise = [];

    ̶p̶r̶o̶m̶i̶s̶e̶.̶p̶u̶s̶h̶(̶t̶h̶i̶s̶.̶g̶e̶t̶A̶l̶l̶L̶o̶c̶a̶t̶i̶o̶n̶s̶(̶I̶d̶)̶.̶t̶h̶e̶n̶(̶
    promise.push(this.getLocations(Id).then(
        (locationsData) => {
            this.locations = locationsData;
        }));

    promise.push(this.getAllStates(Id).then(
        (resp) => {
            this.states = resp.data;
        }));

    promise.push(this.getTerritories(Id).then(
        (resp) => {
            this.utilizations = resp.data;
        }));

    $q.all(promise).then(() => {
        var nodePromise = [];
        angular.forEach(this.states, function(node) {
            var nodeId = node.Id;
            nodePromise.push(this.getNodeHealthSummary(nodeId).then(
                (resp) => {
                    node.healthStatus = resp.data.operationalStatus;
                }));
            this.$q.all(nodePromise).then(() => {
                var index = this.states.indexOf(node);
                this.states.splice(index, 1, angular.copy(node));
            });
        },this);
    }).then(() => {
        for (var i = 0; i < this.locations.length; i++) {
            //do something here with this.states
        }
        this.gridData = this.locations;
    });
}
</code>```

I need this.states updated with healthStatus property when i am in the for loop of this.locations. ( the last.then )

However , i see that this.locations for loop is done ahead before the node.healthStatus property is set on each state.

How can this be done?  Using Promises instead of $q is fine. Please let me know how can i achieve this , i have tried all in vain

答:
The inner $q.all is called in each iteration of the forEach loop, and gets as argument the array that is being populated during that forEach loop. This is obviously not right; it should be called only once, and its result should be the return value of the then callback.

So instead of this block:

```<code>$q.all(promise).then(() => {
    var nodePromise = [];
    angular.forEach(this.states, function(node) {
        var nodeId = node.Id;
        nodePromise.push(this.getNodeHealthSummary(nodeId).then(
            (resp) => {
                node.healthStatus = resp.data.operationalStatus;
            }));
        this.$q.all(nodePromise).then(() => {
            var index = this.states.indexOf(node);
            this.states.splice(index, 1, angular.copy(node));
        });
    },this);
}).then( ......
</code>```

Do this:

```<code>$q.all(promise).then(() => {
    return $q.all(this.states.map((node, index) => {
        return this.getNodeHealthSummary(node.Id).then(resp => {
            node.healthStatus = resp.data.operationalStatus;
            this.states[index] = angular.copy(node);
        });
    }));
}).then( ......
</code>```

Body:
I have 3 parallel promises or api requests once all teh three are done, I need to call another api request based on the second promise and then finally call .then( of $q.all

Here is the code

 getAllLocations() {
    //make a promise call for all here .
    var promise = [];

    ̶p̶r̶o̶m̶i̶s̶e̶.̶p̶u̶s̶h̶(̶t̶h̶i̶s̶.̶g̶e̶t̶A̶l̶l̶L̶o̶c̶a̶t̶i̶o̶n̶s̶(̶I̶d̶)̶.̶t̶h̶e̶n̶(̶
    promise.push(this.getLocations(Id).then(
        (locationsData) => {
            this.locations = locationsData;
        }));

    promise.push(this.getAllStates(Id).then(
        (resp) => {
            this.states = resp.data;
        }));

    promise.push(this.getTerritories(Id).then(
        (resp) => {
            this.utilizations = resp.data;
        }));

    $q.all(promise).then(() => {
        var nodePromise = [];
        angular.forEach(this.states, function(node) {
            var nodeId = node.Id;
            nodePromise.push(this.getNodeHealthSummary(nodeId).then(
                (resp) => {
                    node.healthStatus = resp.data.operationalStatus;
                }));
            this.$q.all(nodePromise).then(() => {
                var index = this.states.indexOf(node);
                this.states.splice(index, 1, angular.copy(node));
            });
        },this);
    }).then(() => {
        for (var i = 0; i < this.locations.length; i++) {
            //do something here with this.states
        }
        this.gridData = this.locations;
    });
}

I need this.states updated with healthStatus property when i am in the for loop of this.locations. ( the last.then )

However , i see that this.locations for loop is done ahead before the node.healthStatus property is set on each state.

How can this be done?  Using Promises instead of $q is fine. Please let me know how can i achieve this , i have tried all in vain

Body:
The inner $q.all is called in each iteration of the forEach loop, and gets as argument the array that is being populated during that forEach loop. This is obviously not right; it should be called only once, and its result should be the return value of the then callback.

So instead of this block:

$q.all(promise).then(() => {
    var nodePromise = [];
    angular.forEach(this.states, function(node) {
        var nodeId = node.Id;
        nodePromise.push(this.getNodeHealthSummary(nodeId).then(
            (resp) => {
                node.healthStatus = resp.data.operationalStatus;
            }));
        this.$q.all(nodePromise).then(() => {
            var index = this.states.indexOf(node);
            this.states.splice(index, 1, angular.copy(node));
        });
    },this);
}).then( ......

Do this:

$q.all(promise).then(() => {
    return $q.all(this.states.map((node, index) => {
        return this.getNodeHealthSummary(node.Id).then(resp => {
            node.healthStatus = resp.data.operationalStatus;
            this.states[index] = angular.copy(node);
        });
    }));
}).then( ......