问:
AngularJS filter tree structure recursively by property
I tried multiple things now, but didn't had much success. Let's assume, that I have a list like this:

```<code>[
    {
        "name": "Africa",
        "translation": "Afrika",
        "someNum": 87207,
        "countries": [
            {
                "name": "Algeria",
                "translation": "Algerien",
                "someNum": 58020,
                "countries": null
            },
            {
                "name": "Morocco",
                "translation": "Marokko",
                "someNum": 27314,
                "countries": null
            },
            {
                "name": "Libya",
                "translation": "Lybien",
                "someNum": 77788,
                "countries": null
            },
            {
                "name": "Somalia",
                "translation": "Somalia",
                "someNum": 17945,
                "countries": null
            },
            {
                "name": "Kenya",
                "translation": "Kenia",
                "someNum": 12505,
                "countries": null
            },
            {
                "name": "Mauritania",
                "translation": "Mauretanien",
                "someNum": 25787,
                "countries": null
            },
            {
                "name": "South Africa",
                "translation": "S\u00fcdafrika",
                "someNum": 39997,
                "countries": null
            }
        ]
    },
    {
        "name": "America",
        "translation": "Amerika",
        "someNum": 48450,
        "countries": [
            {
                "name": "North America",
                "translation": "Nordamerika",
                "someNum": 23397,
                "countries": [
                    {
                        "name": "Canada",
                        "translation": "Kanada",
                        "someNum": 58709,
                        "countries": null
                    },
                    {
                        "name": "USA",
                        "translation": "USA",
                        "someNum": 64725,
                        "countries": [
                            {
                                "name": "New York",
                                "translation": "New York",
                                "someNum": 50202,
                                "countries": null
                            },
                            {
                                "name": "California",
                                "translation": "Kalifornien",
                                "someNum": 92801,
                                "countries": [
                                    {
                                        "name": "Los Angeles",
                                        "translation": "Los Angeles",
                                        "someNum": 78283,
                                        "countries": null
                                    },
                                    {
                                        "name": "San Diego",
                                        "translation": "San Diego",
                                        "someNum": 30373,
                                        "countries": null
                                    },
                                    {
                                        "name": "Sacramento",
                                        "translation": "Sacramento",
                                        "someNum": 50721,
                                        "countries": null
                                    },
                                    {
                                        "name": "San Francisco",
                                        "translation": "San Francisco",
                                        "someNum": 65772,
                                        "countries": null
                                    },
                                    {
                                        "name": "Bakersville",
                                        "translation": "Bakersville",
                                        "someNum": 20390,
                                        "countries": null
                                    }
                                ]
                            },
                            {
                                "name": "Lousiana",
                                "translation": "Lousiana",
                                "someNum": 26245,
                                "countries": null
                            },
                            {
                                "name": "Texas",
                                "translation": "Texas",
                                "someNum": 57720,
                                "countries": null
                            },
                            {
                                "name": "Nevada",
                                "translation": "Nevada",
                                "someNum": 41399,
                                "countries": null
                            },
                            {
                                "name": "Montana",
                                "translation": "Montana",
                                "someNum": 97221,
                                "countries": null
                            },
                            {
                                "name": "Virginia",
                                "translation": "Virginia",
                                "someNum": 64101,
                                "countries": null
                            }
                        ]
                    }
                ]
            },
            {
                "name": "Middle America",
                "translation": "Mittelamerika",
                "someNum": 60813,
                "countries": [
                    {
                        "name": "Mexico",
                        "translation": "Mexiko",
                        "someNum": 97953,
                        "countries": null
                    },
                    {
                        "name": "Honduras",
                        "translation": "Honduras",
                        "someNum": 40591,
                        "countries": null
                    },
                    {
                        "name": "Guatemala",
                        "translation": "Guatemala",
                        "someNum": 41592,
                        "countries": null
                    }
                ]
            },
            {
                "name": "South America",
                "translation": "S\u00fcdamerika",
                "someNum": 61507,
                "countries": null
            }
        ]
    },
    {
        "name": "Asia",
        "translation": "Asien",
        "someNum": 38179,
        "countries": [
            {
                "name": "China",
                "translation": "China",
                "someNum": 47266
            },
            {
                "name": "India",
                "translation": "Indien",
                "someNum": 33424,
                "countries": null
            },
            {
                "name": "Malaysia",
                "translation": "Malaysia",
                "someNum": 38010,
                "countries": null
            },
            {
                "name": "Thailand",
                "translation": "Thailand",
                "someNum": 41356,
                "countries": null
            },
            {
                "name": "Vietnam",
                "translation": "Vietnam",
                "someNum": 79489,
                "countries": null
            },
            {
                "name": "Singapore",
                "translation": "Singapur",
                "someNum": 53176,
                "countries": null
            },
            {
                "name": "Indonesia",
                "translation": "Indonesien",
                "someNum": 89895,
                "countries": null
            },
            {
                "name": "Mongolia",
                "translation": "Mongolei",
                "someNum": 42783,
                "countries": null
            }
        ]
    },
    {
        "name": "Europe",
        "translation": "Europa",
        "someNum": 84723,
        "countries": [
            {
                "name": "North",
                "translation": "Nord",
                "someNum": 16833,
                "countries": [
                    {
                        "name": "Norway",
                        "translation": "Norwegen",
                        "someNum": 11817,
                        "countries": null
                    },
                    {
                        "name": "Sweden",
                        "translation": "Schweden",
                        "someNum": 38210,
                        "countries": null
                    },
                    {
                        "name": "Finland",
                        "translation": "Finnland",
                        "someNum": 10669,
                        "countries": null
                    }
                ]
            },
            {
                "name": "East",
                "translation": "Ost",
                "someNum": 28434,
                "countries": [
                    {
                        "name": "Romania",
                        "translation": "Rum\u00e4nien",
                        "someNum": 45122,
                        "countries": null
                    },
                    {
                        "name": "Bulgaria",
                        "translation": "Bulgarien",
                        "countries": null
                    },
                    {
                        "name": "Poland",
                        "translation": "Polen",
                        "someNum": 84183,
                        "countries": null
                    }
                ]
            },
            {
                "name": "South",
                "translation": "S\u00fcd",
                "someNum": 71856,
                "countries": [
                    {
                        "name": "Italy",
                        "translation": "Italien",
                        "someNum": 76406,
                        "countries": null
                    },
                    {
                        "name": "Greece",
                        "translation": "Griechenland",
                        "someNum": 18189,
                        "countries": null
                    },
                    {
                        "name": "Spain",
                        "translation": "Spanien",
                        "someNum": 36148,
                        "countries": null
                    }
                ]
            },
            {
                "name": "West",
                "translation": "West",
                "someNum": 33487,
                "countries": [
                    {
                        "name": "France",
                        "translation": "Frankreich",
                        "someNum": 72622,
                        "countries": null
                    },
                    {
                        "name": "England",
                        "translation": "England",
                        "someNum": 51927,
                        "countries": null
                    },
                    {
                        "name": "Portugal",
                        "translation": "Portugal",
                        "someNum": 25502,
                        "countries": null
                    }
                ]
            }
        ]
    },
    {
        "name": "Oceania",
        "translation": "Ozeanien",
        "someNum": 69844,
        "countries": [
            {
                "name": "Australia",
                "translation": "Australien",
                "someNum": 17211,
                "countries": null
            },
            {
                "name": "New Zealand",
                "translation": "Neuseeland",
                "someNum": 87401,
                "countries": null
            }
        ]
    },
    {
        "name": "Arctica",
        "translation": "Arktis",
        "someNum": 67183,
        "countries": null
    },
    {
        "name": "Antarctica",
        "translation": "Antarktis",
        "someNum": 92518,
        "countries": null
    }
]
</code>```

What I try to achieve, is to find all parents and/or children, matching my search criteria while keeping the whole tree intact.

Let's say I am searching for Australia as value of the property name. The expected result would be:

```<code>- Oceania
-- Australia
</code>```

But what I get is

```<code>- Oceania
-- Australia
-- New Zealand
</code>```

Another example: I am searching for Kalifornien as value of the property translation. The expected result would be:

```<code>- America
-- North America
--- USA
---- California
----- Bakersville
----- San Diego
----- Sacramento
----- San Francisco
----- Los Angeles
</code>```

But the actual result is absolutely not, what you'd expect.

So the main problem I am experiencing is, that the original Angular filter doesn't process children correctly.

I have set up a Plunker to demonstrate the problem: https://plnkr.co/edit/3FavpC8XB3hTvT94fZli?p=preview

I can also change the format of the JSON data, if that makes it easier to achieve a proper filtering.

EDIT:

I've had partial success: https://plnkr.co/edit/lDoUK3?p=preview

