问:
deduplicate messages whil reading from kafka
Kafka log compaction is not working for me.
I used the following code to create the topic : </p>

```<code>bin/kafka-topics.sh --create --zookeeper z-3.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181,z-1.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181,z-2.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181  --topic  finals  --replication-factor 1  --partitions 1   --config cleanup.policy=compact   --config min.cleanable.dirty.ratio=0.001  --config segment.ms=5000
</code>```

<p>It keeps reading the records having the same key. </p>

答:
Kafka's log compaction feature is used for cleanup data in the partition, not for deduplication. Let say you insert into the partition A with the following order:

```<code>[head] (key1, value1) (key2, value2) (key1, value3) [ tail]
</code>```

After compaction phrase at some future point, the partition will be:

```<code>[head] (key2, value2) (key1, value3) [tail]
</code>```

Before the compaction phrase happens, any consumer consumes the partition A will see 2 records with the same key key1. This mechanism extremely useful for replicate the database (e.g.: MySQL) to some different datastores.

For deduplication, we must know the real reason for duplication to have the correct fix.

If that because of multiple inserts with the same key, you must use a separate mechanism for deduplication. You might deduplicate at the source (before writing to Kafka'topics) or sink ( when consuming messages from the topics). That strongly depends on concreted problems. As @criket_007 pointed out, a key-value datastore (e.g.: Redis, Memcache) is a good start for deduplication.

If the duplication because of the network error. For instance, you insert (key1, value1) into the topic. After brokers received and wrote successfully data to the disk, brokers return the result back to the client. However, the network error happens so clients cannot see the result. Clients think that they haven't delivered yet so they deliver for the second time. Duplication happens. Here is the illustration for this scenario.

So you should use Idempotent producer

Body:
Kafka log compaction is not working for me.
I used the following code to create the topic :

bin/kafka-topics.sh --create --zookeeper z-3.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181,z-1.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181,z-2.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181  --topic  finals  --replication-factor 1  --partitions 1   --config cleanup.policy=compact   --config min.cleanable.dirty.ratio=0.001  --config segment.ms=5000

It keeps reading the records having the same key.

Body:
Kafka's log compaction feature is used for cleanup data in the partition, not for deduplication. Let say you insert into the partition A with the following order:

[head] (key1, value1) (key2, value2) (key1, value3) [ tail]

After compaction phrase at some future point, the partition will be:

[head] (key2, value2) (key1, value3) [tail]

Before the compaction phrase happens, any consumer consumes the partition A will see 2 records with the same key key1. This mechanism extremely useful for replicate the database (e.g.: MySQL) to some different datastores.

For deduplication, we must know the real reason for duplication to have the correct fix.

If that because of multiple inserts with the same key, you must use a separate mechanism for deduplication. You might deduplicate at the source (before writing to Kafka'topics) or sink ( when consuming messages from the topics). That strongly depends on concreted problems. As @criket_007 pointed out, a key-value datastore (e.g.: Redis, Memcache) is a good start for deduplication.

If the duplication because of the network error. For instance, you insert (key1, value1) into the topic. After brokers received and wrote successfully data to the disk, brokers return the result back to the client. However, the network error happens so clients cannot see the result. Clients think that they haven't delivered yet so they deliver for the second time. Duplication happens. Here is the illustration for this scenario.

So you should use Idempotent producer


来源: stackexchange

问:
Scaling nodejs app while assigning unique ports
I'm trying to scale my game servers (nodejs) where instances should have unique ports assigned to them and where instances are separate (no load balancing of any kind) and are aware what port is assigned to them (ideally by env variable?).
I've tried using docker swarm but it has no option to specify port range and I couldn't find any way to allocate or to pass the allocated port to the instance so it's aware of the port its running on e.g via env variable.

Ideal solution would look like:

```<code>Instance 1: hostIP:1000
Instance 2: hostIP:1001
Instance 3: hostIP:1002
... etc
</code>```

Now, I've managed to make this work by using regular Docker (non-swarm) by binding to host network and passing env variable PORT, but this way I'd have to manually spin up as many game servers as I'd need.

My node app uses "process.env.PORT" to bind to host's IP address:port

Any opinion on what solutions I could use to scale my app?

答: Not To Sure What You Mean There? Could You Provide More Detail?</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to scale my game servers (nodejs) where instances should have unique ports assigned to them and where instances are separate (no load balancing of any kind) and are aware what port is assigned to them (ideally by env variable?).
I've tried using docker swarm but it has no option to specify port range and I couldn't find any way to allocate or to pass the allocated port to the instance so it's aware of the port its running on e.g via env variable.

Ideal solution would look like:

Instance 1: hostIP:1000
Instance 2: hostIP:1001
Instance 3: hostIP:1002
... etc

Now, I've managed to make this work by using regular Docker (non-swarm) by binding to host network and passing env variable PORT, but this way I'd have to manually spin up as many game servers as I'd need.

My node app uses "process.env.PORT" to bind to host's IP address:port

Any opinion on what solutions I could use to scale my app?


问:
my webpage gets rendered multiple times when i submit once with post method to python flask
```<code>@app.response("/process" , methods=['POST'])
def process():
    return render_template('index.html')
</code>```

please find the solution for my issue here am using python flask and html

答:
From what you have given, this is the only solution I can think of. If this is not what you were looking for feel free to ask questions, thanks!</p>

```<code>from Flask import request

@app.response("/process" , methods=['POST'])
def process():
    if (request.method == "POST"):
        <enter code here>
    else:
        return render_template('index.html')
</code>```

Body:
@app.response("/process" , methods=['POST'])
def process():
    return render_template('index.html')

please find the solution for my issue here am using python flask and html

Body:
From what you have given, this is the only solution I can think of. If this is not what you were looking for feel free to ask questions, thanks!

from Flask import request

@app.response("/process" , methods=['POST'])
def process():
    if (request.method == "POST"):
        <enter code here>
    else:
        return render_template('index.html')


问:
alternative to Google maps
My client wants some of the functionality of Google maps namely:
- geocoding
- generating maps with points based on postal code or long.lat
- optimal trip mapping

Their issues with Google maps
- cannot control outages
- postal codes are sometimes inaccurate or not updated frequently for Canada/UK
- they have no way to correct inaccurate information

They would prefer to host the mapping application themselves, but will require postal code updates.

Can anyone suggest such a product?

thanks

答:
I think you're looking for something like Caliper-It's a very custom, and I would expect expensive, solution.  Not suggested.

http://www.caliper.com/GISMappingSoftwareDevelopment.htm

One solution could be to use two different mapping services and compare their results, this way there's a much better chance the data is accurate. You can also fix inaccurate data by creating a system which acts as a barrier between the API and your user, where data you know is inaccurate is corrected before it's displayed.  Not sure exactly what you're doing though, so this might not work for you.

Is trip mapping/routing the basic functionality you want to do?

ContentLicense: CC BY-SA 3.0

Title: alternative to Google maps


问:
Extract a string of words between multiple specific words in R
I have a long string that includes one or multiple keywords, "Realm" in this case. I have been using gsub, but that only takes the words after the last of the keywords.

so the string could look like:

...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...

or

...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome...

I have been using the function:

```<code>Realm_fun<-function(x){gsub('^.*Realm -\\s*|\\s*IUCN Ecosystem.*$', '', x)}
</code>```

then using lapply to fun it on all of the strings.

what can I do to get Afrotropical for the first string and Afrotropical , Neotropical for the second?

答:
You can try this:

```<code>stringi::stri_extract_last(st, regex='(?<=Realm - )(\\w+)')
</code>```

stri_extract_last will pull the last match for the regex, using a look behind assertions we can collect word followed by look arounds(using positive look behind in this case), in this case you are having words Afrotropical and Neotropical followed by Realm - .

In case if you want to extract both strings for last match, you can try below(stri_extract_all):

```<code>stringi::stri_extract_all(st, regex='(?<=Realm - )(\\w+)')
</code>```

Input:

```<code>st <- c("...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...",
"...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome..."
)
</code>```

Output:

```<code>> stringi::stri_extract_last(st, regex='(?<=Realm - )(\\w+)')
[1] "Afrotropical" "Neotropical"

> stringi::stri_extract_all(st, regex='(?<=Realm - )(\\w+)')
[[1]]
[1] "Afrotropical"

[[2]]
[1] "Afrotropical" "Neotropical"
</code>```

Body:
I have a long string that includes one or multiple keywords, "Realm" in this case. I have been using gsub, but that only takes the words after the last of the keywords.

so the string could look like:

...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...

or

...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome...

I have been using the function:

Realm_fun<-function(x){gsub('^.*Realm -\\s*|\\s*IUCN Ecosystem.*$', '', x)}

then using lapply to fun it on all of the strings.

what can I do to get Afrotropical for the first string and Afrotropical , Neotropical for the second?

Body:
You can try this:

stringi::stri_extract_last(st, regex='(?<=Realm - )(\\w+)')

stri_extract_last will pull the last match for the regex, using a look behind assertions we can collect word followed by look arounds(using positive look behind in this case), in this case you are having words Afrotropical and Neotropical followed by Realm - .

In case if you want to extract both strings for last match, you can try below(stri_extract_all):

stringi::stri_extract_all(st, regex='(?<=Realm - )(\\w+)')

Input:

st <- c("...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...",
"...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome..."
)

Output:

> stringi::stri_extract_last(st, regex='(?<=Realm - )(\\w+)')
[1] "Afrotropical" "Neotropical"

> stringi::stri_extract_all(st, regex='(?<=Realm - )(\\w+)')
[[1]]
[1] "Afrotropical"

[[2]]
[1] "Afrotropical" "Neotropical"


问:
Angular project did not run
I am trying to run my angular project using 'ng serve' command.

but project did not run more errors in my terminal. please check attached screen and give me the solution.

thanks

答:
Try installing node-sass</p>

```<code>sudo npm install --save-dev  --unsafe-perm node-sass
</code>```

Title: Angular project did not run

Body:
Try installing node-sass

sudo npm install --save-dev  --unsafe-perm node-sass


问:
How to configure a WCF service with a default base address?
When I launch my WCF service from visual studio, it opens up a browser window with a page that contains the below and the address is http://localhost:65535

```<code>HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
</code>```

How can I make it display the page with the complete svc URL? I tried to add the below to service in web.config and it does not make any difference. What else needs to be changed?

Thanks for any advice.

```<code><host>
  <baseAddresses>
    <add baseAddress="http://localhost:65535/TestService.svc"/>
  </baseAddresses>
</host>
</code>```

答:
By default, the base address of the website lists the content of the WCF project instead of the service base address, which can directly be consumed. In order to list it, please configure the section.

```<code><directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>
</code>```

For hosting WCF service in IIS, It is necessary to handle the SVC extension file separately. Thereby .SVC file is included in the service base address.
We should enable the below windows feature,

And access the below address(replace it with the actual svc file name)

http://localhost:65535/Service1.svc

Hosting WCF service in IIS.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-host-a-wcf-service-in-iis

https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-3.5/ms752252(v=vs.90)

Feel free to let me know if the problem still exists.

Body:
When I launch my WCF service from visual studio, it opens up a browser window with a page that contains the below and the address is http://localhost:65535

HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.

How can I make it display the page with the complete svc URL? I tried to add the below to service in web.config and it does not make any difference. What else needs to be changed?

Thanks for any advice.

<host>
  <baseAddresses>
    <add baseAddress="http://localhost:65535/TestService.svc"/>
  </baseAddresses>
</host>

Body:
By default, the base address of the website lists the content of the WCF project instead of the service base address, which can directly be consumed. In order to list it, please configure the section.

<directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

For hosting WCF service in IIS, It is necessary to handle the SVC extension file separately. Thereby .SVC file is included in the service base address.
We should enable the below windows feature,

And access the below address(replace it with the actual svc file name)

http://localhost:65535/Service1.svc

Hosting WCF service in IIS.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-host-a-wcf-service-in-iis

https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-3.5/ms752252(v=vs.90)

Feel free to let me know if the problem still exists.


问:
How to pass ID from url to controller in laravel
I want my view page to open when the type the url as www.domain-name.in/sample/ID. ID can be an integer valure of 5 digits. Right now my view page is opening when I type the url as www.domain-name.in/sample but when i type www.domain-name.in/sample/ID, I'm getting 404 error.
This is my route :

Route::get('/{$id}','HomeController@index');```
</div>
</div>
</p>

<p>This is my controller</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>public function index(Request $request,$id)
    {
        return view('filename');
    }</code>```

How can I get view page with this url : www.domain-name.in/sample/ID

答:
You need to use the below code:

If you defined route group in web.php then use:

```<code>Route::group(['prefix' => 'sample'], function(){
    Route::get('/{id}', 'HomeController@index')->name('home');
});
</code>```

And in the controller:

```<code>public function index(Request $request,$id)
{
    $myid = $id;
    return view('filename', compact('myid'));
}
</code>```

Body:
I want my view page to open when the type the url as www.domain-name.in/sample/ID. ID can be an integer valure of 5 digits. Right now my view page is opening when I type the url as www.domain-name.in/sample but when i type www.domain-name.in/sample/ID, I'm getting 404 error.
This is my route :

Route::get('/{$id}','HomeController@index');

This is my controller

public function index(Request $request,$id)
    {
        return view('filename');
    }

How can I get view page with this url : www.domain-name.in/sample/ID

Body:
You need to use the below code:

If you defined route group in web.php then use:

Route::group(['prefix' => 'sample'], function(){
    Route::get('/{id}', 'HomeController@index')->name('home');
});

And in the controller:

public function index(Request $request,$id)
{
    $myid = $id;
    return view('filename', compact('myid'));
}


问:
How to get jQuery Tablesorter to sort descending by default?
I can't figure this out.  This question was also asked here http://www.nabble.com/TableSorter-plugin---default-column-sort-DESC-instead--How--to25180761s27240.html#a25180761 with no response.

I've tried

```<code>    $.tablesorter.defaults.sortInitialOrder = 'desc';
</code>```

and altering the jquery.tablesorter.js file to default to 'desc' but it doesn't work.  When I click on the column headers, the first sort is still ascending so the user has to click twice to descend the values.

How can I get Tablesorter to sort by descending by default?

答:
Try the latest version from the tablesorter site - this seems to be fixed somewhere between version 2.0.3 and 2.0.5. </p>

```<code><script type="text/javascript">
$(document).ready(function()
    {
        $("#theTable").tablesorter({
            sortInitialOrder: 'desc',
            sortList: [[3,1]] // etc.

    });
    }
);
</script>
</code>```

<p>...that worked with the latest version of tablesorter, but didn't with the previous one I had. Hope it helps!</p>

ContentLicense: CC BY-SA 2.5

Body:
I can't figure this out.  This question was also asked here http://www.nabble.com/TableSorter-plugin---default-column-sort-DESC-instead--How--to25180761s27240.html#a25180761 with no response.

I've tried

    $.tablesorter.defaults.sortInitialOrder = 'desc';

and altering the jquery.tablesorter.js file to default to 'desc' but it doesn't work.  When I click on the column headers, the first sort is still ascending so the user has to click twice to descend the values.

How can I get Tablesorter to sort by descending by default?

Body:
Try the latest version from the tablesorter site - this seems to be fixed somewhere between version 2.0.3 and 2.0.5.

<script type="text/javascript">
$(document).ready(function()
    {
        $("#theTable").tablesorter({
            sortInitialOrder: 'desc',
            sortList: [[3,1]] // etc.

    });
    }
);
</script>

...that worked with the latest version of tablesorter, but didn't with the previous one I had. Hope it helps!


问:
Why is my homepage being set to a specific url instead of the usual '/'?
I'm working on this app, and while I was debugging I noticed that whenever I physically refresh the page and on the initial load of the app, the default homepage seems to be routing to the /search route. Instead, I'd like for the homepage to be set to the / route by default; any ideas as to where in the app to look for this bug/how to set the / route to be the default homepage?

Here is my app.js file with all the routes (this is the app.js file in the `frontend folder):

```<code>const App = () => (
    <div className="app-wrapper">
        <Modal />
        <NavBarContainer />

        <div className="app-main-content-wrapper">
          <Switch>
            <Route exact path="/" component={SpotIndex} />
            <Route exact path="/spots/:spotId" component={SpotDetail} />
            <Route exact path="/search" component={SearchContainer} />
          </Switch>
        </div>
    </div>
);
</code>```

Here is my app.js that's in the root directory (outside of the frontend folder):

```<code>const express = require('express');
const app = express();
const mongoose = require('mongoose');
const db = require('./config/keys').mongoURI;
const bodyParser = require('body-parser');
const passport = require('passport');
const path = require('path');
const users = require('./routes/api/users');
const spots = require('./routes/api/spots');

// Loading static build folder for production
if (process.env.NODE_ENV === 'production') {
    app.use(express.static('frontend/build'));
    app.get('/', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'));
    })
}

// Using mongoose to connect to Mongo database with success and error messages
mongoose
    .connect(db, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => console.log('Connected to MongoDB successfully'))
    .catch(err => console.log(err));

// Respond to JSON requests and requests from other software (i.e. Postman)
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Uses the right port when in development and in production
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server is running on port ${port}`));

// Requests for these routes uses the specified callback function
app.use('/api/users', users);
app.use('/api/spots', spots);

// Middleware for Passport
app.use(passport.initialize());

// Configuration file for Passport
require('./config/passport')(passport);

// Route for serving static assets
// Makes content under the public directory accessible
// i.e. In components, <img src='/images/splash.jpg' />
app.use('/images', express.static(path.join(__dirname, 'public')))
</code>```

UPDATE:
I just tried changing the home route (the / route) to:
<Route path="/" component... /> and the homepage did become the right one, but I don't think that'll work because then the SpotIndex component will always render on every other webpage.

答:
just need to refactor app.js in front-end like so :

```<code>const App = () => (
    <div className="app-wrapper">
        <Modal />
        <NavBarContainer />

        <div className="app-main-content-wrapper">
          <Switch>
            <Route exact path="/" component={SpotIndex} />
            <Route path="/spots/:spotId" component={SpotDetail} />
            <Route path="/search" component={SearchContainer} />
          </Switch>
        </div>
    </div>
);

</code>```

now your default homepage will be /

Body:
I'm working on this app, and while I was debugging I noticed that whenever I physically refresh the page and on the initial load of the app, the default homepage seems to be routing to the /search route. Instead, I'd like for the homepage to be set to the / route by default; any ideas as to where in the app to look for this bug/how to set the / route to be the default homepage?

Here is my app.js file with all the routes (this is the app.js file in the `frontend folder):

const App = () => (

        <Modal />
        <NavBarContainer />

          <Switch>
            <Route exact path="/" component={SpotIndex} />
            <Route exact path="/spots/:spotId" component={SpotDetail} />
            <Route exact path="/search" component={SearchContainer} />
          </Switch>

);

Here is my app.js that's in the root directory (outside of the frontend folder):

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const db = require('./config/keys').mongoURI;
const bodyParser = require('body-parser');
const passport = require('passport');
const path = require('path');
const users = require('./routes/api/users');
const spots = require('./routes/api/spots');

// Loading static build folder for production
if (process.env.NODE_ENV === 'production') {
    app.use(express.static('frontend/build'));
    app.get('/', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'));
    })
}

// Using mongoose to connect to Mongo database with success and error messages
mongoose
    .connect(db, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => console.log('Connected to MongoDB successfully'))
    .catch(err => console.log(err));

// Respond to JSON requests and requests from other software (i.e. Postman)
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Uses the right port when in development and in production
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server is running on port ${port}`));

// Requests for these routes uses the specified callback function
app.use('/api/users', users);
app.use('/api/spots', spots);

// Middleware for Passport
app.use(passport.initialize());

// Configuration file for Passport
require('./config/passport')(passport);

// Route for serving static assets
// Makes content under the public directory accessible
// i.e. In components,
app.use('/images', express.static(path.join(__dirname, 'public')))

UPDATE:
I just tried changing the home route (the / route) to:
<Route path="/" component... /> and the homepage did become the right one, but I don't think that'll work because then the SpotIndex component will always render on every other webpage.

Body:
just need to refactor app.js in front-end like so :

const App = () => (
    <div className="app-wrapper">
        <Modal />
        <NavBarContainer />

        <div className="app-main-content-wrapper">
          <Switch>
            <Route exact path="/" component={SpotIndex} />
            <Route path="/spots/:spotId" component={SpotDetail} />
            <Route path="/search" component={SearchContainer} />
          </Switch>
        </div>
    </div>
);

now your default homepage will be /


问:
Separating even and odd indexes from and ArrayList in Java using recursion
I'm trying to separate even and odd indexes from an ArrayList in java as part of an assignment. It must be a recursive method. Here is what I've tried;;

```<code>public ArrayList<Integer> toOddList(ArrayList<Integer> input) {
        ArrayList<Integer> copiedList = (ArrayList<Integer>) input.clone();
        ArrayList<Integer> oddList = new ArrayList<Integer>();
        ArrayList<Integer> evenList = new ArrayList<Integer>();
        int index = (copiedList.size() - 1);      // Sets index to the max size of ArrayList - 1
        if (index <= 0) {
            return oddList;
        }
        if ((index % 2) == 0) {
            evenList.add(copiedList.get(index));  // Adds indexed number to even Arraylist
            copiedList.remove(index);             // Removes index from copiedList
            copiedList = toOddList(copiedList);   // Calls function again
        } else {
            oddList.add(copiedList.get(index));   // Adds indexed number to odd Arraylist
            copiedList.remove(index);             // Removes index from copied List
            copiedList = toOddList(copiedList);   // Call method again
        } return oddList;
    }
</code>```

If there is any other way to use recursion for this, or to instead use two methods for even and odd separately, any help would be appreciated.

答:
Few optimizations we can do in your implementation. U don't even need to create final output list on every recursion call and using java Predicate class we can common out final internal method also.

Please checkout implementation.

```<code>  public ArrayList<Integer> buildOddList(ArrayList<Integer> input) {
    ArrayList<Integer> output = new ArrayList<>();
    return buildList(input,0,output,i -> i % 2 != 0 );
  }

  public ArrayList<Integer> buildEvenList(ArrayList<Integer> input) {
    ArrayList<Integer> output = new ArrayList<>();
    return buildList(input,0,output,i -> i % 2 == 0 );
  }

  private ArrayList<Integer> buildList(ArrayList<Integer> input, Integer index, ArrayList<Integer> output, Predicate<Integer> predicate) {

    if (index == input.size()) {
      return output;
    }
    if (predicate.test(index)) {
      output.add(input.get(index));
    }
    return buildList(input,index+1,output,predicate);
  }
</code>```

Body:
I'm trying to separate even and odd indexes from an ArrayList in java as part of an assignment. It must be a recursive method. Here is what I've tried;;

public ArrayList<Integer> toOddList(ArrayList<Integer> input) {
        ArrayList<Integer> copiedList = (ArrayList<Integer>) input.clone();
        ArrayList<Integer> oddList = new ArrayList<Integer>();
        ArrayList<Integer> evenList = new ArrayList<Integer>();
        int index = (copiedList.size() - 1);      // Sets index to the max size of ArrayList - 1
        if (index <= 0) {
            return oddList;
        }
        if ((index % 2) == 0) {
            evenList.add(copiedList.get(index));  // Adds indexed number to even Arraylist
            copiedList.remove(index);             // Removes index from copiedList
            copiedList = toOddList(copiedList);   // Calls function again
        } else {
            oddList.add(copiedList.get(index));   // Adds indexed number to odd Arraylist
            copiedList.remove(index);             // Removes index from copied List
            copiedList = toOddList(copiedList);   // Call method again
        } return oddList;
    }

If there is any other way to use recursion for this, or to instead use two methods for even and odd separately, any help would be appreciated.

Body:
Few optimizations we can do in your implementation. U don't even need to create final output list on every recursion call and using java Predicate class we can common out final internal method also.

Please checkout implementation.

  public ArrayList<Integer> buildOddList(ArrayList<Integer> input) {
    ArrayList<Integer> output = new ArrayList<>();
    return buildList(input,0,output,i -> i % 2 != 0 );
  }

  public ArrayList<Integer> buildEvenList(ArrayList<Integer> input) {
    ArrayList<Integer> output = new ArrayList<>();
    return buildList(input,0,output,i -> i % 2 == 0 );
  }

  private ArrayList<Integer> buildList(ArrayList<Integer> input, Integer index, ArrayList<Integer> output, Predicate<Integer> predicate) {

    if (index == input.size()) {
      return output;
    }
    if (predicate.test(index)) {
      output.add(input.get(index));
    }
    return buildList(input,index+1,output,predicate);
  }


问:
GridView in GridView UWP Height Issue
I am working with a Nested data set that needs to be displayed in a GridView and inside the main gridView has to be another gridView (or something that can lay the content out in two columns and n number of rows based on data).

The problem I face is that the height of the GridView Item is determined by the requestedHeight of the first item in the gridView.

Is there a way to make it to pick the largest? Below is a screenshot, I don't want the scrollbar instead the content needs to be layed  out as a whole:

Is there a way I can make all the elements of the size of the element that has the maximum requestedHeight so that the second gridview doesn't have a scroll

To Reproduce the Issue Below is the code:

```<code>public sealed partial class MainPage : Page, INotifyPropertyChanged
{

    private readonly string seed = "[{\"Title\":\"Heading A\",\"Description\":\"A really short description\",\"Contents\":[{\"Title\":\"Hey!\"},{\"Title\":\"Hey You\"},{\"Title\":\"Bye!\"},{\"Title\":\"Bye You\"}]},{\"Title\":\"Heading A\",\"Description\":\"A really short description\",\"Contents\":[{\"Title\":\"Foo!\"},{\"Title\":\"Foo You\"},{\"Title\":\"Bar!\"},{\"Title\":\"Bar You\"},{\"Title\":\"Hey!\"},{\"Title\":\"Hey You\"},{\"Title\":\"Bye!\"},{\"Title\":\"Bye You\"}]}]";

    public MainPage()
    {
        this.InitializeComponent();

        IEnumerable<Section> deserialized = JsonConvert.DeserializeObject<IEnumerable<Section>>(seed);
        this.Items = new ObservableCollection<Section>(deserialized);

    }

    private ObservableCollection<Section> items;

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string name) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    public ObservableCollection<Section> Items
    {
        get { return items; }
        set
        {
            items = value;
            RaisePropertyChanged(nameof(Items));
        }
    }
}
</code>```

The MainPage.xaml

```<code><Page
    x:Class="GridViewInGridView.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:GridViewInGridView"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    RequestedTheme="Dark">

    <Page.Resources>

        <DataTemplate x:Name="SecondTemplate" x:DataType="local:SubSection">
            <TextBlock Text="{x:Bind Title}"/>
        </DataTemplate>

        <DataTemplate x:Name="FirstTemplate" x:DataType="local:Section">
            <RelativePanel BorderThickness="2" BorderBrush="Cyan">
                <TextBlock x:Name="Title" Text="{x:Bind Title}" Margin="10,10,10,0"/>
                <TextBlock x:Name="Desc" Text="{x:Bind Description}" RelativePanel.Below="Title" TextWrapping="WrapWholeWords"
                           Margin="10"/>

                <GridView RelativePanel.Below="Desc"
                          Margin="20, 10"
                          RelativePanel.AlignLeftWithPanel="True"
                          RelativePanel.AlignRightWithPanel="True"
                          RelativePanel.AlignBottomWithPanel="True"
                          ItemsSource="{x:Bind Contents}"
                          ItemTemplate="{StaticResource SecondTemplate}">
                    <GridView.ItemContainerStyle>
                        <Style TargetType="GridViewItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                            <Setter Property="VerticalContentAlignment" Value="Stretch"/>
                            <Setter Property="Padding" Value="0"/>
                            <Setter Property="Margin" Value="5,5"/>
                        </Style>
                    </GridView.ItemContainerStyle>

                    <GridView.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VariableSizedWrapGrid MaximumRowsOrColumns="2" Orientation="Horizontal"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Stretch"/>
                        </ItemsPanelTemplate>
                    </GridView.ItemsPanel>
                </GridView>

            </RelativePanel>
        </DataTemplate>
    </Page.Resources>

    <Grid>
        <GridView ItemTemplate="{StaticResource FirstTemplate}"
                  ItemsSource="{x:Bind Items, Mode=OneWay}"
                  Margin="0,10" ScrollViewer.VerticalScrollBarVisibility="Hidden" SelectionMode="Single">

            <GridView.ItemContainerStyle>
                <Style TargetType="GridViewItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                    <Setter Property="VerticalContentAlignment" Value="Stretch"/>
                    <Setter Property="Padding" Value="0"/>
                    <Setter Property="Margin" Value="20,20"/>
                </Style>
            </GridView.ItemContainerStyle>

            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsWrapGrid MaximumRowsOrColumns="3" Orientation="Horizontal"
                                       HorizontalAlignment="Center"
                                       VerticalAlignment="Stretch"/>
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>

        </GridView>
    </Grid>
</Page>
</code>```

The Model Classes:

```<code>public class Section
{
    public string Title { get; set; }

    public string Description { get; set; }

    public IEnumerable<SubSection> Contents { get; set; }

}

public class SubSection
{
    public string Title { get; set; }

}
</code>```

答:
As you said, the height of the GridView Item is determined by the requestedHeight of the first item in the gridView. In that case, you could create a custom panel for the GridView's ItemPanel. For example:

```<code>public class GridViewCustomPanel : Panel
{
    private double maxWidth;
    private double maxHeight;

    protected override Size ArrangeOverride(Size finalSize)
    {
        var x = 0.0;
        var y = 0.0;
        foreach (var child in Children)
        {
            if ((maxWidth + x) > finalSize.Width)
            {
                x = 0;
                y += maxHeight;
            }
            var newpos = new Rect(x, y, maxWidth, maxHeight);
            child.Arrange(newpos);
            x += maxWidth;
        }
        return finalSize;
    }

    protected override Size MeasureOverride(Size availableSize)
    {
        foreach (var child in Children)
        {
            child.Measure(availableSize);

            var desirtedwidth = child.DesiredSize.Width;
            if (desirtedwidth > maxWidth)
                maxWidth = desirtedwidth;

            var desiredheight = child.DesiredSize.Height;
            if (desiredheight > maxHeight)
                maxHeight = desiredheight;
        }
        var itemperrow = Math.Floor(availableSize.Width / maxWidth);
        var rows = Math.Ceiling(Children.Count / itemperrow);
        return new Size(itemperrow * maxWidth, maxHeight * rows);
    }
}
</code>```

Then you can replace the ItemsPanelTemplate of GridView with your custom panel.

.xaml:

```<code>......
<GridView.ItemsPanel>
    <ItemsPanelTemplate>
        <!--<ItemsWrapGrid MaximumRowsOrColumns="3" Orientation="Horizontal"
                           HorizontalAlignment="Center"
                           VerticalAlignment="Stretch"/>-->
        <local:GridViewCustomPanel />
    </ItemsPanelTemplate>
</GridView.ItemsPanel>
......
</code>```

About how to custom a panel, you can refer to this document.

Title: GridView in GridView UWP Height Issue

Body:
I am working with a Nested data set that needs to be displayed in a GridView and inside the main gridView has to be another gridView (or something that can lay the content out in two columns and n number of rows based on data).

The problem I face is that the height of the GridView Item is determined by the requestedHeight of the first item in the gridView.

Is there a way to make it to pick the largest? Below is a screenshot, I don't want the scrollbar instead the content needs to be layed  out as a whole:

Is there a way I can make all the elements of the size of the element that has the maximum requestedHeight so that the second gridview doesn't have a scroll

To Reproduce the Issue Below is the code:

public sealed partial class MainPage : Page, INotifyPropertyChanged
{

    private readonly string seed = "[{\"Title\":\"Heading A\",\"Description\":\"A really short description\",\"Contents\":[{\"Title\":\"Hey!\"},{\"Title\":\"Hey You\"},{\"Title\":\"Bye!\"},{\"Title\":\"Bye You\"}]},{\"Title\":\"Heading A\",\"Description\":\"A really short description\",\"Contents\":[{\"Title\":\"Foo!\"},{\"Title\":\"Foo You\"},{\"Title\":\"Bar!\"},{\"Title\":\"Bar You\"},{\"Title\":\"Hey!\"},{\"Title\":\"Hey You\"},{\"Title\":\"Bye!\"},{\"Title\":\"Bye You\"}]}]";

    public MainPage()
    {
        this.InitializeComponent();

        IEnumerable
 deserialized = JsonConvert.DeserializeObject<IEnumerable
>(seed);
        this.Items = new ObservableCollection
(deserialized);

    }

    private ObservableCollection
 items;

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string name) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    public ObservableCollection
 Items
    {
        get { return items; }
        set
        {
            items = value;
            RaisePropertyChanged(nameof(Items));
        }
    }
}