There's just one problem left. If I search (for example) for California, the objects from the countries property of the object with the name California are missing. So the last item is California (which is good so far), but I also need Bakersville, San Diego & co. under it.

答:
If you want to get the subItems of your selected element in the list, you should add the items whose parent (Or some parent-of-parent) must appear in the list after filtering. To do this, I would recommend you to create a recursive function:

```<code>this.getSelectedElementList = function(list, element) {
  var result;
  for (var i in list) {
    if (list[i].name.toLowerCase().indexOf(element) > -1) {
      return list[i];
    } else {
      if (list[i].countries && list[i].countries.length) {
        result = this.getSelectedElementList(list[i].countries, element);
        if (typeof result !== 'undefined') {
          return result;
        }
      }
    }
  }
  return result;
};
</code>```

And you can call it inside your preFilter function twice. The first time to get the parent object:

```<code>var parentList = _self.getSelectedElementList(_self.listItems, _self.filterQuery.toLowerCase());
</code>```

And the second one to check that the current item is inside that object:

```<code>if (typeof parentList !== 'undefined' && parentList.countries && parentList.countries.length && typeof _self.getSelectedElementList(parentList.countries, item.name.toLowerCase()) !== 'undefined') {
  path.push(item);
}
</code>```

As you are currently filtering only by name, my proposal works this way. I have also updated your Plunkr

Body:
I tried multiple things now, but didn't had much success. Let's assume, that I have a list like this:

[
    {
        "name": "Africa",
        "translation": "Afrika",
        "someNum": 87207,
        "countries": [
            {
                "name": "Algeria",
                "translation": "Algerien",
                "someNum": 58020,
                "countries": null
            },
            {
                "name": "Morocco",
                "translation": "Marokko",
                "someNum": 27314,
                "countries": null
            },
            {
                "name": "Libya",
                "translation": "Lybien",
                "someNum": 77788,
                "countries": null
            },
            {
                "name": "Somalia",
                "translation": "Somalia",
                "someNum": 17945,
                "countries": null
            },
            {
                "name": "Kenya",
                "translation": "Kenia",
                "someNum": 12505,
                "countries": null
            },
            {
                "name": "Mauritania",
                "translation": "Mauretanien",
                "someNum": 25787,
                "countries": null
            },
            {
                "name": "South Africa",
                "translation": "S\u00fcdafrika",
                "someNum": 39997,
                "countries": null
            }
        ]
    },
    {
        "name": "America",
        "translation": "Amerika",
        "someNum": 48450,
        "countries": [
            {
                "name": "North America",
                "translation": "Nordamerika",
                "someNum": 23397,
                "countries": [
                    {
                        "name": "Canada",
                        "translation": "Kanada",
                        "someNum": 58709,
                        "countries": null
                    },
                    {
                        "name": "USA",
                        "translation": "USA",
                        "someNum": 64725,
                        "countries": [
                            {
                                "name": "New York",
                                "translation": "New York",
                                "someNum": 50202,
                                "countries": null
                            },
                            {
                                "name": "California",
                                "translation": "Kalifornien",
                                "someNum": 92801,
                                "countries": [
                                    {
                                        "name": "Los Angeles",
                                        "translation": "Los Angeles",
                                        "someNum": 78283,
                                        "countries": null
                                    },
                                    {
                                        "name": "San Diego",
                                        "translation": "San Diego",
                                        "someNum": 30373,
                                        "countries": null
                                    },
                                    {
                                        "name": "Sacramento",
                                        "translation": "Sacramento",
                                        "someNum": 50721,
                                        "countries": null
                                    },
                                    {
                                        "name": "San Francisco",
                                        "translation": "San Francisco",
                                        "someNum": 65772,
                                        "countries": null
                                    },
                                    {
                                        "name": "Bakersville",
                                        "translation": "Bakersville",
                                        "someNum": 20390,
                                        "countries": null
                                    }
                                ]
                            },
                            {
                                "name": "Lousiana",
                                "translation": "Lousiana",
                                "someNum": 26245,
                                "countries": null
                            },
                            {
                                "name": "Texas",
                                "translation": "Texas",
                                "someNum": 57720,
                                "countries": null
                            },
                            {
                                "name": "Nevada",
                                "translation": "Nevada",
                                "someNum": 41399,
                                "countries": null
                            },
                            {
                                "name": "Montana",
                                "translation": "Montana",
                                "someNum": 97221,
                                "countries": null
                            },
                            {
                                "name": "Virginia",
                                "translation": "Virginia",
                                "someNum": 64101,
                                "countries": null
                            }
                        ]
                    }
                ]
            },
            {
                "name": "Middle America",
                "translation": "Mittelamerika",
                "someNum": 60813,
                "countries": [
                    {
                        "name": "Mexico",
                        "translation": "Mexiko",
                        "someNum": 97953,
                        "countries": null
                    },
                    {
                        "name": "Honduras",
                        "translation": "Honduras",
                        "someNum": 40591,
                        "countries": null
                    },
                    {
                        "name": "Guatemala",
                        "translation": "Guatemala",
                        "someNum": 41592,
                        "countries": null
                    }
                ]
            },
            {
                "name": "South America",
                "translation": "S\u00fcdamerika",
                "someNum": 61507,
                "countries": null
            }
        ]
    },
    {
        "name": "Asia",
        "translation": "Asien",
        "someNum": 38179,
        "countries": [
            {
                "name": "China",
                "translation": "China",
                "someNum": 47266
            },
            {
                "name": "India",
                "translation": "Indien",
                "someNum": 33424,
                "countries": null
            },
            {
                "name": "Malaysia",
                "translation": "Malaysia",
                "someNum": 38010,
                "countries": null
            },
            {
                "name": "Thailand",
                "translation": "Thailand",
                "someNum": 41356,
                "countries": null
            },
            {
                "name": "Vietnam",
                "translation": "Vietnam",
                "someNum": 79489,
                "countries": null
            },
            {
                "name": "Singapore",
                "translation": "Singapur",
                "someNum": 53176,
                "countries": null
            },
            {
                "name": "Indonesia",
                "translation": "Indonesien",
                "someNum": 89895,
                "countries": null
            },
            {
                "name": "Mongolia",
                "translation": "Mongolei",
                "someNum": 42783,
                "countries": null
            }
        ]
    },
    {
        "name": "Europe",
        "translation": "Europa",
        "someNum": 84723,
        "countries": [
            {
                "name": "North",
                "translation": "Nord",
                "someNum": 16833,
                "countries": [
                    {
                        "name": "Norway",
                        "translation": "Norwegen",
                        "someNum": 11817,
                        "countries": null
                    },
                    {
                        "name": "Sweden",
                        "translation": "Schweden",
                        "someNum": 38210,
                        "countries": null
                    },
                    {
                        "name": "Finland",
                        "translation": "Finnland",
                        "someNum": 10669,
                        "countries": null
                    }
                ]
            },
            {
                "name": "East",
                "translation": "Ost",
                "someNum": 28434,
                "countries": [
                    {
                        "name": "Romania",
                        "translation": "Rum\u00e4nien",
                        "someNum": 45122,
                        "countries": null
                    },
                    {
                        "name": "Bulgaria",
                        "translation": "Bulgarien",
                        "countries": null
                    },
                    {
                        "name": "Poland",
                        "translation": "Polen",
                        "someNum": 84183,
                        "countries": null
                    }
                ]
            },
            {
                "name": "South",
                "translation": "S\u00fcd",
                "someNum": 71856,
                "countries": [
                    {
                        "name": "Italy",
                        "translation": "Italien",
                        "someNum": 76406,
                        "countries": null
                    },
                    {
                        "name": "Greece",
                        "translation": "Griechenland",
                        "someNum": 18189,
                        "countries": null
                    },
                    {
                        "name": "Spain",
                        "translation": "Spanien",
                        "someNum": 36148,
                        "countries": null
                    }
                ]
            },
            {
                "name": "West",
                "translation": "West",
                "someNum": 33487,
                "countries": [
                    {
                        "name": "France",
                        "translation": "Frankreich",
                        "someNum": 72622,
                        "countries": null
                    },
                    {
                        "name": "England",
                        "translation": "England",
                        "someNum": 51927,
                        "countries": null
                    },
                    {
                        "name": "Portugal",
                        "translation": "Portugal",
                        "someNum": 25502,
                        "countries": null
                    }
                ]
            }
        ]
    },
    {
        "name": "Oceania",
        "translation": "Ozeanien",
        "someNum": 69844,
        "countries": [
            {
                "name": "Australia",
                "translation": "Australien",
                "someNum": 17211,
                "countries": null
            },
            {
                "name": "New Zealand",
                "translation": "Neuseeland",
                "someNum": 87401,
                "countries": null
            }
        ]
    },
    {
        "name": "Arctica",
        "translation": "Arktis",
        "someNum": 67183,
        "countries": null
    },
    {
        "name": "Antarctica",
        "translation": "Antarktis",
        "someNum": 92518,
        "countries": null
    }
]

What I try to achieve, is to find all parents and/or children, matching my search criteria while keeping the whole tree intact.

Let's say I am searching for Australia as value of the property name. The expected result would be:

- Oceania
-- Australia

But what I get is

- Oceania
-- Australia
-- New Zealand

Another example: I am searching for Kalifornien as value of the property translation. The expected result would be:

- America
-- North America
--- USA
---- California
----- Bakersville
----- San Diego
----- Sacramento
----- San Francisco
----- Los Angeles

But the actual result is absolutely not, what you'd expect.

So the main problem I am experiencing is, that the original Angular filter doesn't process children correctly.

I have set up a Plunker to demonstrate the problem: https://plnkr.co/edit/3FavpC8XB3hTvT94fZli?p=preview

I can also change the format of the JSON data, if that makes it easier to achieve a proper filtering.

EDIT:

I've had partial success: https://plnkr.co/edit/lDoUK3?p=preview

There's just one problem left. If I search (for example) for California, the objects from the countries property of the object with the name California are missing. So the last item is California (which is good so far), but I also need Bakersville, San Diego & co. under it.

Body:
If you want to get the subItems of your selected element in the list, you should add the items whose parent (Or some parent-of-parent) must appear in the list after filtering. To do this, I would recommend you to create a recursive function:

this.getSelectedElementList = function(list, element) {
  var result;
  for (var i in list) {
    if (list[i].name.toLowerCase().indexOf(element) > -1) {
      return list[i];
    } else {
      if (list[i].countries && list[i].countries.length) {
        result = this.getSelectedElementList(list[i].countries, element);
        if (typeof result !== 'undefined') {
          return result;
        }
      }
    }
  }
  return result;
};

And you can call it inside your preFilter function twice. The first time to get the parent object:

var parentList = _self.getSelectedElementList(_self.listItems, _self.filterQuery.toLowerCase());

And the second one to check that the current item is inside that object:

if (typeof parentList !== 'undefined' && parentList.countries && parentList.countries.length && typeof _self.getSelectedElementList(parentList.countries, item.name.toLowerCase()) !== 'undefined') {
  path.push(item);
}

As you are currently filtering only by name, my proposal works this way. I have also updated your Plunkr


来源: stackexchange

问:
I didn't find windows form application C# in visual studio 2017
I can't find Windows form application in visual studio 2017.When I select C# and Windows, i can't find windows form application...Please help me</p>

答:
In VS 2017, workloads to be downloaded needs to explicity selected. To install win forms workload, please follow following step

Launch visual studio installer -> click modify -> Select .Net desktop development workload -> click modify

Link has exact steps

ContentLicense: CC BY-SA 3.0


问:
Can I have both Maven and Gradle installed on my machine
Just wanted to know, can I have both Maven and Gradle on my machine. I'm getting myself familiar with both the tools, I have already installed Gradle on my machine, now want to check out maven as well. Is it safe to have both on a single machine. I think both use .m2 as their local repository directory. I'm doing this for learning purposes. </p>

答:
Yes of course you can!

This is two diffrenet programs that not affect each other. It's like to install java , C# and python on the same machine, there is nothing wrong with this.

Note: if you want you can change the default local repostiory path (e.g .m2)
that maven use from the settings.xml file

Hope it was helpful


问:
asp-route-[parameter] not being added to route/url. Why?
I am building a web application for a parser. The home page is a simple razor view with basic controls, that will allow the user to add the input, and later will show the results of the parse. One of the components of this main page is a ViewComponent that returns one of the two relevant partial views for the parser's functionality: a first view that allows the user to add the input, and a result view showing the output. The decision of showing one or the other view will depend on a bool variable, "parsed", that will register whether the user has added input and parsed or not. We'll call the main page "Home", the input view "Main" and the output view "Results". If the user adds input and clicks the "Parse" button, "parsed" will be true and the Results view will load.

I have configured the logic and routes for this behaviour, and I can test it without a problem if I manually type the routes, adding the optional parameter. So, for example, all of these work properly:

localhost:1111/ -> Shows Main.

localhost:1111/?parsed=false -> Shows Main.

localhost:1111/?parsed=true -> Shows Result.

localhost:1111/parser/?parsed=false -> Shows Main, so on and so forth.

What's the problem then? When I hit the "Parse" button, I can't make the system retrieve the expected url localhost:1111/?parsed=true, obtaining instead localhost:1111/?. From this tutorial (and many more I've read) I understand that I need to use asp-route-[parameter], and that it has to match the signature of the method that is being called in asp-action, but I can't make it work.

This is the button in question:

```<code><div class="col-2">
    <form>
        <button class="button"
                asp-controller="Home" asp-action="Index"
                asp-route-parsed="true">
            Start Parsing
        </button>
    </form>
</div>
</code>```

And this is the method it calls:

```<code>    [Route("parser/{parsed:bool?}")]
    [Route("/{parsed:bool?}")]
    [Route("")]
    public ViewResult Index(bool parsed = false) {
        ViewData["Title"] = "Home";

        if (parsed == true) {
            Helper.parsed = true;
        } else {
            Helper.parsed = false;
        }

        return View("Index", Helper);
    }
</code>```

I'll really appreciate some orientation here, I've read several articles and the documentation, but can't see where the problem is. In anyone would like to take a look at the whole system, the code is available here. Thanks in advance.

答:
You don't need a form to redirect to an action. Use simple links like:

```<code><div class="col-2">
    <a class="button"
            asp-controller="Home" asp-action="Index"
            asp-route-parsed="true">
        Start Parsing
    </a>
</div>
</code>```

Also deleting all the [Route] elements from the method will generate the required link.

Body:
I am building a web application for a parser. The home page is a simple razor view with basic controls, that will allow the user to add the input, and later will show the results of the parse. One of the components of this main page is a ViewComponent that returns one of the two relevant partial views for the parser's functionality: a first view that allows the user to add the input, and a result view showing the output. The decision of showing one or the other view will depend on a bool variable, "parsed", that will register whether the user has added input and parsed or not. We'll call the main page "Home", the input view "Main" and the output view "Results". If the user adds input and clicks the "Parse" button, "parsed" will be true and the Results view will load.

I have configured the logic and routes for this behaviour, and I can test it without a problem if I manually type the routes, adding the optional parameter. So, for example, all of these work properly:

localhost:1111/ -> Shows Main.

localhost:1111/?parsed=false -> Shows Main.

localhost:1111/?parsed=true -> Shows Result.

localhost:1111/parser/?parsed=false -> Shows Main, so on and so forth.

What's the problem then? When I hit the "Parse" button, I can't make the system retrieve the expected url localhost:1111/?parsed=true, obtaining instead localhost:1111/?. From this tutorial (and many more I've read) I understand that I need to use asp-route-[parameter], and that it has to match the signature of the method that is being called in asp-action, but I can't make it work.

This is the button in question:

    <form>
        <button class="button"
                asp-controller="Home" asp-action="Index"
                asp-route-parsed="true">
            Start Parsing
        </button>
    </form>

And this is the method it calls:

    [Route("parser/{parsed:bool?}")]
    [Route("/{parsed:bool?}")]
    [Route("")]
    public ViewResult Index(bool parsed = false) {
        ViewData["Title"] = "Home";

        if (parsed == true) {
            Helper.parsed = true;
        } else {
            Helper.parsed = false;
        }

        return View("Index", Helper);
    }

I'll really appreciate some orientation here, I've read several articles and the documentation, but can't see where the problem is. In anyone would like to take a look at the whole system, the code is available here. Thanks in advance.

Body:
You don't need a form to redirect to an action. Use simple links like:

<div class="col-2">
    <a class="button"
            asp-controller="Home" asp-action="Index"
            asp-route-parsed="true">
        Start Parsing
    </a>
</div>

Also deleting all the [Route] elements from the method will generate the required link.


问:
Setting different text of a textview from an arraylist
I have a textview created programmatically in a loop. On a click of a button i want to fill each textview created with different values from the array how do i achieve this. Here is what happens when the button is clicked. Thanks for the help.

```<code>    btnPnar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            listLayout.removeAllViews();

            for (EditText et : editTextCollection)
            {
                gottenText = et.getText().toString();
                inputList.add(gottenText);
                Collections.shuffle(inputList);
            }
            // Creating alert Dialog with one Button
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,R.style.DialogeTheme);

            // Setting Dialog Title
            alertDialog.setTitle("PNAR");

            // Setting Dialog Message
            alertDialog.setMessage("Enter Amount of Numbers to Pick");
            final EditText input; input = new EditText(MainActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            input.setTextColor(Color.parseColor("#f06292"));
            input.setInputType(2);
            alertDialog.setView(input);
            alertDialog.setPositiveButton("DONE",
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    pnarGotten = Integer.parseInt(input.getText().toString());
                    Collections.shuffle(inputList);

                    for (int n =0; n<pnarGotten; n++) {

                        TextView textView = new TextView(MainActivity.this);
                        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textView.setGravity(Gravity.CENTER);
                        textView.setTextColor(Color.WHITE);
                        textView.setText(inputList.get(0));
                        textView.setText(inputList.get(1));
                        listLayout.addView(textView);

                    }
                }
            });

            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("CANCEL",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Write your code here to execute after dialog
                            dialog.cancel();
                        }
                    });
            // Showing Alert Message
            alertDialog.create();
            alertDialog.show();

        }

    });
</code>```

UPDATE
This is what i added to the code inside the for loop but it shows only one output

```<code>    for (int n =0; n<pnarGotten; n++) {

                        textViewForPnar = new TextView(MainActivity.this);
                        textViewForPnar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textViewForPnar.setGravity(Gravity.CENTER);
                        textViewForPnar.setTextColor(Color.WHITE);
                        while (iterator.hasNext())
                        {
                            textViewForPnar.setText(iterator.next());

                        }
                        listLayout.addView(textViewForPnar);

                    }
</code>```

答:
Just simply replace your for loop with this code

```<code>for (int n = 0; n < pnarGotten; n++)
{
    TextView textView = new TextView(MainActivity.this);
    textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(Color.WHITE);
    textView.setText(inputList.get(n));
    listLayout.addView(textView);
}
</code>```

Body:
I have a textview created programmatically in a loop. On a click of a button i want to fill each textview created with different values from the array how do i achieve this. Here is what happens when the button is clicked. Thanks for the help.

    btnPnar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            listLayout.removeAllViews();

            for (EditText et : editTextCollection)
            {
                gottenText = et.getText().toString();
                inputList.add(gottenText);
                Collections.shuffle(inputList);
            }
            // Creating alert Dialog with one Button
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,R.style.DialogeTheme);

            // Setting Dialog Title
            alertDialog.setTitle("PNAR");

            // Setting Dialog Message
            alertDialog.setMessage("Enter Amount of Numbers to Pick");
            final EditText input; input = new EditText(MainActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            input.setTextColor(Color.parseColor("#f06292"));
            input.setInputType(2);
            alertDialog.setView(input);
            alertDialog.setPositiveButton("DONE",
                    new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    pnarGotten = Integer.parseInt(input.getText().toString());
                    Collections.shuffle(inputList);

                    for (int n =0; n<pnarGotten; n++) {

                        TextView textView = new TextView(MainActivity.this);
                        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textView.setGravity(Gravity.CENTER);
                        textView.setTextColor(Color.WHITE);
                        textView.setText(inputList.get(0));
                        textView.setText(inputList.get(1));
                        listLayout.addView(textView);

                    }
                }
            });

            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("CANCEL",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Write your code here to execute after dialog
                            dialog.cancel();
                        }
                    });
            // Showing Alert Message
            alertDialog.create();
            alertDialog.show();

        }

    });