The MainPage.xaml

<Page
    x:Class="GridViewInGridView.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:GridViewInGridView"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    RequestedTheme="Dark">

    <Page.Resources>

        <DataTemplate x:Name="SecondTemplate" x:DataType="local:SubSection">
            <TextBlock Text="{x:Bind Title}"/>
        </DataTemplate>

        <DataTemplate x:Name="FirstTemplate" x:DataType="local:Section">
            <RelativePanel BorderThickness="2" BorderBrush="Cyan">
                <TextBlock x:Name="Title" Text="{x:Bind Title}" Margin="10,10,10,0"/>
                <TextBlock x:Name="Desc" Text="{x:Bind Description}" RelativePanel.Below="Title" TextWrapping="WrapWholeWords"
                           Margin="10"/>

                <GridView RelativePanel.Below="Desc"
                          Margin="20, 10"
                          RelativePanel.AlignLeftWithPanel="True"
                          RelativePanel.AlignRightWithPanel="True"
                          RelativePanel.AlignBottomWithPanel="True"
                          ItemsSource="{x:Bind Contents}"
                          ItemTemplate="{StaticResource SecondTemplate}">
                    <GridView.ItemContainerStyle>

                    </GridView.ItemContainerStyle>

                    <GridView.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VariableSizedWrapGrid MaximumRowsOrColumns="2" Orientation="Horizontal"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Stretch"/>
                        </ItemsPanelTemplate>
                    </GridView.ItemsPanel>
                </GridView>

            </RelativePanel>
        </DataTemplate>
    </Page.Resources>

    <Grid>
        <GridView ItemTemplate="{StaticResource FirstTemplate}"
                  ItemsSource="{x:Bind Items, Mode=OneWay}"
                  Margin="0,10" ScrollViewer.VerticalScrollBarVisibility="Hidden" SelectionMode="Single">

            <GridView.ItemContainerStyle>

            </GridView.ItemContainerStyle>

            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsWrapGrid MaximumRowsOrColumns="3" Orientation="Horizontal"
                                       HorizontalAlignment="Center"
                                       VerticalAlignment="Stretch"/>
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>

        </GridView>
    </Grid>