UPDATE
This is what i added to the code inside the for loop but it shows only one output

    for (int n =0; n<pnarGotten; n++) {

                        textViewForPnar = new TextView(MainActivity.this);
                        textViewForPnar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textViewForPnar.setGravity(Gravity.CENTER);
                        textViewForPnar.setTextColor(Color.WHITE);
                        while (iterator.hasNext())
                        {
                            textViewForPnar.setText(iterator.next());

                        }
                        listLayout.addView(textViewForPnar);

                    }

Body:
Just simply replace your for loop with this code

for (int n = 0; n < pnarGotten; n++)
{
    TextView textView = new TextView(MainActivity.this);
    textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(Color.WHITE);
    textView.setText(inputList.get(n));
    listLayout.addView(textView);
}


问:
How to create a subversion repository
I have an apache server running and working with a username and password.  I want to create a subversion project - how do I connect to the apache server in Terminal (if I have to) and create the project structure etc before configuring in Xcode?</p>

答:
You can connect to your server using SSH. The command would be:

```<code>$> ssh username@192.168.1.100
</code>```

If your server has a non-standard SSH port of 22, then you'll need to add the port number:

```<code>$> ssh -p 1234 username@192.168.1.100
</code>```

From the examples above, simply substitute 192.168.1.100 with your server's IP address. Substitute  "1234" with the SSH Port you're trying to connect to.

Finally, to create a new subversion repository, use the following:

```<code>$> sudo svnadmin create /my/svn_path/my_new_project
</code>```

At this point, I would create the directory structure:

```<code>$> mkdir /my/project_path/
$> mkdir /my/project_path/trunk
$> mkdir /my/project_path/branches
$> mkdir /my/project_path/tags
$> mkdir /my/project_path/test
$> mkdir /my/porject_path/etc
</code>```

Of'course, you don't have to follow the directory structure above.  It's just an example. But after you have your directory structure, you'll want to import it to the repository:

```<code>$> sudo svn import /my/project_path file:///my/svn_path/my_new_project -m "Initial Import of directory structure"
</code>```

Once the directory structure has been imported, you should check out a copy of the repository to your local computer/desktop, and start coding.

ContentLicense: CC BY-SA 2.5

Title: How to create a subversion repository

Body:
You can connect to your server using SSH. The command would be:

$> ssh username@192.168.1.100

If your server has a non-standard SSH port of 22, then you'll need to add the port number:

$> ssh -p 1234 username@192.168.1.100

From the examples above, simply substitute 192.168.1.100 with your server's IP address. Substitute  "1234" with the SSH Port you're trying to connect to.

Finally, to create a new subversion repository, use the following:

$> sudo svnadmin create /my/svn_path/my_new_project

At this point, I would create the directory structure:

$> mkdir /my/project_path/
$> mkdir /my/project_path/trunk
$> mkdir /my/project_path/branches
$> mkdir /my/project_path/tags
$> mkdir /my/project_path/test
$> mkdir /my/porject_path/etc

Of'course, you don't have to follow the directory structure above.  It's just an example. But after you have your directory structure, you'll want to import it to the repository:

$> sudo svn import /my/project_path file:///my/svn_path/my_new_project -m "Initial Import of directory structure"

Once the directory structure has been imported, you should check out a copy of the repository to your local computer/desktop, and start coding.


问:
Click using automation id in python
Please help !! I managed to install python 3.5.3 (32 bit) and pywinauto. I have started going through the getting started guide for pywinauto. I am using the inspect tool. I have launched the application using the code:

```<code>from pywinauto import Application
app = Application().start(r"C:\Program Files (x86)\Trane\TRACE 3D Plus\TRACE™ 3D Plus.exe").
</code>```

Now as I understood to tell python what the window is we use the:

```<code>dlg = app['TRACE™ 3D Plus']
</code>```

In this screen I have value for automation id and class name using the inspect tool. Please tell me the syntax for clicking on that button using the automation id. For example, a button on my application has the automation id "Airflows" which is seen in the inspect tool. Now how can I click on this using pywinauto?

答:
Automation id can be used with more detailed window specification (see Window Specification chapter in the Getting Started Guide). In your case it should look so:</p>

```<code>dlg = app['TRACE™ 3D Plus']
dlg.child_window(auto_id='Airflows').invoke() # or .click() that just calls an action
# or
dlg.child_window(auto_id='Airflows').click_input() # true click with moving cursor
</code>```

Title: Click using automation id in python

Body:
Please help !! I managed to install python 3.5.3 (32 bit) and pywinauto. I have started going through the getting started guide for pywinauto. I am using the inspect tool. I have launched the application using the code:

from pywinauto import Application
app = Application().start(r"C:\Program Files (x86)\Trane\TRACE 3D Plus\TRACE™ 3D Plus.exe").

Now as I understood to tell python what the window is we use the:

dlg = app['TRACE™ 3D Plus']

In this screen I have value for automation id and class name using the inspect tool. Please tell me the syntax for clicking on that button using the automation id. For example, a button on my application has the automation id "Airflows" which is seen in the inspect tool. Now how can I click on this using pywinauto?

Body:
Automation id can be used with more detailed window specification (see Window Specification chapter in the Getting Started Guide). In your case it should look so:

dlg = app['TRACE™ 3D Plus']
dlg.child_window(auto_id='Airflows').invoke() # or .click() that just calls an action
# or
dlg.child_window(auto_id='Airflows').click_input() # true click with moving cursor


问:
App Crashes when using setVisibility
As the title says,

When using startLabel.setVisibility(View.GONE);
The app Crashes and I am not sure how to fix

The Java code below.

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

private TextView  scoreLabel;
private TextView  startLabel;

private ImageView box;
private ImageView orange;
private ImageView pink;
private ImageView black;

// Position
private int boxY;
private int boxX;

// Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();

//Status Check
private boolean action_flg = false;
private boolean start_flg = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    scoreLabel = (TextView) findViewById(R.id.scoreLabel);
    scoreLabel = (TextView) findViewById(R.id.startLabel);

    box = (ImageView) findViewById(R.id.box);
    orange = (ImageView) findViewById(R.id.orange);
    pink = (ImageView) findViewById(R.id.pink);
    black = (ImageView) findViewById(R.id.black);

    //Moves images to out of the screen
    //orange.setX(-80.0f);
    orange.setY(-80.0f);

   // pink.setX(-80.0f);
    pink.setY(-80.0f);

    //black.setX(-80.0f);
    black.setY(-80.0f);

     boxY = 200;

}

public void changePos()
{

    //Move box
    if (action_flg == true)
    {
        // touching
        boxY  -= 20;
    } else {
        //released
        boxY += 20;

    }
    box.setY(boxY);
}

public boolean onTouchEvent(MotionEvent me)
{

    if (start_flg == false)
    {
        start_flg = true;

        //Issue here with setting the visibility of the start
       // startLabel.setVisibility(View.GONE);

        timer.schedule(new TimerTask()
        {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        changePos();
                    }
                });
            }

            // Changing these numbers slows down how fast the box moves.
        }, 0, 100);
    }else {
        if(me.getAction() == MotionEvent.ACTION_DOWN)
        {
            action_flg = true;
        }else if (me.getAction() == MotionEvent.ACTION_UP){
            action_flg = false;
        }

    }

    return true;
  }
}
</code>```

Here is the XML version of the code.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="me.scott.nathan.catchtheball.Main">

<TextView
    android:id="@+id/scoreLabel"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="Score : 300"
    android:textSize="18sp"
    android:paddingLeft="10dp"
    android:gravity="center_vertical">
  </TextView>

    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/startLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tap to Start"
            android:textSize="30sp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="130dp"
            />

        <ImageView
            android:id="@+id/box"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/box"
            android:layout_gravity="center_vertical"
            />

        <ImageView
         android:id="@+id/orange"
         android:layout_width="20dp"
         android:layout_height="20dp"
         android:src="@drawable/orange" />

        <ImageView
            android:id="@+id/black"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:src="@drawable/black" />

        <ImageView
            android:id="@+id/pink"
            android:layout_width="16dp"
            android:layout_height="16dp"
            android:src="@drawable/pink" />

    </FrameLayout>

<!--
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.22" />
-->

</LinearLayout>
</code>```

Anyone help appreciated to fix this issue, Thanks

答:
Your startLabel is null (copy paste problem?^^). Replace this:

```<code>scoreLabel = (TextView) findViewById(R.id.startLabel);
</code>```

with this:

```<code>startLabel = (TextView) findViewById(R.id.startLabel);
</code>```

Title: App Crashes when using setVisibility

Body:
As the title says,

When using startLabel.setVisibility(View.GONE);
The app Crashes and I am not sure how to fix

The Java code below.

public class Main extends AppCompatActivity {

private TextView  scoreLabel;
private TextView  startLabel;

private ImageView box;
private ImageView orange;
private ImageView pink;
private ImageView black;

// Position
private int boxY;
private int boxX;

// Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();

//Status Check
private boolean action_flg = false;
private boolean start_flg = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    scoreLabel = (TextView) findViewById(R.id.scoreLabel);
    scoreLabel = (TextView) findViewById(R.id.startLabel);

    box = (ImageView) findViewById(R.id.box);
    orange = (ImageView) findViewById(R.id.orange);
    pink = (ImageView) findViewById(R.id.pink);
    black = (ImageView) findViewById(R.id.black);

    //Moves images to out of the screen
    //orange.setX(-80.0f);
    orange.setY(-80.0f);

   // pink.setX(-80.0f);
    pink.setY(-80.0f);

    //black.setX(-80.0f);
    black.setY(-80.0f);

     boxY = 200;

}

public void changePos()
{

    //Move box
    if (action_flg == true)
    {
        // touching
        boxY  -= 20;
    } else {
        //released
        boxY += 20;

    }
    box.setY(boxY);
}

public boolean onTouchEvent(MotionEvent me)
{

    if (start_flg == false)
    {
        start_flg = true;

        //Issue here with setting the visibility of the start
       // startLabel.setVisibility(View.GONE);

        timer.schedule(new TimerTask()
        {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        changePos();
                    }
                });
            }

            // Changing these numbers slows down how fast the box moves.
        }, 0, 100);
    }else {
        if(me.getAction() == MotionEvent.ACTION_DOWN)
        {
            action_flg = true;
        }else if (me.getAction() == MotionEvent.ACTION_UP){
            action_flg = false;
        }

    }

    return true;
  }
}

Here is the XML version of the code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="me.scott.nathan.catchtheball.Main">

<TextView
    android:id="@+id/scoreLabel"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="Score : 300"
    android:textSize="18sp"
    android:paddingLeft="10dp"
    android:gravity="center_vertical">
  </TextView>

    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/startLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tap to Start"
            android:textSize="30sp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="130dp"
            />

        <ImageView
            android:id="@+id/box"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/box"
            android:layout_gravity="center_vertical"
            />

        <ImageView
         android:id="@+id/orange"
         android:layout_width="20dp"
         android:layout_height="20dp"
         android:src="@drawable/orange" />

        <ImageView
            android:id="@+id/black"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:src="@drawable/black" />

        <ImageView
            android:id="@+id/pink"
            android:layout_width="16dp"
            android:layout_height="16dp"
            android:src="@drawable/pink" />

    </FrameLayout>

</LinearLayout>

Anyone help appreciated to fix this issue, Thanks

Body:
Your startLabel is null (copy paste problem?^^). Replace this:

scoreLabel = (TextView) findViewById(R.id.startLabel);

with this:

startLabel = (TextView) findViewById(R.id.startLabel);


问:
Best way to link a FCM token to a device?
I'm making a server that sends messages using FCM to clients depending on what happens (temperature and/or humidity change, a door is opened, etc.).

But if the token can change, how can I keep track of the device to send messages to the correct one (w/o using a login system)?

I was thinking to link the token to the sim iccid in a database, is this correct?

答: Use device's advertising id. It won't change unless the user manually changes it. Please check the thread How to get Advertising ID in android</p>


问:
SQL Query question
No particular DBMS in mind, how would I do the following:

```<code># There are many tables per one restaurant, many napkins per one table
# Pseudo SQL

SELECT RESTAURANT WHERE ID = X;
SELECT ALL TABLES WHERE RESTAURANT_ID = RESTAURANT.ID;
SELECT ALL NAPKINS WHERE TABLE_ID = TABLE.ID;
</code>```

But, all in one query? I've used a JOIN to get all the tables in the same query as restaurant, but is it possible to get all napkins for each table as well, in the same query?

答:
It seems you want to return three separate results, not a single result with repeat values for RESTAURANT_N or TABLE_N.

In SQL, this is done with stored procedures which can return multiple result sets. The syntax for stored procedures varies among database products, therefore you should ask the question for specific products. In the stored procedure, there will be three select statements for the RESTAURANTS, TABLES and NAPKINS. The results of the three statements are returned in a bundle to the application, which can then use the results.

Title: SQL Query question

Body:
No particular DBMS in mind, how would I do the following:

# There are many tables per one restaurant, many napkins per one table
# Pseudo SQL

SELECT RESTAURANT WHERE ID = X;
SELECT ALL TABLES WHERE RESTAURANT_ID = RESTAURANT.ID;
SELECT ALL NAPKINS WHERE TABLE_ID = TABLE.ID;

But, all in one query? I've used a JOIN to get all the tables in the same query as restaurant, but is it possible to get all napkins for each table as well, in the same query?


问:
showDialog deprecated. What's the alternative?
Is there something else that should be called?

```<code>showDialog(TIME_DIALOG_ID);
</code>```

It's in this tutorial but says deprecated in Eclipse.

答:
```<code>package com.keshav.datePicker_With_Hide_Future_Past_Date;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    EditText ed_date;
    int year;
    int month;
    int day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ed_date=(EditText) findViewById(R.id.et_date);

        ed_date.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Calendar mcurrentDate=Calendar.getInstance();
                year=mcurrentDate.get(Calendar.YEAR);
                month=mcurrentDate.get(Calendar.MONTH);
                day=mcurrentDate.get(Calendar.DAY_OF_MONTH);

                final DatePickerDialog   mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
                    {
                              ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                            int month_k=selectedmonth+1;

                    }
                },year, month, day);
                mDatePicker.setTitle("Please select date");
                // TODO Hide Future Date Here
                mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

                // TODO Hide Past Date Here
                //  mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
                mDatePicker.show();
            }
        });
    }
}

// Its Working
</code>```