</Page>

The Model Classes:

public class Section
{
    public string Title { get; set; }

    public string Description { get; set; }

    public IEnumerable<SubSection> Contents { get; set; }

}

public class SubSection
{
    public string Title { get; set; }

}

Body:
As you said, the height of the GridView Item is determined by the requestedHeight of the first item in the gridView. In that case, you could create a custom panel for the GridView's ItemPanel. For example:

public class GridViewCustomPanel : Panel
{
    private double maxWidth;
    private double maxHeight;

    protected override Size ArrangeOverride(Size finalSize)
    {
        var x = 0.0;
        var y = 0.0;
        foreach (var child in Children)
        {
            if ((maxWidth + x) > finalSize.Width)
            {
                x = 0;
                y += maxHeight;
            }
            var newpos = new Rect(x, y, maxWidth, maxHeight);
            child.Arrange(newpos);
            x += maxWidth;
        }
        return finalSize;
    }

    protected override Size MeasureOverride(Size availableSize)
    {
        foreach (var child in Children)
        {
            child.Measure(availableSize);

            var desirtedwidth = child.DesiredSize.Width;
            if (desirtedwidth > maxWidth)
                maxWidth = desirtedwidth;

            var desiredheight = child.DesiredSize.Height;
            if (desiredheight > maxHeight)
                maxHeight = desiredheight;
        }
        var itemperrow = Math.Floor(availableSize.Width / maxWidth);
        var rows = Math.Ceiling(Children.Count / itemperrow);
        return new Size(itemperrow * maxWidth, maxHeight * rows);
    }
}

Then you can replace the ItemsPanelTemplate of GridView with your custom panel.

.xaml:

......
<GridView.ItemsPanel>
    <ItemsPanelTemplate>
        <!--<ItemsWrapGrid MaximumRowsOrColumns="3" Orientation="Horizontal"
                           HorizontalAlignment="Center"
                           VerticalAlignment="Stretch"/>-->
        <local:GridViewCustomPanel />
    </ItemsPanelTemplate>
</GridView.ItemsPanel>
......

About how to custom a panel, you can refer to this document.


问:
Color specific treeview items based on object property
I have an object SampleTypeRepresentation which has a boolean property "IsNew".  Given the below treeview, how do I color SampleTypeRepresentation objects that are IsNew = true?

Thanks for any help on this.  I know I need to implement some kind of style trigger, but I've found the resources online to be a bit confusing and haven't had any luck so far.

```<code>        <TreeView x:Name="tvSTR" ItemsSource="{Binding SampleTypeRepresentations}" Height="445"
                  SelectedItemChanged="tvSTR_SelectedItemChanged" MouseDoubleClick="tvSTR_DoubleClick">
        <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:SampleTypeRepresentations}" ItemsSource="{Binding Path=SampleTypeRepresentation}">
                    <TextBlock Text="{Binding Name}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <HierarchicalDataTemplate DataType="{x:Type local:SampleTypeRepresentation}" ItemsSource="{Binding Path=ChildSampleTypeRepresentations.SampleTypeRepresentation}">
                            <TextBlock Text="{Binding Name}"/>
                        </HierarchicalDataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>
</code>```