Body:
Is there something else that should be called?

showDialog(TIME_DIALOG_ID);

It's in this tutorial but says deprecated in Eclipse.


问:
How to sort a dataset in Apache Flink?
I have a Tuple Dataset of the form DataSet>. I wish to sort the "entire" Dataset on field String and then get only the Long values in a file. Flink does provide sort-partition but that does not help here as I need to sort the Dataset completely.</p>

答:
You can also use sortPartition() to sort the complete DataSet if you set the parallelism to 1:

```<code>DataSet<Tuple2<String, Long>> data = ...
DataSet<Tuple2<String, Long>> sorted = data
  .sortPartition(0, Order.ASCENDING).setParallelism(1); // sort in one partition
DataSet<Long> longs = sorted.map(new LongExtractor());  // map to extract long
</code>```

Title: How to sort a dataset in Apache Flink?

Body:
You can also use sortPartition() to sort the complete DataSet if you set the parallelism to 1:

DataSet<Tuple2<String, Long>> data = ...
DataSet<Tuple2<String, Long>> sorted = data
  .sortPartition(0, Order.ASCENDING).setParallelism(1); // sort in one partition
DataSet<Long> longs = sorted.map(new LongExtractor());  // map to extract long


问:
Lambda expressions, concurrency and static variables
As far as I know, such use of static  storage within lambda is legal. Essentially it counts number of entries into the closure:

```<code>#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

typedef std::pair<int,int> mypair;

std::ostream &operator<< (std::ostream &os, mypair const &data) {
    return os << "(" << data.first << ": " << data.second << ") ";
}

int main()
{
    int n;
    std::vector<mypair> v;
    std::cin >> n;
    v.reserve(n);

    std::for_each(std::begin(v), std::end(v), [](mypair& x) {
        static int i = 0;
        std::cin >> x.second;
        x.first = i++;
    });

    std::for_each(std::begin(v), std::end(v), [](mypair& x) {
        std::cout << x;
    });

    return 0;
}
</code>```

Let assume I have a container 'workers' of threads.

```<code>std::vector<std::thread> workers;
for (int i = 0; i < 5; i++) {
    workers.push_back(std::thread([]()
    {
        std::cout << "thread #" << "start\n";
        doLengthyOperation();
        std::cout << "thread #" << "finish\n";
    }));
}
</code>```

Code in doLengthyOperation() is contained and self-sufficient operation, akin a new process creation.

Provided I join them using for_each and the stored variable in question must count number of active tasks, not just number of entries, what possible implementations for such counter are there, if I want to avoid to rely onto global variables to avoid someone else messing up with it and allowing automatic support for separate "flavors" of threads.

```<code>std::for_each(workers.begin(), workers.end(), [](std::thread &t)
    {
        t.join();
    });
</code>```

Surrounding scope would die  quickly after finishing thread starts, may repeat , adding new threads to the container is possible, and that must be global variable, which I want to avoid. More of, the whole  operation is a template

答:
The best way to handle this is to capture an instance of std::atomic<int> which provides a thread safe counter. Depending on the lifetime of lambdas and the surrounding scope, you may wish to capture by reference or shared pointer.

To take your example:

```<code>std::vector<std::thread> workers;
auto counter = std::make_shared<std::atomic<int>>(0);
for (int i = 0; i < 5; i++) {
    workers.push_back(std::thread([counter]()
    {
        std::cout << "thread #" << "start\n";
        (*counter)++;
        doLengthyOperation();

        (*counter)--;
        std::cout << "thread #" << "finish\n";
    }));
}
</code>```

Body:
As far as I know, such use of static  storage within lambda is legal. Essentially it counts number of entries into the closure:

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

typedef std::pair<int,int> mypair;

std::ostream &operator<< (std::ostream &os, mypair const &data) {
    return os << "(" << data.first << ": " << data.second << ") ";
}

int main()
{
    int n;
    std::vector<mypair> v;
    std::cin >> n;
    v.reserve(n);

    std::for_each(std::begin(v), std::end(v), [](mypair& x) {
        static int i = 0;
        std::cin >> x.second;
        x.first = i++;
    });

    std::for_each(std::begin(v), std::end(v), [](mypair& x) {
        std::cout << x;
    });

    return 0;
}

Let assume I have a container 'workers' of threads.

std::vector<std::thread> workers;
for (int i = 0; i < 5; i++) {
    workers.push_back(std::thread([]()
    {
        std::cout << "thread #" << "start\n";
        doLengthyOperation();
        std::cout << "thread #" << "finish\n";
    }));
}

Code in doLengthyOperation() is contained and self-sufficient operation, akin a new process creation.

Provided I join them using for_each and the stored variable in question must count number of active tasks, not just number of entries, what possible implementations for such counter are there, if I want to avoid to rely onto global variables to avoid someone else messing up with it and allowing automatic support for separate "flavors" of threads.

std::for_each(workers.begin(), workers.end(), [](std::thread &t)
    {
        t.join();
    });

Surrounding scope would die  quickly after finishing thread starts, may repeat , adding new threads to the container is possible, and that must be global variable, which I want to avoid. More of, the whole  operation is a template

Body:
The best way to handle this is to capture an instance of std::atomic<int> which provides a thread safe counter. Depending on the lifetime of lambdas and the surrounding scope, you may wish to capture by reference or shared pointer.

To take your example:

std::vector<std::thread> workers;
auto counter = std::make_shared<std::atomic<int>>(0);
for (int i = 0; i < 5; i++) {
    workers.push_back(std::thread([counter]()
    {
        std::cout << "thread #" << "start\n";
        (*counter)++;
        doLengthyOperation();

        (*counter)--;
        std::cout << "thread #" << "finish\n";
    }));
}


问:
UWP - BackgroundTask and ContactManager
I am facing the problem that if I try to access the ContactManager from a BackgroundTask I get a System.IO.FileLoadException .

The same code works well when calling it from my main application:

```<code>    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
        test();
        deferral.Complete();

    }

    private async void test()
    {
        ContactStore contactStore = await ContactManager.RequestStoreAsync();
    }
</code>```

The BackgroundTasks starts normally, but as soon as I call "test" the exception is thrown.

答:
Ok got it...

Reason was that I switched to VS2017 while developing and got a wrong dependency in the project.json of the backgroundtask:

While the main project had:

"dependencies": {
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
  },

the background task got:

"dependencies": {
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2"
  },

after editing to 5.0.0 all went perfect

Title: UWP - BackgroundTask and ContactManager

Body:
I am facing the problem that if I try to access the ContactManager from a BackgroundTask I get a System.IO.FileLoadException .

The same code works well when calling it from my main application:

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
        test();
        deferral.Complete();

    }

    private async void test()
    {
        ContactStore contactStore = await ContactManager.RequestStoreAsync();
    }

The BackgroundTasks starts normally, but as soon as I call "test" the exception is thrown.


问:
DaoConfig init failure with greendao on Samsung Devices with Android 5.0
Crashlytics is reporting a lot of crashes in greendao:

```<code>> Caused by de.greenrobot.dao.DaoException: Could not init DAOConfig
>        at de.greenrobot.dao.internal.DaoConfig.<init>(DaoConfig.java:94)
>        at de.greenrobot.dao.AbstractDaoMaster.registerDaoClass(AbstractDaoMaster.java:44)
> ... Caused by java.lang.NoSuchFieldException: TABLENAME
>        at java.lang.Class.getField(Class.java:1104)
>        at de.greenrobot.dao.internal.DaoConfig.<init>(DaoConfig.java:56)
>        at de.greenrobot.dao.AbstractDaoMaster.registerDaoClass(AbstractDaoMaster.java:44)
</code>```

Seems to be only Samsung devices (SM-G900V, SM-900A, SM-900P, SM-870A, SCH-545 etc) all running Android 5.0 Lollipop.

From my research there seems to be a Samsung class loader implementation issue on their devices that's causing this. People mentioned the possible loader as a problem in this issue:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=8314

People have suggested adding keep rules to Proguard but we're not using Proguard at all in the application. We do have multidexing enabled though.

Anyone have suggestions for fixes or workarounds?

答:
I've encountered the same problem. I know it's the a proguard problem.

if you use the greenDao version above 3.2.0 just try the proguard-rules below