Here are the classes this block of code references.  This is a part of a rather large hierarchical data structure, but I think this should give you an idea of what's going on.

```<code>[XmlRoot(ElementName = "SampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class SampleTypeRepresentations
{
    [XmlElement(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public List<SampleTypeRepresentation> SampleTypeRepresentation { get; set; }
    [XmlAttribute(AttributeName = "ID")]
    public string ID { get; set; }
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "ReportingGroup")]
    public string ReportingGroup { get; set; }
}

[XmlRoot(ElementName = "ChildSampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class ChildSampleTypeRepresentations : INotifyPropertyChanged
{
    private ObservableCollection<SampleTypeRepresentation> sampleTypeRepresentation;

    [XmlElement(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public ObservableCollection<SampleTypeRepresentation> SampleTypeRepresentation { get => sampleTypeRepresentation;
        set
        {
            sampleTypeRepresentation = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

[XmlRoot(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class SampleTypeRepresentation : INotifyPropertyChanged
{
    //Controls highlighting in UI
    [XmlIgnore]
    public bool IsNew = false;

    private ChildSampleTypeRepresentations childSampleTypeRepresentations;
    private string name;

    [XmlElement(ElementName = "Name", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public string Name { get => name;
        set
        {
            if (name == value)
            {
                return;
            }

            name = value;
            NotifyPropertyChanged();
        }
     }

    [XmlElement(ElementName = "SampleTypeInfo", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public SampleTypeInfo SampleTypeInfo { get; set; }
    [XmlElement(ElementName = "ChildSampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public ChildSampleTypeRepresentations ChildSampleTypeRepresentations
    {
        get => childSampleTypeRepresentations;
        set
        {
            if (childSampleTypeRepresentations == value)
            {
                return;
            }

            childSampleTypeRepresentations = value;
            NotifyPropertyChanged();
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

答:
I adjusted the sample to a slightly less crowded one (removed attributes etc). Here is whats wrong with your HierarchicalDataTemplate:

```<code><HierarchicalDataTemplate DataType="{x:Type local:Manufacturer}" ItemsSource="{Binding Path=Models}">
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} <from: {1}>">
                <Binding Path="Name" />
                <Binding Path="HeadQuarters" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</HierarchicalDataTemplate>