```<code>-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
    public static java.lang.String TABLENAME;
}
-keep class **$Properties`
</code>```

Body:
Crashlytics is reporting a lot of crashes in greendao:

> Caused by de.greenrobot.dao.DaoException: Could not init DAOConfig
>        at de.greenrobot.dao.internal.DaoConfig.<init>(DaoConfig.java:94)
>        at de.greenrobot.dao.AbstractDaoMaster.registerDaoClass(AbstractDaoMaster.java:44)
> ... Caused by java.lang.NoSuchFieldException: TABLENAME
>        at java.lang.Class.getField(Class.java:1104)
>        at de.greenrobot.dao.internal.DaoConfig.<init>(DaoConfig.java:56)
>        at de.greenrobot.dao.AbstractDaoMaster.registerDaoClass(AbstractDaoMaster.java:44)

Seems to be only Samsung devices (SM-G900V, SM-900A, SM-900P, SM-870A, SCH-545 etc) all running Android 5.0 Lollipop.

From my research there seems to be a Samsung class loader implementation issue on their devices that's causing this. People mentioned the possible loader as a problem in this issue:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=8314

People have suggested adding keep rules to Proguard but we're not using Proguard at all in the application. We do have multidexing enabled though.

Anyone have suggestions for fixes or workarounds?

Body:
I've encountered the same problem. I know it's the a proguard problem.

if you use the greenDao version above 3.2.0 just try the proguard-rules below

-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
    public static java.lang.String TABLENAME;
}
-keep class **$Properties`


问:
How to switch class for div using js?
I've done this using jquery, but can't do it with js.

Look at my code:

https:// jsfiddle. net/88pd6zj0/

It's working only with first class = "html", but not working with another.
I've tried change "querySelector" on "querySelectorAll" - and it's working no one class.

How to fix this problem?
Thank you.

答:
Try document.querySelectorAll()