<HierarchicalDataTemplate DataType="{x:Type local:Model}" ItemsSource="{Binding Path=Variants}">
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} costs {1}">
                <Binding Path="Name" />
                <Binding Path="Price" />
            </MultiBinding>
        </TextBlock.Text>
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsNew}" Value="true">
                        <Setter Property="Foreground" Value="Green"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</HierarchicalDataTemplate>

<DataTemplate DataType="{x:Type local:Variant}">
    <TextBlock Text="{Binding Name}"/>
</DataTemplate>
</code>```

Don't know why your Hierarchy is contained in one another.

For clarity sake here's is my Model:

```<code>public class Manufacturer
    {
        public string Name { get; set; }
        public string HeadQuarters { get; set; }
        public List<Model> Models { get; set; }
    }

    public class Model
    {
        public string Name { get; set; }
        public string Price { get; set; }
        public bool IsNew { get; set; }
        public List<Variant> Variants { get; set; }
    }

    public class Variant
    {
        public string Name { get; set; }
        public string FuelType { get; set; }
    }
</code>```

This is the output - Note that RAV4 is marked with IsNew = true and so its color is Green as defined in Trigger

Body:
I have an object SampleTypeRepresentation which has a boolean property "IsNew".  Given the below treeview, how do I color SampleTypeRepresentation objects that are IsNew = true?

Thanks for any help on this.  I know I need to implement some kind of style trigger, but I've found the resources online to be a bit confusing and haven't had any luck so far.

        <TreeView x:Name="tvSTR" ItemsSource="{Binding SampleTypeRepresentations}" Height="445"
                  SelectedItemChanged="tvSTR_SelectedItemChanged" MouseDoubleClick="tvSTR_DoubleClick">
        <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:SampleTypeRepresentations}" ItemsSource="{Binding Path=SampleTypeRepresentation}">
                    <TextBlock Text="{Binding Name}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <HierarchicalDataTemplate DataType="{x:Type local:SampleTypeRepresentation}" ItemsSource="{Binding Path=ChildSampleTypeRepresentations.SampleTypeRepresentation}">
                            <TextBlock Text="{Binding Name}"/>
                        </HierarchicalDataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>

Here are the classes this block of code references.  This is a part of a rather large hierarchical data structure, but I think this should give you an idea of what's going on.

[XmlRoot(ElementName = "SampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class SampleTypeRepresentations
{
    [XmlElement(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public List<SampleTypeRepresentation> SampleTypeRepresentation { get; set; }
    [XmlAttribute(AttributeName = "ID")]
    public string ID { get; set; }
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "ReportingGroup")]
    public string ReportingGroup { get; set; }
}

[XmlRoot(ElementName = "ChildSampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class ChildSampleTypeRepresentations : INotifyPropertyChanged
{
    private ObservableCollection<SampleTypeRepresentation> sampleTypeRepresentation;

    [XmlElement(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public ObservableCollection<SampleTypeRepresentation> SampleTypeRepresentation { get => sampleTypeRepresentation;
        set
        {
            sampleTypeRepresentation = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

[XmlRoot(ElementName = "SampleTypeRepresentation", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
public class SampleTypeRepresentation : INotifyPropertyChanged
{
    //Controls highlighting in UI
    [XmlIgnore]
    public bool IsNew = false;

    private ChildSampleTypeRepresentations childSampleTypeRepresentations;
    private string name;

    [XmlElement(ElementName = "Name", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public string Name { get => name;
        set
        {
            if (name == value)
            {
                return;
            }

            name = value;
            NotifyPropertyChanged();
        }
     }

    [XmlElement(ElementName = "SampleTypeInfo", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public SampleTypeInfo SampleTypeInfo { get; set; }
    [XmlElement(ElementName = "ChildSampleTypeRepresentations", Namespace = "http://www.hilllaboratories.com/ns/clientrequestoptions")]
    public ChildSampleTypeRepresentations ChildSampleTypeRepresentations
    {
        get => childSampleTypeRepresentations;
        set
        {
            if (childSampleTypeRepresentations == value)
            {
                return;
            }

            childSampleTypeRepresentations = value;
            NotifyPropertyChanged();
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Body:
I adjusted the sample to a slightly less crowded one (removed attributes etc). Here is whats wrong with your HierarchicalDataTemplate:

<HierarchicalDataTemplate DataType="{x:Type local:Manufacturer}" ItemsSource="{Binding Path=Models}">
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} &lt;from: {1}&gt;">
                <Binding Path="Name" />
                <Binding Path="HeadQuarters" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</HierarchicalDataTemplate>

<HierarchicalDataTemplate DataType="{x:Type local:Model}" ItemsSource="{Binding Path=Variants}">
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} costs {1}">
                <Binding Path="Name" />
                <Binding Path="Price" />
            </MultiBinding>
        </TextBlock.Text>
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsNew}" Value="true">
                        <Setter Property="Foreground" Value="Green"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
</HierarchicalDataTemplate>

<DataTemplate DataType="{x:Type local:Variant}">
    <TextBlock Text="{Binding Name}"/>
</DataTemplate>

Don't know why your Hierarchy is contained in one another.

For clarity sake here's is my Model:

public class Manufacturer
    {
        public string Name { get; set; }
        public string HeadQuarters { get; set; }
        public List<Model> Models { get; set; }
    }

    public class Model
    {
        public string Name { get; set; }
        public string Price { get; set; }
        public bool IsNew { get; set; }
        public List<Variant> Variants { get; set; }
    }

    public class Variant
    {
        public string Name { get; set; }
        public string FuelType { get; set; }
    }

This is the output - Note that RAV4 is marked with IsNew = true and so its color is Green as defined in Trigger


问:
How to mask string after first character
Let's say I have a string that consists of a person's name:

```<code>var name = "Jason, Bruno Mars";
</code>```

How do I mask the string with X for the name behind the comma and returns:

```<code>var name = "Jason, BXXXX MXXX";
</code>```

I have tried using the following methods but only front characters are masked:

```<code>string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}
</code>```

Anyone has a better idea of how can I achieve the same result in a more efficient way?

答:
Try This</p>

```<code> private string ReturnMaskedName(string name)
        {
            string temporary = "";
            var newname = (name.Split(new string[] { "," }, StringSplitOptions.None)[1].Trim().Split(new String[] { " " }, StringSplitOptions.None));

            foreach (string allnames in newname)
            {
                temporary = temporary + " " + allnames[0].ToString() + new string('X', allnames.Length - 1);
            }
            return name.Split(new string[] { " " }, StringSplitOptions.None)[0] + " " + temporary;
        }
</code>```

Body:
Let's say I have a string that consists of a person's name:

var name = "Jason, Bruno Mars";

How do I mask the string with X for the name behind the comma and returns:

var name = "Jason, BXXXX MXXX";

I have tried using the following methods but only front characters are masked:

string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}

Anyone has a better idea of how can I achieve the same result in a more efficient way?

Body:
Try This

 private string ReturnMaskedName(string name)
        {
            string temporary = "";
            var newname = (name.Split(new string[] { "," }, StringSplitOptions.None)[1].Trim().Split(new String[] { " " }, StringSplitOptions.None));

            foreach (string allnames in newname)
            {
                temporary = temporary + " " + allnames[0].ToString() + new string('X', allnames.Length - 1);
            }
            return name.Split(new string[] { " " }, StringSplitOptions.None)[0] + " " + temporary;
        }


答:
Please try installing below package

```<code>npm install -g mirror-config-china --registry=http://registry.npm.taobao.org
</code>```

OR try below one if the above doesn't work.

```<code>npm install node-sass
</code>```

Title: Angular project did not run

Body:
I am trying to run my angular project using 'ng serve' command.

but project did not run more errors in my terminal. please check attached screen and give me the solution.

thanks

Body:
Please try installing below package

npm install -g mirror-config-china --registry=http://registry.npm.taobao.org

OR try below one if the above doesn't work.

npm install node-sass


问:
for loop in jinja, flask
I have a function which select the matching data from data set and return it as dict. Function is given below.

```<code>def Return_details(movie_name):
    t = movie_details.loc[movie_details['title'].str.contains(movie_name), 'title']
    imdb = movie_details.loc[movie_details['title'].str.contains(movie_name), 'imdb_score']
    g = movie_details.loc[movie_details['title'].str.contains(movie_name), 'genre']
    y = movie_details.loc[movie_details['title'].str.contains(movie_name), 'year']
    p = movie_details.loc[movie_details['title'].str.contains(movie_name), 'poster']
    try:
        title = t.iat[0]
        imdb_score = imdb.iat[0]
        genre = g.iat[0]
        year = y.iat[0]
        link = p.iat[0]
    except IndexError:
        return{'None':'None'}
    else:
        return {'title':movie_name},{'poster':link},{'imdb_score':imdb_score},{'genre':genre},{'year':year}return movie_name,link,imdb_score,genre,year
</code>```

And in the flask app I have create a list which accept this dict and place it inside a list. here is the code for list

```<code>    list_contains_details = []
    for i in predict:
        list_contains_details.extend(Return_details(i))
        print(list_contains_details)

    return render_template('index.html',data = list_contains_details)
</code>```

inside index.html

```<code><!DOCTYPE html>
<html >
<body>
<div>
    {% for i in data %}
        <p>{{  i.title }} </p><br>
    {% endfor %}
</div>
</body>
</html>
</code>```

The problem is, it is only printing title which is present at last of the list and rest of the title is not printing. I have also tried with the static list but it is not working, here is the code for it.

```<code>    data = [{'title':'toy story', 'year':'2018', 'title':'Jumanji','year':'2019'}]
    return render_template('data.html',data=data)
</code>```

data.html

```<code><!DOCTYPE html>
<html >
<body>
<div>
    {% for i in data %}
        <p>{{  i.title }} </p><br>
    {% endfor %}