var icon = document.querySelectorAll(".buttons div");
for(i =0;i<icon.length;i++){
icon[i].addEventListener("click", function(event){

 event.preventDefault();
 this.classList.add("active");
});
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.html, .html5, .css{
 width: 80px;
 height: 80px;
 border:1px dashed;
  display:inline;
  margin-left:10px;
}
.active{
  border:1px solid;
}</code>```

   HTML

   HTML 5

   CSS 3

```

Title: How to switch class for div using js?

Body:
Try document.querySelectorAll()

var icon = document.querySelectorAll(".buttons div");
for(i =0;i<icon.length;i++){
icon[i].addEventListener("click", function(event){

 event.preventDefault();
 this.classList.add("active");
});
}

.html, .html5, .css{
 width: 80px;
 height: 80px;
 border:1px dashed;
  display:inline;
  margin-left:10px;
}
.active{
  border:1px solid;
}

<div class="buttons">
 <div class="html ">
   <a href="#">HTML</a>
 </div>
 <div class="html5" >
   <a href="#">HTML 5</a>
 </div>
 <div class="css">
   <a href="#">CSS 3</a>
 </div>
</div>


问:
Maven release plugin fails : source artifacts getting deployed twice
We are using the maven release plugin on hudson and trying to automate the release process.
The release:prepare works fine. When we try to do the release:perform , it fails because it tries to upload a source artifact twice to the repository.

Things that I tried,

removing the profile which does include the maven source plugin from the super pom ( did not work)

specifying the goals on hudson for release as -P!attach-source release:prepare release:perform. Which I thought will exclude the source plugin from getting executed. (did not work).

tried specifying the plugin phase to some non existent phase in the super pom.(Did not work)

tried specifying the plugin configuration, forReleaseProfile as false. ( guess what?? Did not work too)

It still spits out this error.

```<code>[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [DEBUG] Checking for pre-existing User-Agent configuration.
[INFO] [DEBUG] Adding User-Agent configuration.
[INFO] [DEBUG] not adding permissions to wagon connection
[INFO] Uploading: http://xx.xx.xx.xx:8081/nexus/content/repositories/releases//com/yyy/xxx/hhh/hhh-hhh/1.9.40/hhh-hhh-1.9.40-sources.jar
[INFO] 57K uploaded  (xxx-xxx-1.9.40-sources.jar)
[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [DEBUG] Checking for pre-existing User-Agent configuration.
[INFO] [DEBUG] Adding User-Agent configuration.
[INFO] [DEBUG] not adding permissions to wagon connection
[INFO] Uploading: http://xx.xxx.xx.xx:8081/nexus/content/repositories/releases//com/xxx/xxxx/xxx/xxx-xxx/1.9.40/xxx-xxx-1.9.40-sources.jar
[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [ERROR] BUILD ERROR
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] Error deploying artifact: Authorization failed: Access denied to: http://xx.xxx.xx.xx:8081/nexus/content/repositories/releases/com/xxx/xxx/xxx/xxx-config/1.9.40/xxx-xxx-1.9.40-sources.jar
</code>```

Any help regarding this will be really appreciated.

答:
I configured the maven release plug-in with releaseProfile=false and dont execute the source artifacts profile. Which did the trick. </p>

```<code><build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-release-plugin</artifactId>
                    <version>2.1</version>
                    <configuration>
                            <arguments>-P!source-artifacts</arguments>
                            <useReleaseProfile>false</useReleaseProfile>
                            <goals>-Dmaven.test.skip=true deploy</goals>
                    </configuration>
                </plugin>
            </plugins>
        </build>
</code>```

Body:
We are using the maven release plugin on hudson and trying to automate the release process.
The release:prepare works fine. When we try to do the release:perform , it fails because it tries to upload a source artifact twice to the repository.

Things that I tried,

removing the profile which does include the maven source plugin from the super pom ( did not work)

specifying the goals on hudson for release as -P!attach-source release:prepare release:perform. Which I thought will exclude the source plugin from getting executed. (did not work).

tried specifying the plugin phase to some non existent phase in the super pom.(Did not work)

tried specifying the plugin configuration, forReleaseProfile as false. ( guess what?? Did not work too)

It still spits out this error.

[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [DEBUG] Checking for pre-existing User-Agent configuration.
[INFO] [DEBUG] Adding User-Agent configuration.
[INFO] [DEBUG] not adding permissions to wagon connection
[INFO] Uploading: http://xx.xx.xx.xx:8081/nexus/content/repositories/releases//com/yyy/xxx/hhh/hhh-hhh/1.9.40/hhh-hhh-1.9.40-sources.jar
[INFO] 57K uploaded  (xxx-xxx-1.9.40-sources.jar)
[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [DEBUG] Checking for pre-existing User-Agent configuration.
[INFO] [DEBUG] Adding User-Agent configuration.
[INFO] [DEBUG] not adding permissions to wagon connection
[INFO] Uploading: http://xx.xxx.xx.xx:8081/nexus/content/repositories/releases//com/xxx/xxxx/xxx/xxx-xxx/1.9.40/xxx-xxx-1.9.40-sources.jar
[INFO] [DEBUG] Using Wagon implementation lightweight from default mapping for protocol http
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [ERROR] BUILD ERROR
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] Error deploying artifact: Authorization failed: Access denied to: http://xx.xxx.xx.xx:8081/nexus/content/repositories/releases/com/xxx/xxx/xxx/xxx-config/1.9.40/xxx-xxx-1.9.40-sources.jar

Any help regarding this will be really appreciated.

Body:
I configured the maven release plug-in with releaseProfile=false and dont execute the source artifacts profile. Which did the trick.

<build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-release-plugin</artifactId>
                    <version>2.1</version>
                    <configuration>
                            <arguments>-P!source-artifacts</arguments>
                            <useReleaseProfile>false</useReleaseProfile>
                            <goals>-Dmaven.test.skip=true deploy</goals>
                    </configuration>
                </plugin>
            </plugins>
        </build>


问:
C# Google Sheets APIv4 filling requestbody
Sorry if this question is very basic.
I'm trying to create an update request to fill me some googledocs spreadsheets with content (btw the portion of the code that READS those sheets works just fine), but, being intermediate at best, I can not wrap my head around this issue.

So here's the problematic fraction of the code:

```<code> Data.ValueRange requestBody = new Data.ValueRange();
 var test = new string[] { "p1", "p2", "p3", "", "", "", "", "iwannadie" };
 requestBody.Values.Add(test);`
</code>```

The third line of this code returns System.NullReferenceException, Object reference is not set to an instance of an object.
What gives?

requestBody.Values has a type of IList<IList<object>>, trying to instead use this code:

requestBody.Values.Add(new IList<object> { "", "", "" });

Results in compiler error "Can not create instance of abstract class lol suffer".
And trying to Add a List gives compiler error "can not convert List into IList".
Please help q-q

答:
Basically, requestBody.Values will be null until you populate it.

Just create your own list and populate it with your array, e.g.

```<code>var test = new string[] { "p1", "p2", "p3", "", "", "", "", "foo" };
requestBody.Values = new List<IList<object>> { test };
</code>```

Body:
Sorry if this question is very basic.
I'm trying to create an update request to fill me some googledocs spreadsheets with content (btw the portion of the code that READS those sheets works just fine), but, being intermediate at best, I can not wrap my head around this issue.

So here's the problematic fraction of the code:

 Data.ValueRange requestBody = new Data.ValueRange();
 var test = new string[] { "p1", "p2", "p3", "", "", "", "", "iwannadie" };
 requestBody.Values.Add(test);`

The third line of this code returns System.NullReferenceException, Object reference is not set to an instance of an object.
What gives?

requestBody.Values has a type of IList<IList<object>>, trying to instead use this code:

requestBody.Values.Add(new IList<object> { "", "", "" });

Results in compiler error "Can not create instance of abstract class lol suffer".
And trying to Add a List gives compiler error "can not convert List into IList".
Please help q-q

Body:
Basically, requestBody.Values will be null until you populate it.

Just create your own list and populate it with your array, e.g.

var test = new string[] { "p1", "p2", "p3", "", "", "", "", "foo" };
requestBody.Values = new List<IList<object>> { test };


问:
Toolbar haven't the full size
Hey Guys I want to make a Custom Toolbar. I tried so many things but nothing works.... So I have this in my manifest.xml:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true">
    <activity android:name=".HomeActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <!--android:theme="@style/HomeActionBar">-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

And here my activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

</android.support.design.widget.CoordinatorLayout>```

But look! I didn't get the full size of the ActionBar:

答:
You must change the width of ToolBar

The code will look like:

```<code> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.iiiii.iiiii.HomeActivity"
  >

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

    <!-- <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Delete SharedPreferences" /> -->

</android.support.design.widget.CoordinatorLayout>
</code>```

Title: Toolbar haven't the full size

Body:
Hey Guys I want to make a Custom Toolbar. I tried so many things but nothing works.... So I have this in my manifest.xml:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true">
    <activity android:name=".HomeActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And here my activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

</android.support.design.widget.CoordinatorLayout>

But look! I didn't get the full size of the ActionBar:

Body:
You must change the width of ToolBar

The code will look like:

 <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.iiiii.iiiii.HomeActivity"
  >

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

    <!-- <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Delete SharedPreferences" /> -->

</android.support.design.widget.CoordinatorLayout>


问:
Python OpenCV: inRange() stopped working without change
I am currently doing real time object detection of an orange ball with Raspberry Pi 3 Model B. The code below is supposed to take a frame, then with the cv2.inRange() function, filter out the image using RGB (BGR). Then I apply dialation and erosion to remove noise. Then I find the contours and draw them. This code worked until now. However when I ran it today without changing it, I got the folowing error:

```<code> Traceback (most recent call last):
 File "/home/pi/Desktop/maincode.py", line 12, in <module>
   mask = cv2.inRange(frame, lower, upper)
error: /build/opencv-ISmtkH/opencv-2.4.9.1+dfsg/modules/core/src/arithm.cpp:2701: error: (-209) The lower bounary is neither an array of the same size and same type as src, nor a scalar in function inRange
</code>```

Any help would be really awesome, because I was new to openCV and spent a lot of time proggraming this, and I have a competetion of robotics in 5 days.

Thank you in advance

```<code>            import cv2
            import cv2.cv as cv
            import numpy as np

            capture = cv2.VideoCapture(0)
            while capture.isOpened:
                    ret, frame = capture.read()
                    im = frame
                    lower = np.array([0, 100 ,150], dtype = 'uint8')
                    upper = np.array([10,180,255], dtype = 'uint8')
                    mask = cv2.inRange(frame, lower, upper)
                    eroded = cv2.erode(mask, np.ones((7, 7)))
                    dilated = cv2.dilate(eroded, np.ones((7, 7)))
                    contours, hierarchy =   cv2.findContours(dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

                    cv2.drawContours(im,contours,-1,(0,255,0),3)
                    cv2.imshow('colors',im)
                    cv2.waitKey(1)
</code>```

答:
The error you receive almost certainly means you  have an empty image (or you mix up the sizes of your input image).

Webcam captures in OpenCV often start with one or a couple of black/emtpy images (crappy drivers). Since it goes too fast, that's why you don't notice this. However, this will have an influence on your application if you want to process the image.  Therefore, I recommend you to check the image before proceeding with the calculations on them. Just add this after your capture.read() line:

```<code>if ret == True:
</code>```

Note: make sure (by printing in the console or something) that this only happens when you start capturing. If this happens regularly (empty frames from your webcam), maybe there's something else wrong (or maybe with your webcam). Also check it on another computer.

Body:
I am currently doing real time object detection of an orange ball with Raspberry Pi 3 Model B. The code below is supposed to take a frame, then with the cv2.inRange() function, filter out the image using RGB (BGR). Then I apply dialation and erosion to remove noise. Then I find the contours and draw them. This code worked until now. However when I ran it today without changing it, I got the folowing error:

 Traceback (most recent call last):
 File "/home/pi/Desktop/maincode.py", line 12, in <module>
   mask = cv2.inRange(frame, lower, upper)
error: /build/opencv-ISmtkH/opencv-2.4.9.1+dfsg/modules/core/src/arithm.cpp:2701: error: (-209) The lower bounary is neither an array of the same size and same type as src, nor a scalar in function inRange

Any help would be really awesome, because I was new to openCV and spent a lot of time proggraming this, and I have a competetion of robotics in 5 days.

Thank you in advance

            import cv2
            import cv2.cv as cv
            import numpy as np

            capture = cv2.VideoCapture(0)
            while capture.isOpened:
                    ret, frame = capture.read()
                    im = frame
                    lower = np.array([0, 100 ,150], dtype = 'uint8')
                    upper = np.array([10,180,255], dtype = 'uint8')
                    mask = cv2.inRange(frame, lower, upper)
                    eroded = cv2.erode(mask, np.ones((7, 7)))
                    dilated = cv2.dilate(eroded, np.ones((7, 7)))
                    contours, hierarchy =   cv2.findContours(dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

                    cv2.drawContours(im,contours,-1,(0,255,0),3)
                    cv2.imshow('colors',im)
                    cv2.waitKey(1)

Body:
The error you receive almost certainly means you  have an empty image (or you mix up the sizes of your input image).

Webcam captures in OpenCV often start with one or a couple of black/emtpy images (crappy drivers). Since it goes too fast, that's why you don't notice this. However, this will have an influence on your application if you want to process the image.  Therefore, I recommend you to check the image before proceeding with the calculations on them. Just add this after your capture.read() line:

if ret == True:

Note: make sure (by printing in the console or something) that this only happens when you start capturing. If this happens regularly (empty frames from your webcam), maybe there's something else wrong (or maybe with your webcam). Also check it on another computer.


问:
JavaScript best practice, Using closures
Hey I read at Google article (here) that we need to be careful when using closures.

For example, they gave there this function:

```<code>function foo(element, a, b) {
    element.onclick = function() { /* uses a and b */ };
}
</code>```

And I quote:

the function closure keeps a reference to element, a, and b even if it never uses element. Since element also keeps a reference to the closure, we have a cycle that won't be cleaned up by garbage collection.

And I also read an article on the module pattern , and there is a lot of use in closures

for example if I declare a module like that:

```<code>(function () {
    var a = function () { };
    var b = function () { };
}());
</code>```

So b have access to a , meaning its also save reference to all functions declared on the module.

Is it considered bad practice too?

答:
The statement you quoted is rubbish.

the function closure keeps a reference to element, a, and b even if it never uses element.

No it doesn't.

Since element also keeps a reference to the closure, we have a cycle that won't be cleaned up by garbage collection.

No they will1.

(1: We tend to ignore ancient buggy internet explorers)

So to answer your question: No, those are not bad practices.

Body:
Hey I read at Google article (here) that we need to be careful when using closures.

For example, they gave there this function:

function foo(element, a, b) {
    element.onclick = function() { /* uses a and b */ };
}

And I quote:

the function closure keeps a reference to element, a, and b even if it never uses element. Since element also keeps a reference to the closure, we have a cycle that won't be cleaned up by garbage collection.

And I also read an article on the module pattern , and there is a lot of use in closures

for example if I declare a module like that:

(function () {
    var a = function () { };
    var b = function () { };
}());

So b have access to a , meaning its also save reference to all functions declared on the module.

Is it considered bad practice too?


问:
How to quote an expression that contains a comma in R?
```<code>quote(~ source == "abc", ~ name == xyz)
</code>```

I want to quote this expressions. I am getting following error:

```<code>enter Error in quote(~abc, bca) :
2 arguments passed to 'quote' which requires 1
</code>```

答:
If you're trying to capture the expressions as arguments to create a new call try, eval(substitute(alist(~abc,bca))). This uses the alist() function and captures all the arguments (credit to Hadley Wickham's Advanced R)

Or c(quote(~source == 'abc'), quote(~name == xyz))

Body:
quote(~ source == "abc", ~ name == xyz)

I want to quote this expressions. I am getting following error:

enter Error in quote(~abc, bca) :
2 arguments passed to 'quote' which requires 1