</div>
</body>
</html>
</code>```

答: From what I see, at the point you are defining your "data" variable. The items in data should be separated, data = [{'title':'toy story', 'year':'2018'}, {'title':'Jumanji','year':'2019'}]. Hope this helps!</p>

Title: for loop in jinja, flask

Body:
I have a function which select the matching data from data set and return it as dict. Function is given below.

def Return_details(movie_name):
    t = movie_details.loc[movie_details['title'].str.contains(movie_name), 'title']
    imdb = movie_details.loc[movie_details['title'].str.contains(movie_name), 'imdb_score']
    g = movie_details.loc[movie_details['title'].str.contains(movie_name), 'genre']
    y = movie_details.loc[movie_details['title'].str.contains(movie_name), 'year']
    p = movie_details.loc[movie_details['title'].str.contains(movie_name), 'poster']
    try:
        title = t.iat[0]
        imdb_score = imdb.iat[0]
        genre = g.iat[0]
        year = y.iat[0]
        link = p.iat[0]
    except IndexError:
        return{'None':'None'}
    else:
        return {'title':movie_name},{'poster':link},{'imdb_score':imdb_score},{'genre':genre},{'year':year}return movie_name,link,imdb_score,genre,year

And in the flask app I have create a list which accept this dict and place it inside a list. here is the code for list

    list_contains_details = []
    for i in predict:
        list_contains_details.extend(Return_details(i))
        print(list_contains_details)

    return render_template('index.html',data = list_contains_details)

inside index.html

<!DOCTYPE html>

    {% for i in data %}

{{  i.title }}

    {% endfor %}

The problem is, it is only printing title which is present at last of the list and rest of the title is not printing. I have also tried with the static list but it is not working, here is the code for it.

    data = [{'title':'toy story', 'year':'2018', 'title':'Jumanji','year':'2019'}]
    return render_template('data.html',data=data)

data.html

<!DOCTYPE html>

    {% for i in data %}

{{  i.title }}

    {% endfor %}


问:
in the angulardart tutorial, you can't find information on how to get data from a more complex json than in the example
in the angulardart tutorial, you can't find information on how to get data from a more complex json than in the example
link to the tutorial

json in brauser django rest framework

```<code>Content-Type: application/vnd.api+json
Vary: Accept

{
    "data": [
        {
            "type": "Hero",
            "id": "1",
            "**attributes**": {
                "name": "Windstorm"
            }
        },
        {
            "type": "Hero",
            "id": "2",
            "**attributes**": {
                "name": "Bombasto"
            }
        },
        {
            "type": "Hero",
            "id": "3",
            "**attributes**": {
                "name": "Magneta"
            }
        },
        {
            "type": "Hero",
            "id": "4",
            "**attributes**": {
                "name": "Tornado"
            }
        }
    ]
}
</code>```

hero.dart
//if you don't mind, use the tutorial example to show how to output data

```<code>  class Hero {
  final int id;
  String name;

  Hero(this.id, this.name);

  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['name']);

  Map toJson() => {'id': id, 'name': name};
  }

  int _toInt(id) => id is int ? id : int.parse(id);
</code>```

hero_service.dart

```<code>  import 'dart:async';
  import 'dart:convert';

  import 'package:http/http.dart';

  import 'hero.dart';

  class HeroService {
  static final _headers = {'Content-Type': 'application/json'};
  static const _heroesUrl = 'http://127.0.0.1:8000/heroes'; // источник получения данных
  final Client _http;

  HeroService(this._http);

  Future<List<Hero>> getAll() async {
    try {
      final response = await _http.get(_heroesUrl);
      final heroes = (_extractData(response) as List)
          .map((value) => Hero.fromJson(value))
          .toList();
      return heroes;
    } catch (e) {
      throw _handleError(e);
    }
  }

  Future<Hero> create(String name) async {
    try {
      final response = await _http.post(_heroesUrl,
          headers: _headers, body: json.encode({'name': name}));
      return Hero.fromJson(_extractData(response));
    } catch (e) {
      throw _handleError(e);
    }
  }

  dynamic _extractData(Response resp) => json.decode(resp.body)['data'];

  Exception _handleError(dynamic e) {
    print(e); // for demo purposes only
    return Exception('Server error; cause: $e');
   }
  }
</code>```

I don't get errors when working, he just can't get through to the characters...

答:
Your "name" is down a level in the sample json inside of the **attributes** object .. so it would be:

```<code>class Hero {
  final int id;
  String name;

  Hero(this.id, this.name);

  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['**attributes**']['name']);

  Map toJson() => {'id': id, 'name': name};
  }

  int _toInt(id) => id is int ? id : int.parse(id);
</code>```

It's important to not that any level of complexity of JSON can be represented in Dart through parent/child relationships of Map and/or List after being decoded.

Body:
in the angulardart tutorial, you can't find information on how to get data from a more complex json than in the example
link to the tutorial

json in brauser django rest framework

Content-Type: application/vnd.api+json
Vary: Accept

{
    "data": [
        {
            "type": "Hero",
            "id": "1",
            "**attributes**": {
                "name": "Windstorm"
            }
        },
        {
            "type": "Hero",
            "id": "2",
            "**attributes**": {
                "name": "Bombasto"
            }
        },
        {
            "type": "Hero",
            "id": "3",
            "**attributes**": {
                "name": "Magneta"
            }
        },
        {
            "type": "Hero",
            "id": "4",
            "**attributes**": {
                "name": "Tornado"
            }
        }
    ]
}

hero.dart
//if you don't mind, use the tutorial example to show how to output data

  class Hero {
  final int id;
  String name;

  Hero(this.id, this.name);

  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['name']);

  Map toJson() => {'id': id, 'name': name};
  }

  int _toInt(id) => id is int ? id : int.parse(id);

hero_service.dart

  import 'dart:async';
  import 'dart:convert';

  import 'package:http/http.dart';

  import 'hero.dart';

  class HeroService {
  static final _headers = {'Content-Type': 'application/json'};
  static const _heroesUrl = 'http://127.0.0.1:8000/heroes'; // источник получения данных
  final Client _http;

  HeroService(this._http);

  Future<List<Hero>> getAll() async {
    try {
      final response = await _http.get(_heroesUrl);
      final heroes = (_extractData(response) as List)
          .map((value) => Hero.fromJson(value))
          .toList();
      return heroes;
    } catch (e) {
      throw _handleError(e);
    }
  }

  Future<Hero> create(String name) async {
    try {
      final response = await _http.post(_heroesUrl,
          headers: _headers, body: json.encode({'name': name}));
      return Hero.fromJson(_extractData(response));
    } catch (e) {
      throw _handleError(e);
    }
  }

  dynamic _extractData(Response resp) => json.decode(resp.body)['data'];

  Exception _handleError(dynamic e) {
    print(e); // for demo purposes only
    return Exception('Server error; cause: $e');
   }
  }

I don't get errors when working, he just can't get through to the characters...

Body:
Your "name" is down a level in the sample json inside of the **attributes** object .. so it would be:

class Hero {
  final int id;
  String name;

  Hero(this.id, this.name);

  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['**attributes**']['name']);

  Map toJson() => {'id': id, 'name': name};
  }

  int _toInt(id) => id is int ? id : int.parse(id);

It's important to not that any level of complexity of JSON can be represented in Dart through parent/child relationships of Map and/or List after being decoded.


问:
Do you believe the Firefox project should be forked into a developer targeted version?
I've just got this idea that there is a need for a forked version of Firefox that would provide right out of the box tools for web development. Like FireBug, YSlow, FireCookie, LiveHTTPHeaders, etc.

Maybe the fork should only include those extensions or take a further step and implement them in existing chrome.

The reason I'm thinking about this is that right now I have two Firefox profiles. A "browsing" one which has only one extension and a "development" one which has lots and lots of extensions. The advantage is obviously that the former is faster than the latter. Maybe if aimed from the beginning at developers, a forked version would bring some speed improvements and other niceties.

What do you think? Any volunteers?

答:
I think it is unnecessary to fork for that, because you can both things already - that is, have multiple profiles, and have all the developer tools as extensions.

You could even install two different profiles and run them from two different executables (portable Firefox makes this easy) allowing you to have a completely different plugin set as well as extension set for both.

OwnerDisplayName: Ionut G. Stan

OwnerDisplayName: thomasrutter