qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
38,870 | I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance?
Example:
>
> str = "happy" substr = "app"
>
>
> index = 1
>
>
>
My code:
```
public static int subStringIndex(String str, String substr) {
int substrlen = substr.length();
int strlen = str.length();
int j = 0;
int index = -1;
if (substrlen < 1) {
return index;
}
else {
for (int i = 0; i < strlen; i++) { // iterate through main string
if (str.charAt(i) == substr.charAt(j)) { // check substring
index = i - j; // remember index
j++; // iterate
if (j == substrlen) { // when to stop
return index;
}
}
else {
j = 0;
index = -1;
}
}
}
return index;
}
``` | 2014/01/09 | [
"https://codereview.stackexchange.com/questions/38870",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/32250/"
] | Actually there is a bug. Consider `str="aaS"` and `substr="aS"`.
At first iteration `a` and `a` are equal.
At second iteration `a` and `S` are not equal, and it will skip it, however `substr`'s first character is equal to it.
So it should be:
```
public static int subStringIndex(String str, String substr) {
int substrlen = substr.length();
int strlen = str.length();
int j = 0;
if (substrlen >= 1) {
for (int i = 0; i < strlen; i++) { // iterate through main string
if (str.charAt(i) == substr.charAt(j)) { // check substring
j++; // iterate
if (j == substrlen) { // when to stop
return i - (substrlen - 1); //found substring. As i is currently at the end of our substr so sub substrlen
}
}
else {
i -= j;
j = 0;
}
}
}
return -1;
}
```
**Edit update:**
Needed to subtract 1 from the String's length in order to pass the right answer. | Here is another version:
```
public static int indexOf(String original, String find) {
if (find.length() < 1)
return -1;
boolean flag = false;
for (int i = 0, k = 0; i < original.length(); i++) {
if (original.charAt(i) == find.charAt(k)) {
k++;
flag = true;
if (k == find.length())
return i - k + 1;
} else {
k = 0;
if (flag) {
i--;
flag = false;
}
}
}
return -1;
}
``` |
38,870 | I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance?
Example:
>
> str = "happy" substr = "app"
>
>
> index = 1
>
>
>
My code:
```
public static int subStringIndex(String str, String substr) {
int substrlen = substr.length();
int strlen = str.length();
int j = 0;
int index = -1;
if (substrlen < 1) {
return index;
}
else {
for (int i = 0; i < strlen; i++) { // iterate through main string
if (str.charAt(i) == substr.charAt(j)) { // check substring
index = i - j; // remember index
j++; // iterate
if (j == substrlen) { // when to stop
return index;
}
}
else {
j = 0;
index = -1;
}
}
}
return index;
}
``` | 2014/01/09 | [
"https://codereview.stackexchange.com/questions/38870",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/32250/"
] | Actually there is a bug. Consider `str="aaS"` and `substr="aS"`.
At first iteration `a` and `a` are equal.
At second iteration `a` and `S` are not equal, and it will skip it, however `substr`'s first character is equal to it.
So it should be:
```
public static int subStringIndex(String str, String substr) {
int substrlen = substr.length();
int strlen = str.length();
int j = 0;
if (substrlen >= 1) {
for (int i = 0; i < strlen; i++) { // iterate through main string
if (str.charAt(i) == substr.charAt(j)) { // check substring
j++; // iterate
if (j == substrlen) { // when to stop
return i - (substrlen - 1); //found substring. As i is currently at the end of our substr so sub substrlen
}
}
else {
i -= j;
j = 0;
}
}
}
return -1;
}
```
**Edit update:**
Needed to subtract 1 from the String's length in order to pass the right answer. | My re-writing: clear and clean, yet efficient. There is no innovation in the algorithm. Just the way of the coding in more structural re-arrangement, trying to make the thought and steps easy to read and understand (comments are welcome):
```
static int subStringIndex( String str, String substring) {
if (substring.length() < 1 )
return -1;
int L = str.length();
int l = substring.length();
int index = -1;
for (int i = 0, j; i <= L-l; i++) {
// if the remaining (L-i) is smaller than l,
// there won't be no enough length to contain the substring.
for (j = 0; j < l; j++) {
if (substring.charAt(j) != str.charAt(i+j) ) {
break;
}
}
// has it reached the end of the shorter string?
// if so, it means no non-equals encountered.
if (j == l) {
index = i;
break;
}
}
return index;
}
``` |
38,870 | I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance?
Example:
>
> str = "happy" substr = "app"
>
>
> index = 1
>
>
>
My code:
```
public static int subStringIndex(String str, String substr) {
int substrlen = substr.length();
int strlen = str.length();
int j = 0;
int index = -1;
if (substrlen < 1) {
return index;
}
else {
for (int i = 0; i < strlen; i++) { // iterate through main string
if (str.charAt(i) == substr.charAt(j)) { // check substring
index = i - j; // remember index
j++; // iterate
if (j == substrlen) { // when to stop
return index;
}
}
else {
j = 0;
index = -1;
}
}
}
return index;
}
``` | 2014/01/09 | [
"https://codereview.stackexchange.com/questions/38870",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/32250/"
] | Here is another version:
```
public static int indexOf(String original, String find) {
if (find.length() < 1)
return -1;
boolean flag = false;
for (int i = 0, k = 0; i < original.length(); i++) {
if (original.charAt(i) == find.charAt(k)) {
k++;
flag = true;
if (k == find.length())
return i - k + 1;
} else {
k = 0;
if (flag) {
i--;
flag = false;
}
}
}
return -1;
}
``` | My re-writing: clear and clean, yet efficient. There is no innovation in the algorithm. Just the way of the coding in more structural re-arrangement, trying to make the thought and steps easy to read and understand (comments are welcome):
```
static int subStringIndex( String str, String substring) {
if (substring.length() < 1 )
return -1;
int L = str.length();
int l = substring.length();
int index = -1;
for (int i = 0, j; i <= L-l; i++) {
// if the remaining (L-i) is smaller than l,
// there won't be no enough length to contain the substring.
for (j = 0; j < l; j++) {
if (substring.charAt(j) != str.charAt(i+j) ) {
break;
}
}
// has it reached the end of the shorter string?
// if so, it means no non-equals encountered.
if (j == l) {
index = i;
break;
}
}
return index;
}
``` |
20,486,890 | It's been a while since I posted on here so I hope this isn't bad form. But I figured it's easier to look at the page for a live example: <http://www.wrangelloutfitters.com>
The drop down menu works in IE, chrome, and Safari, but not Firefox. Tested in Firefox 11.0, and Firefox 25.0.1. I recently converted it from a CSS hover to jQuery events for touch screens and it's working fine. Just not in Firefox which leaves me baffled.
For summary and posterity if someone else needs this after the site has been changed basic code is:
```
<script>
function hideAllDrops (){
document.getElementById('mainA-sub').style.display='none';
document.getElementById('mainB-sub').style.display='none';
document.getElementById('mainC-sub').style.display='none';
};
$(function(){
$( "html" ).click(function() {
hideAllDrops ();
});
$( "#mainA" ).click(function(){
hideAllDrops ();
document.getElementById('mainA-sub').style.display='block';
event.stopPropagation();
});
});
</script>
```
---
```
<li><a class="menuOpt" id="mainA">Guided Hunts</a>
<div class="nav_sub last" id="mainA-sub">
<div class="nav_sub_wrapper">
<ul>
<li><a href="/subPage">Option 1</a></li>
<li><a href="/subPage01">Option 2</a></li>
<li><a href="/subPage03">Option 3</a></li>
</ul>
</div><div class="sub_nav_end"></div>
</div>
</li>
``` | 2013/12/10 | [
"https://Stackoverflow.com/questions/20486890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522307/"
] | Firefox Console : [00:40:05,423] ReferenceError: event is not defined @ <http://www.wrangelloutfitters.com/:64>
your dropdown link throws error. please refer your console in firebug.
you not passed event as a argument and still you are using event.stopPropagation();
instead you should use like below
```
$( "#about-wrangelloutfitters" ).click(function(event) {
hideAllDrops ();
document.getElementById('about-wrangelloutfitters-sub').style.display='block';
event.stopPropagation();
});
``` | You need to use `'` in ,`getElementById('mainA-sub')`
```
$( "html" ).click(function() {
hideAllDrops ();
});
function hideAllDrops (){
document.getElementById('mainA-sub').style.display='none';
document.getElementById('mainB-sub').style.display='none';
document.getElementById('mainC-sub').style.display='none';
}
``` |
61,593 | I am setting up an informational interview with a director of a firm. I approached the person to which they replied that they were happy to read my message and would like to offer me time and asked me for schedule. I replied with a thank you note and told them that i am free on these days but can find time on other days according to your schedule. Note: I am still a student so I can find time between classes. I have waited 7 business days but did not get a reply from her and now I am thinking of writing a polite reminder but I am confused on how to write it.
Following was her reply:
>
> Good morning Faisal! I enjoyed reading your email this morning and would like to offer up some time for us to chat. Let me know your availability and we can look to sync up to discuss. Sound good?
>
>
> | 2016/02/04 | [
"https://workplace.stackexchange.com/questions/61593",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/46446/"
] | This is something to bring up with management immediately. Maybe the locks disable when the fire alarm is tripped or maybe you are all in a death trap. Check that they have done their due diligence that the layout complies with fire code, then confirm it to your own satisfaction. Your life is not something to risk on not wanting to make waves.
In further research you may want to refer to OHSA 1910.36(b)(1)
>
> Two exit routes. At least two exit routes must be available in a workplace to permit prompt evacuation of employees and other building occupants during an emergency, except as allowed in paragraph (b)(3) of this section. The exit routes must be located as far away as practical from each other so that if one exit route is blocked by fire or smoke, employees can evacuate using the second exit route.
>
>
>
1910.36(d)(1)
>
> Employees must be able to open an exit route door from the inside at all times without keys, tools, or special knowledge. A device such
> as a panic bar that locks only from the outside is permitted on exit
> discharge doors.
>
>
>
1910.36(d)(2)
>
> Exit route doors must be free of any device or alarm that could
> restrict emergency use of the exit route if the device or alarm fails.
>
>
>
<https://www.osha.gov/pls/oshaweb/owadisp.show_document?p_table=STANDARDS&p_id=9724>
If a violation exists and management is not willing to rectify it contact your OH&S officer (if the workplace has one), your state labor board, or your municipal fire department and ask for fire code inspection. | Myles is correct that you should raise this immediately. Convenience would be one thing but what you describe is a dangerously unsafe office. When you bring this to management one key thing to keep in mind in such discussions is to avoid laying blame and make it about "us versus them" Don't say "I'll report this to the fire marshall" but say "I fear this would be a violation of the OHSA regulations."
As an example script:
>
> Hey X, a couple of us (or just "I") noticed after the access control system came online that we also need our fobs to leave the building/office. While this is not only inconvenient, we're worried that this might be a serious safety issue in case of a fire or other emergency or if the system breaks down1.
>
>
> I looked into the building regulations that apply to office and according to OHSA we need at least two unlocked emergency exits. Aside from the safety issue we could also be at serious risks of being fined or shut down if we get an inspection of our new premises.
>
>
>
Keep in mind that this is a conversation you should have in person so you see how your manager reacts. Your take-away from this should be that the system will be immediately deactivated for exits, or at the very least the opening of at least one additional emergency exit, possibly more depending on the size and layout of your building. If that does not happen or if you catch even a hint of resistance from your manager on this, I'd suggest contacting the relevant safety agency for your area immediately. If you have a competent HR department who aren't in the loop on the renovations, you could contact them first as they should realise quickly how dangerous this situation is from both a safety and a legal perspective.
I'm normally not a fan of actually taking (semi-) legal action, but your health and safety should not be compromised at work. A newly renovated building is already at a higher short-term risk, before you add in ethically questionably construction companies.
---
1 Note that as far as I know any electrically secured access control system is required to fail-open. This shouldn't be an issue but if the security guys aren't even following basic OHSA guidelines then I wouldn't be surprised if they're creating actual death traps. |
39,113,876 | I created a custom type based on the Golang [`net.IP`](https://golang.org/pkg/net/#IP) type. What surprised me is that a method declared with a pointer receiver to my custom type can't modify the value to which the receiver points.
The `u` variable in this code snippet remains `nil` after calling `u.defaultIP()`. The IP can be modified if I changed my custom type to a struct with an IP field and the method is defined with a pointer receiver to the struct. What am I missing? Executable example can be found [here](https://play.golang.org/p/QZhx4XqOHt).
```
type userIP net.IP
func main() {
var u *userIP
u.defaultIP()
fmt.Printf("%v\n", u)
}
func (u *userIP) defaultIP() {
defaultIP := userIP("127.0.0.1")
u = &defaultIP
}
``` | 2016/08/24 | [
"https://Stackoverflow.com/questions/39113876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144203/"
] | You need to dereference the `u` before setting it's value.
From your example, change
```
defaultIP := userIP("127.0.0.1")
u = &defaultIP
```
to
```
*u = userIP("127.0.0.1")
```
For your example updated and working: <https://play.golang.org/p/ycCLT0ed9F> | TL;DR: The pointer receiver needs to be dereferenced before it's value can be set. This applies to both struct and non-struct types. In the case of struct types, the dereferencing is automatically done by the selector expression.
After digging around a bit further, I think this behaviour is caused by the fact that the pointer receiver is not the same pointer calling the method.
Running this code snippet shows that the `u` pointer in the `main()` function is different from that in the `defaultIP()` method. Essentially, I end up **only** modifying the `u` pointer in the `defaultIP()` method. Executable example can be found [here](https://play.golang.org/p/bjNWbNdTjg).
```
func main() {
var u *userIP
u.defaultIP()
fmt.Printf("main(): address of pointer is %v\n", &u)
fmt.Printf("main(): user IP address is %v\n", u)
}
type userIP net.IP
func (u *userIP) defaultIP() {
defaultIP := userIP("127.0.0.1")
u = &defaultIP
fmt.Printf("defaultIP(): address of pointer is %v\n", &u)
fmt.Printf("defaultIP(): user IP address is %s\n", *u)
}
```
The correct way to do this is as pointed in Tom's answer i.e. dereference `u` in the `defaultIP()` method.
What puzzled me earlier was why would this example work if I wrapped the IP as a field in the struct? Running the code snippet shows that the two `u` pointers are indeed different, but the `ip` field is modified. Executable example can be found [here](https://play.golang.org/p/bCDrb2FAH5).
```
func main() {
u := &userInfo{}
u.defaultIP()
fmt.Printf("main(): address of pointer is %v\n", &u)
fmt.Printf("main(): user IP address is %s\n", u.ip)
}
type userInfo struct{
ip net.IP
}
func (u *userInfo) defaultIP() {
u.ip = net.ParseIP("127.0.0.1")
fmt.Printf("defaultIP(): address of pointer is %v\n", &u)
fmt.Printf("defaultIP(): user IP address is %s\n", u.ip)
}
```
Turns out that this is caused by the [selector expression](https://golang.org/ref/spec#Selectors) (`x.y`). To quote the doc,
>
> Selectors automatically dereference pointers to structs. If x is a pointer to a struct, x.y is shorthand for (*x).y; if the field y is also a pointer to a struct, x.y.z is shorthand for (*(\*x).y).z, and so on. If x contains an anonymous field of type \*A, where A is also a struct type, x.f is a shortcut for (\*x.A).f.
>
>
>
So in my case, the `u.ip` expression dereferences `u` before modifying the `ip` field, which essentially translates to`(*u).ip`. |
39,113,876 | I created a custom type based on the Golang [`net.IP`](https://golang.org/pkg/net/#IP) type. What surprised me is that a method declared with a pointer receiver to my custom type can't modify the value to which the receiver points.
The `u` variable in this code snippet remains `nil` after calling `u.defaultIP()`. The IP can be modified if I changed my custom type to a struct with an IP field and the method is defined with a pointer receiver to the struct. What am I missing? Executable example can be found [here](https://play.golang.org/p/QZhx4XqOHt).
```
type userIP net.IP
func main() {
var u *userIP
u.defaultIP()
fmt.Printf("%v\n", u)
}
func (u *userIP) defaultIP() {
defaultIP := userIP("127.0.0.1")
u = &defaultIP
}
``` | 2016/08/24 | [
"https://Stackoverflow.com/questions/39113876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144203/"
] | You need to dereference the `u` before setting it's value.
From your example, change
```
defaultIP := userIP("127.0.0.1")
u = &defaultIP
```
to
```
*u = userIP("127.0.0.1")
```
For your example updated and working: <https://play.golang.org/p/ycCLT0ed9F> | Two Options:
1- With dereferencing: like this working code and using `net.ParseIP("127.0.0.1")`
([The Go Playground](https://play.golang.org/p/qbVIFjCY7j)):
```golang
package main
import (
"fmt"
"net"
)
type userIP net.IP
func main() {
var u userIP
u.defaultIP()
fmt.Println(u)
}
func (u *userIP) defaultIP() {
*u = userIP(net.ParseIP("127.0.0.1"))
}
```
output:
```
[0 0 0 0 0 0 0 0 0 0 255 255 127 0 0 1]
```
---
2- Without dereferencing ([The Go Playground](https://play.golang.org/p/QLTX0iR3Jr)):
```golang
package main
import (
"fmt"
"net"
)
type userIP net.IP
func main() {
u := make(userIP, 4)
u.defaultIP()
fmt.Printf("%v\n", u)
}
func (u userIP) defaultIP() {
u[0], u[1], u[2], u[3] = 127, 0, 0, 1
}
```
---
And note that `net.IP` is `[]byte`, see `net.IP` Docs:
>
> An IP is a single IP address, a slice of bytes. Functions in this
> package accept either 4-byte (IPv4) or 16-byte (IPv6) slices as input.
>
>
> |
39,113,876 | I created a custom type based on the Golang [`net.IP`](https://golang.org/pkg/net/#IP) type. What surprised me is that a method declared with a pointer receiver to my custom type can't modify the value to which the receiver points.
The `u` variable in this code snippet remains `nil` after calling `u.defaultIP()`. The IP can be modified if I changed my custom type to a struct with an IP field and the method is defined with a pointer receiver to the struct. What am I missing? Executable example can be found [here](https://play.golang.org/p/QZhx4XqOHt).
```
type userIP net.IP
func main() {
var u *userIP
u.defaultIP()
fmt.Printf("%v\n", u)
}
func (u *userIP) defaultIP() {
defaultIP := userIP("127.0.0.1")
u = &defaultIP
}
``` | 2016/08/24 | [
"https://Stackoverflow.com/questions/39113876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144203/"
] | TL;DR: The pointer receiver needs to be dereferenced before it's value can be set. This applies to both struct and non-struct types. In the case of struct types, the dereferencing is automatically done by the selector expression.
After digging around a bit further, I think this behaviour is caused by the fact that the pointer receiver is not the same pointer calling the method.
Running this code snippet shows that the `u` pointer in the `main()` function is different from that in the `defaultIP()` method. Essentially, I end up **only** modifying the `u` pointer in the `defaultIP()` method. Executable example can be found [here](https://play.golang.org/p/bjNWbNdTjg).
```
func main() {
var u *userIP
u.defaultIP()
fmt.Printf("main(): address of pointer is %v\n", &u)
fmt.Printf("main(): user IP address is %v\n", u)
}
type userIP net.IP
func (u *userIP) defaultIP() {
defaultIP := userIP("127.0.0.1")
u = &defaultIP
fmt.Printf("defaultIP(): address of pointer is %v\n", &u)
fmt.Printf("defaultIP(): user IP address is %s\n", *u)
}
```
The correct way to do this is as pointed in Tom's answer i.e. dereference `u` in the `defaultIP()` method.
What puzzled me earlier was why would this example work if I wrapped the IP as a field in the struct? Running the code snippet shows that the two `u` pointers are indeed different, but the `ip` field is modified. Executable example can be found [here](https://play.golang.org/p/bCDrb2FAH5).
```
func main() {
u := &userInfo{}
u.defaultIP()
fmt.Printf("main(): address of pointer is %v\n", &u)
fmt.Printf("main(): user IP address is %s\n", u.ip)
}
type userInfo struct{
ip net.IP
}
func (u *userInfo) defaultIP() {
u.ip = net.ParseIP("127.0.0.1")
fmt.Printf("defaultIP(): address of pointer is %v\n", &u)
fmt.Printf("defaultIP(): user IP address is %s\n", u.ip)
}
```
Turns out that this is caused by the [selector expression](https://golang.org/ref/spec#Selectors) (`x.y`). To quote the doc,
>
> Selectors automatically dereference pointers to structs. If x is a pointer to a struct, x.y is shorthand for (*x).y; if the field y is also a pointer to a struct, x.y.z is shorthand for (*(\*x).y).z, and so on. If x contains an anonymous field of type \*A, where A is also a struct type, x.f is a shortcut for (\*x.A).f.
>
>
>
So in my case, the `u.ip` expression dereferences `u` before modifying the `ip` field, which essentially translates to`(*u).ip`. | Two Options:
1- With dereferencing: like this working code and using `net.ParseIP("127.0.0.1")`
([The Go Playground](https://play.golang.org/p/qbVIFjCY7j)):
```golang
package main
import (
"fmt"
"net"
)
type userIP net.IP
func main() {
var u userIP
u.defaultIP()
fmt.Println(u)
}
func (u *userIP) defaultIP() {
*u = userIP(net.ParseIP("127.0.0.1"))
}
```
output:
```
[0 0 0 0 0 0 0 0 0 0 255 255 127 0 0 1]
```
---
2- Without dereferencing ([The Go Playground](https://play.golang.org/p/QLTX0iR3Jr)):
```golang
package main
import (
"fmt"
"net"
)
type userIP net.IP
func main() {
u := make(userIP, 4)
u.defaultIP()
fmt.Printf("%v\n", u)
}
func (u userIP) defaultIP() {
u[0], u[1], u[2], u[3] = 127, 0, 0, 1
}
```
---
And note that `net.IP` is `[]byte`, see `net.IP` Docs:
>
> An IP is a single IP address, a slice of bytes. Functions in this
> package accept either 4-byte (IPv4) or 16-byte (IPv6) slices as input.
>
>
> |
20,653,750 | I'm using jQuery.
```
$.ajax({
url: xxx,
success: function(data) {
...
}
});
```
The data is an XML document like:
```
<root>
<source>
<a><source>...</source></a>
<b>...</b>
...
</source>
<article>
...
</article>
</root>
```
I want to extract the XML fragment under source tag, and append them to a div with id "converted". How could I do?
PS: the fragment may include source tags too. | 2013/12/18 | [
"https://Stackoverflow.com/questions/20653750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114401/"
] | Try this:
```
$('#converted').append($('source:first', data));
``` | ```
var txt = data
if (window.DOMParser)
{
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
var array_of_source_elems = xmlDoc.getElementsByTagName("source");
```
`xmlDoc` can then be used like DOM Documents e.g.: `xmlDoc.getElementsBy`... etc. |
20,653,750 | I'm using jQuery.
```
$.ajax({
url: xxx,
success: function(data) {
...
}
});
```
The data is an XML document like:
```
<root>
<source>
<a><source>...</source></a>
<b>...</b>
...
</source>
<article>
...
</article>
</root>
```
I want to extract the XML fragment under source tag, and append them to a div with id "converted". How could I do?
PS: the fragment may include source tags too. | 2013/12/18 | [
"https://Stackoverflow.com/questions/20653750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114401/"
] | Try this:
```
$('#converted').append($('source:first', data));
``` | if you are getting XML documents from ajax, try this
Documentation & Source: <https://github.com/josefvanniekerk/jQuery-xml2json>
```
$.get('data/temp.xml', function(xml) {
var jObj = $.xml2json(xml);
alert(jObj.node.node1.name[0]["Hello"]);
});
``` |
58,704,880 | I hope my title is enough to determine what the error is.
I have this code in my `models.py` (post\_save)
```py
class StudentsEnrolledSubject(models.Model):
Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+',
on_delete=models.CASCADE, null=True)
Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
@receiver(post_save, sender=StudentsEnrollmentRecord)
def create(sender, instance, created, *args, **kwargs):
teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses)
for each in teachers:
if created and teachers.exists():
StudentsEnrolledSubject.objects.update_or_create(
pk=each.id,
Students_Enrollment_Records=instance,
Subject_Section_Teacher=teachers.all()
)
class StudentsEnrollmentRecord(models.Model):
Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True)
class SubjectSectionTeacher(models.Model):
Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True)
Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True)
Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)
Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True)
```
when I used the `Subject_Section_Teacher=teachers.first()` i received no error but that is not what i want result, then i decide to change it to this `Subject_Section_Teacher=teachers.all()`
I just want the result to become this
[](https://i.stack.imgur.com/JH9f4.png)
not this
[](https://i.stack.imgur.com/IH2eE.png)
this is where I get/filter data
[](https://i.stack.imgur.com/cH6rP.png) | 2019/11/05 | [
"https://Stackoverflow.com/questions/58704880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You are trying to access list as a single object, which is not possible.
you need to create single instance of your list class and then you can add string in that single instance.
```
properData.Secnd = new List<ProSecndData>();
ProSecndData proSecndData = new ProSecndData();
proSecndData.product = "Hello";
properData.Secnd.Add(proSecndData);
``` | Actually I know the answer already, you have not created a constructor to initialise your List.
I'm guessing you get a object null ref error?
Create the constructor to initialise your list and it should be fine.
But in future, please post the error message *(not the whole stack, just the actual error)* as well as **all** the code required to repeat the issue. Otherwise you run the risk of getting your question deleted
*(It should be deleted anyway because it could be considered a "what is a null ref err?" question).*
Also you are accessing an item in a list like the list is that item (should be more like: `ProperData.Secnd.elementAt(0).product`, please also note the capitalisation of 'product' in the model vs your code. |
58,704,880 | I hope my title is enough to determine what the error is.
I have this code in my `models.py` (post\_save)
```py
class StudentsEnrolledSubject(models.Model):
Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+',
on_delete=models.CASCADE, null=True)
Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
@receiver(post_save, sender=StudentsEnrollmentRecord)
def create(sender, instance, created, *args, **kwargs):
teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses)
for each in teachers:
if created and teachers.exists():
StudentsEnrolledSubject.objects.update_or_create(
pk=each.id,
Students_Enrollment_Records=instance,
Subject_Section_Teacher=teachers.all()
)
class StudentsEnrollmentRecord(models.Model):
Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True)
class SubjectSectionTeacher(models.Model):
Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True)
Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True)
Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)
Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True)
```
when I used the `Subject_Section_Teacher=teachers.first()` i received no error but that is not what i want result, then i decide to change it to this `Subject_Section_Teacher=teachers.all()`
I just want the result to become this
[](https://i.stack.imgur.com/JH9f4.png)
not this
[](https://i.stack.imgur.com/IH2eE.png)
this is where I get/filter data
[](https://i.stack.imgur.com/cH6rP.png) | 2019/11/05 | [
"https://Stackoverflow.com/questions/58704880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you cannot directly access property of `Secnd` as it is a list
you need to iterate or select the index of the `List<Secnd>`
*you must initialize* `Secnd` *first* and `Secnd` should have items in the list
```
properData.Secnd = new List<ProSecndData>();
```
so it can be access via
```
foreach(var second in properData.Secnd)
{
second.product = "hello";
}
//or
for(var i = 0; i < proderData.Secnd.Count(); i++)
{
properData.Secnd[i].product = "hello";
}
//or
var index = //0-length of list;
properData.Secnd[index].product = "hello";
```
if you want to have items first then add first on your `Secnd` List
```
properData.Secnd = new List<ProSecndData>();
properData.Secnd.Add(new ProSecndData{ product = "hello"});
```
then you now can iterate the list by using methods above | Actually I know the answer already, you have not created a constructor to initialise your List.
I'm guessing you get a object null ref error?
Create the constructor to initialise your list and it should be fine.
But in future, please post the error message *(not the whole stack, just the actual error)* as well as **all** the code required to repeat the issue. Otherwise you run the risk of getting your question deleted
*(It should be deleted anyway because it could be considered a "what is a null ref err?" question).*
Also you are accessing an item in a list like the list is that item (should be more like: `ProperData.Secnd.elementAt(0).product`, please also note the capitalisation of 'product' in the model vs your code. |
58,704,880 | I hope my title is enough to determine what the error is.
I have this code in my `models.py` (post\_save)
```py
class StudentsEnrolledSubject(models.Model):
Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+',
on_delete=models.CASCADE, null=True)
Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
@receiver(post_save, sender=StudentsEnrollmentRecord)
def create(sender, instance, created, *args, **kwargs):
teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses)
for each in teachers:
if created and teachers.exists():
StudentsEnrolledSubject.objects.update_or_create(
pk=each.id,
Students_Enrollment_Records=instance,
Subject_Section_Teacher=teachers.all()
)
class StudentsEnrollmentRecord(models.Model):
Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True)
class SubjectSectionTeacher(models.Model):
Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True)
Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True)
Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)
Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True)
```
when I used the `Subject_Section_Teacher=teachers.first()` i received no error but that is not what i want result, then i decide to change it to this `Subject_Section_Teacher=teachers.all()`
I just want the result to become this
[](https://i.stack.imgur.com/JH9f4.png)
not this
[](https://i.stack.imgur.com/IH2eE.png)
this is where I get/filter data
[](https://i.stack.imgur.com/cH6rP.png) | 2019/11/05 | [
"https://Stackoverflow.com/questions/58704880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you cannot directly access property of `Secnd` as it is a list
you need to iterate or select the index of the `List<Secnd>`
*you must initialize* `Secnd` *first* and `Secnd` should have items in the list
```
properData.Secnd = new List<ProSecndData>();
```
so it can be access via
```
foreach(var second in properData.Secnd)
{
second.product = "hello";
}
//or
for(var i = 0; i < proderData.Secnd.Count(); i++)
{
properData.Secnd[i].product = "hello";
}
//or
var index = //0-length of list;
properData.Secnd[index].product = "hello";
```
if you want to have items first then add first on your `Secnd` List
```
properData.Secnd = new List<ProSecndData>();
properData.Secnd.Add(new ProSecndData{ product = "hello"});
```
then you now can iterate the list by using methods above | You are trying to access list as a single object, which is not possible.
you need to create single instance of your list class and then you can add string in that single instance.
```
properData.Secnd = new List<ProSecndData>();
ProSecndData proSecndData = new ProSecndData();
proSecndData.product = "Hello";
properData.Secnd.Add(proSecndData);
``` |
69,709,122 | `godoc` has been removed from the go standard install [since 1.12](https://github.com/golang/go/issues/25443) and looks like it wont be updated anytime soon. `pkg.go.dev` at least [appears to be its successor](https://github.com/golang/pkgsite). It also has additional documentation features like grabbing the `README.md` file and rendering it in the documentation page.
For these reasons I was hoping to switch over to using `pkg.go.dev` locally to view and create documentation for small internal packages. The major issue is that unlike `godoc` there does not seem to be a clear usage guide. I also do not know if `pkpg.go.dev` is completely overkill for this task. So I would like to know:
1. Can and should `pkg.go.dev` be used as a local `godoc` replacement?
2. If yes, how would I run it for this task? | 2021/10/25 | [
"https://Stackoverflow.com/questions/69709122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987437/"
] | Run pkgsite locally.
`go install golang.org/x/pkgsite/cmd/pkgsite@latest && pkgsite`
References:
1. <https://tip.golang.org/doc/comment>
2. <https://pkg.go.dev/golang.org/x/pkgsite/cmd/pkgsite> | You can use the [x/tools/godoc](https://pkg.go.dev/golang.org/x/tools/cmd/godoc) that has the previous godoc tool |
69,709,122 | `godoc` has been removed from the go standard install [since 1.12](https://github.com/golang/go/issues/25443) and looks like it wont be updated anytime soon. `pkg.go.dev` at least [appears to be its successor](https://github.com/golang/pkgsite). It also has additional documentation features like grabbing the `README.md` file and rendering it in the documentation page.
For these reasons I was hoping to switch over to using `pkg.go.dev` locally to view and create documentation for small internal packages. The major issue is that unlike `godoc` there does not seem to be a clear usage guide. I also do not know if `pkpg.go.dev` is completely overkill for this task. So I would like to know:
1. Can and should `pkg.go.dev` be used as a local `godoc` replacement?
2. If yes, how would I run it for this task? | 2021/10/25 | [
"https://Stackoverflow.com/questions/69709122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987437/"
] | Run pkgsite locally.
`go install golang.org/x/pkgsite/cmd/pkgsite@latest && pkgsite`
References:
1. <https://tip.golang.org/doc/comment>
2. <https://pkg.go.dev/golang.org/x/pkgsite/cmd/pkgsite> | Running `godoc` [1] on its own worked for me, but was really slow because it generates docs for every single package in the standard library, while I only care about the local package that I am working on. To that end, if your package is in a folder called `something`, you can move the folder so that it looks like this:
```
godoc/src/something
```
Then, go to the `godoc` folder, and run
```
godoc -goroot .
```
Then, browse to `localhost:6060`. Alternatively, another site is available for
Go docs [2].
1. <https://github.com/golang/tools/tree/master/cmd/godoc>
2. <https://godocs.io> |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Sorry, there is no way to run a function directly. Either call it using a sql Text command
```
Public Sub RunFunction(ByVal input As Short)
Using myConnection As New Data.SqlClient.SqlConnection
Using myCommand As New Data.SqlClient.SqlCommand("Select dbo.MyFunction(@MyParam)", myConnection)
myCommand.CommandType = CommandType.Text
myCommand.Parameters.Add(New Data.SqlClient.SqlParameter("@MyParam", input))
myCommand.CommandTimeout = 0
Try
myCommand.ExecuteNonQuery()
Catch ex As Exception
End Try
End Using
End Using
End Sub
```
Or Wrap a procedure round it...
```
Create Procedure RunMyFunction(@MyParam as int)
Select * FROM dbo.MyFunction(@MyParam)
Go
``` | [You'd just call it like you'd call a regular line of sql code](http://forums.asp.net/t/757642.aspx) |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | [You'd just call it like you'd call a regular line of sql code](http://forums.asp.net/t/757642.aspx) | One of the things about functions is they can return different data types.
I use:
```
Friend Function execFunctionReturnsString(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As String
Dim cmd As SqlCommand
Dim param As SqlParameter
Dim sRet As String
Dim sCmdText As String
Dim iParam As Integer
cmd = New SqlCommand
sCmdText = "select dbo." & funcName & "("
cmd.CommandType = CommandType.Text
cmd.Connection = _sqlConn
cmd.CommandTimeout = 0
If Not params Is Nothing Then
For iParam = 1 To params.Count
param = params(iParam)
sCmdText = sCmdText & param.Value
If iParam < params.Count Then
sCmdText = sCmdText & ","
End If
Next
End If
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
'If _sqlConn.State <> ConnectionState.Open Then
_sqlConn.Open()
'End If
sRet = cmd.ExecuteScalar() & "" ' if null
_sqlConn.Close()
Return sRet
End Function
```
---
```
Friend Function execFunctionReturnsInt(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As Integer
Dim cmd As SqlCommand
Dim param As SqlParameter
Dim iRet As Integer
Dim sCmdText As String
Dim iParam As Integer
cmd = New SqlCommand
sCmdText = "select dbo." & funcName & "("
cmd.CommandType = CommandType.Text
cmd.Connection = _sqlConn
cmd.CommandTimeout = 0
If Not params Is Nothing Then
For iParam = 1 To params.Count
param = params(iParam)
sCmdText = sCmdText & param.Value
If iParam < params.Count Then
sCmdText = sCmdText & ","
End If
Next
End If
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
'If _sqlConn.State <> ConnectionState.Open Then
_sqlConn.Open()
'End If
iRet = cmd.ExecuteScalar()
_sqlConn.Close()
Return iRet
End Function
```
---
here's an example of a call:
---
```
params = New Collection
params.Add(SQLClientAccess.instance.sqlParam("@setID", DbType.String, 0,
_editListSetID))
valGrid.hidePKFields = SQLClientAccess.instance.execFunctionReturnsInt
("udf_hiddenCount", params)
```
---
and here's my sqlParam code:
---
```
Friend Function sqlParam(ByVal paramName As String, ByVal dBType As System.Data.DbType, ByVal iSize As Integer, ByVal sVal As String) As SqlParameter
Dim param As SqlParameter
param = New SqlParameter
param.ParameterName = paramName
param.DbType = dBType
param.Size = iSize
param.Value = sVal
Return param
End Function
```
---
HTH |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Yes you can call a function directly as demonstrated below.
```
Dim dtaName As New SqlClient.SqlDataAdapter
dtaName.SelectCommand = New SqlClient.SqlCommand
With dtaName.SelectCommand
.CommandTimeout = 60
.Connection = prvcmpINC.cntINC
.CommandType = CommandType.StoredProcedure
.CommandText = "dbo.app_GetName"
.Parameters.AddWithValue("@ParamToPassIn", parstrParamToPassIn)
.Parameters.Add("@intResult", SqlDbType.Int)
.Parameters("@intResult").Direction = ParameterDirection.ReturnValue
End With
dtaName.SelectCommand.ExecuteScalar()
intRuleNo = dtaName.SelectCommand.Parameters("@intResult").Value
``` | [You'd just call it like you'd call a regular line of sql code](http://forums.asp.net/t/757642.aspx) |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This works for me and is based on one of the above answers using a `SqlDataAdapter` (note that you do not need to use one) and `ExecuteScalar` (can use `ExecuteNonQuery` as shown here):
```
bool res = false;
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
using (SqlCommand comm = new SqlCommand("dbo.MyFunction", conn))
{
comm.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("@MyParam", SqlDbType.Int);
// You can call the return value parameter anything, .e.g. "@Result".
SqlParameter p2 = new SqlParameter("@Result", SqlDbType.Bit);
p1.Direction = ParameterDirection.Input;
p2.Direction = ParameterDirection.ReturnValue;
p1.Value = myParamVal;
comm.Parameters.Add(p1);
comm.Parameters.Add(p2);
conn.Open();
comm.ExecuteNonQuery();
if (p2.Value != DBNull.Value)
res = (bool)p2.Value;
}
}
return res;
``` | [You'd just call it like you'd call a regular line of sql code](http://forums.asp.net/t/757642.aspx) |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Sorry, there is no way to run a function directly. Either call it using a sql Text command
```
Public Sub RunFunction(ByVal input As Short)
Using myConnection As New Data.SqlClient.SqlConnection
Using myCommand As New Data.SqlClient.SqlCommand("Select dbo.MyFunction(@MyParam)", myConnection)
myCommand.CommandType = CommandType.Text
myCommand.Parameters.Add(New Data.SqlClient.SqlParameter("@MyParam", input))
myCommand.CommandTimeout = 0
Try
myCommand.ExecuteNonQuery()
Catch ex As Exception
End Try
End Using
End Using
End Sub
```
Or Wrap a procedure round it...
```
Create Procedure RunMyFunction(@MyParam as int)
Select * FROM dbo.MyFunction(@MyParam)
Go
``` | One of the things about functions is they can return different data types.
I use:
```
Friend Function execFunctionReturnsString(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As String
Dim cmd As SqlCommand
Dim param As SqlParameter
Dim sRet As String
Dim sCmdText As String
Dim iParam As Integer
cmd = New SqlCommand
sCmdText = "select dbo." & funcName & "("
cmd.CommandType = CommandType.Text
cmd.Connection = _sqlConn
cmd.CommandTimeout = 0
If Not params Is Nothing Then
For iParam = 1 To params.Count
param = params(iParam)
sCmdText = sCmdText & param.Value
If iParam < params.Count Then
sCmdText = sCmdText & ","
End If
Next
End If
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
'If _sqlConn.State <> ConnectionState.Open Then
_sqlConn.Open()
'End If
sRet = cmd.ExecuteScalar() & "" ' if null
_sqlConn.Close()
Return sRet
End Function
```
---
```
Friend Function execFunctionReturnsInt(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As Integer
Dim cmd As SqlCommand
Dim param As SqlParameter
Dim iRet As Integer
Dim sCmdText As String
Dim iParam As Integer
cmd = New SqlCommand
sCmdText = "select dbo." & funcName & "("
cmd.CommandType = CommandType.Text
cmd.Connection = _sqlConn
cmd.CommandTimeout = 0
If Not params Is Nothing Then
For iParam = 1 To params.Count
param = params(iParam)
sCmdText = sCmdText & param.Value
If iParam < params.Count Then
sCmdText = sCmdText & ","
End If
Next
End If
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
'If _sqlConn.State <> ConnectionState.Open Then
_sqlConn.Open()
'End If
iRet = cmd.ExecuteScalar()
_sqlConn.Close()
Return iRet
End Function
```
---
here's an example of a call:
---
```
params = New Collection
params.Add(SQLClientAccess.instance.sqlParam("@setID", DbType.String, 0,
_editListSetID))
valGrid.hidePKFields = SQLClientAccess.instance.execFunctionReturnsInt
("udf_hiddenCount", params)
```
---
and here's my sqlParam code:
---
```
Friend Function sqlParam(ByVal paramName As String, ByVal dBType As System.Data.DbType, ByVal iSize As Integer, ByVal sVal As String) As SqlParameter
Dim param As SqlParameter
param = New SqlParameter
param.ParameterName = paramName
param.DbType = dBType
param.Size = iSize
param.Value = sVal
Return param
End Function
```
---
HTH |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Sorry, there is no way to run a function directly. Either call it using a sql Text command
```
Public Sub RunFunction(ByVal input As Short)
Using myConnection As New Data.SqlClient.SqlConnection
Using myCommand As New Data.SqlClient.SqlCommand("Select dbo.MyFunction(@MyParam)", myConnection)
myCommand.CommandType = CommandType.Text
myCommand.Parameters.Add(New Data.SqlClient.SqlParameter("@MyParam", input))
myCommand.CommandTimeout = 0
Try
myCommand.ExecuteNonQuery()
Catch ex As Exception
End Try
End Using
End Using
End Sub
```
Or Wrap a procedure round it...
```
Create Procedure RunMyFunction(@MyParam as int)
Select * FROM dbo.MyFunction(@MyParam)
Go
``` | Yes you can call a function directly as demonstrated below.
```
Dim dtaName As New SqlClient.SqlDataAdapter
dtaName.SelectCommand = New SqlClient.SqlCommand
With dtaName.SelectCommand
.CommandTimeout = 60
.Connection = prvcmpINC.cntINC
.CommandType = CommandType.StoredProcedure
.CommandText = "dbo.app_GetName"
.Parameters.AddWithValue("@ParamToPassIn", parstrParamToPassIn)
.Parameters.Add("@intResult", SqlDbType.Int)
.Parameters("@intResult").Direction = ParameterDirection.ReturnValue
End With
dtaName.SelectCommand.ExecuteScalar()
intRuleNo = dtaName.SelectCommand.Parameters("@intResult").Value
``` |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Sorry, there is no way to run a function directly. Either call it using a sql Text command
```
Public Sub RunFunction(ByVal input As Short)
Using myConnection As New Data.SqlClient.SqlConnection
Using myCommand As New Data.SqlClient.SqlCommand("Select dbo.MyFunction(@MyParam)", myConnection)
myCommand.CommandType = CommandType.Text
myCommand.Parameters.Add(New Data.SqlClient.SqlParameter("@MyParam", input))
myCommand.CommandTimeout = 0
Try
myCommand.ExecuteNonQuery()
Catch ex As Exception
End Try
End Using
End Using
End Sub
```
Or Wrap a procedure round it...
```
Create Procedure RunMyFunction(@MyParam as int)
Select * FROM dbo.MyFunction(@MyParam)
Go
``` | This works for me and is based on one of the above answers using a `SqlDataAdapter` (note that you do not need to use one) and `ExecuteScalar` (can use `ExecuteNonQuery` as shown here):
```
bool res = false;
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
using (SqlCommand comm = new SqlCommand("dbo.MyFunction", conn))
{
comm.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("@MyParam", SqlDbType.Int);
// You can call the return value parameter anything, .e.g. "@Result".
SqlParameter p2 = new SqlParameter("@Result", SqlDbType.Bit);
p1.Direction = ParameterDirection.Input;
p2.Direction = ParameterDirection.ReturnValue;
p1.Value = myParamVal;
comm.Parameters.Add(p1);
comm.Parameters.Add(p2);
conn.Open();
comm.ExecuteNonQuery();
if (p2.Value != DBNull.Value)
res = (bool)p2.Value;
}
}
return res;
``` |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Yes you can call a function directly as demonstrated below.
```
Dim dtaName As New SqlClient.SqlDataAdapter
dtaName.SelectCommand = New SqlClient.SqlCommand
With dtaName.SelectCommand
.CommandTimeout = 60
.Connection = prvcmpINC.cntINC
.CommandType = CommandType.StoredProcedure
.CommandText = "dbo.app_GetName"
.Parameters.AddWithValue("@ParamToPassIn", parstrParamToPassIn)
.Parameters.Add("@intResult", SqlDbType.Int)
.Parameters("@intResult").Direction = ParameterDirection.ReturnValue
End With
dtaName.SelectCommand.ExecuteScalar()
intRuleNo = dtaName.SelectCommand.Parameters("@intResult").Value
``` | One of the things about functions is they can return different data types.
I use:
```
Friend Function execFunctionReturnsString(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As String
Dim cmd As SqlCommand
Dim param As SqlParameter
Dim sRet As String
Dim sCmdText As String
Dim iParam As Integer
cmd = New SqlCommand
sCmdText = "select dbo." & funcName & "("
cmd.CommandType = CommandType.Text
cmd.Connection = _sqlConn
cmd.CommandTimeout = 0
If Not params Is Nothing Then
For iParam = 1 To params.Count
param = params(iParam)
sCmdText = sCmdText & param.Value
If iParam < params.Count Then
sCmdText = sCmdText & ","
End If
Next
End If
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
'If _sqlConn.State <> ConnectionState.Open Then
_sqlConn.Open()
'End If
sRet = cmd.ExecuteScalar() & "" ' if null
_sqlConn.Close()
Return sRet
End Function
```
---
```
Friend Function execFunctionReturnsInt(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As Integer
Dim cmd As SqlCommand
Dim param As SqlParameter
Dim iRet As Integer
Dim sCmdText As String
Dim iParam As Integer
cmd = New SqlCommand
sCmdText = "select dbo." & funcName & "("
cmd.CommandType = CommandType.Text
cmd.Connection = _sqlConn
cmd.CommandTimeout = 0
If Not params Is Nothing Then
For iParam = 1 To params.Count
param = params(iParam)
sCmdText = sCmdText & param.Value
If iParam < params.Count Then
sCmdText = sCmdText & ","
End If
Next
End If
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
'If _sqlConn.State <> ConnectionState.Open Then
_sqlConn.Open()
'End If
iRet = cmd.ExecuteScalar()
_sqlConn.Close()
Return iRet
End Function
```
---
here's an example of a call:
---
```
params = New Collection
params.Add(SQLClientAccess.instance.sqlParam("@setID", DbType.String, 0,
_editListSetID))
valGrid.hidePKFields = SQLClientAccess.instance.execFunctionReturnsInt
("udf_hiddenCount", params)
```
---
and here's my sqlParam code:
---
```
Friend Function sqlParam(ByVal paramName As String, ByVal dBType As System.Data.DbType, ByVal iSize As Integer, ByVal sVal As String) As SqlParameter
Dim param As SqlParameter
param = New SqlParameter
param.ParameterName = paramName
param.DbType = dBType
param.Size = iSize
param.Value = sVal
Return param
End Function
```
---
HTH |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This works for me and is based on one of the above answers using a `SqlDataAdapter` (note that you do not need to use one) and `ExecuteScalar` (can use `ExecuteNonQuery` as shown here):
```
bool res = false;
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
using (SqlCommand comm = new SqlCommand("dbo.MyFunction", conn))
{
comm.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("@MyParam", SqlDbType.Int);
// You can call the return value parameter anything, .e.g. "@Result".
SqlParameter p2 = new SqlParameter("@Result", SqlDbType.Bit);
p1.Direction = ParameterDirection.Input;
p2.Direction = ParameterDirection.ReturnValue;
p1.Value = myParamVal;
comm.Parameters.Add(p1);
comm.Parameters.Add(p2);
conn.Open();
comm.ExecuteNonQuery();
if (p2.Value != DBNull.Value)
res = (bool)p2.Value;
}
}
return res;
``` | One of the things about functions is they can return different data types.
I use:
```
Friend Function execFunctionReturnsString(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As String
Dim cmd As SqlCommand
Dim param As SqlParameter
Dim sRet As String
Dim sCmdText As String
Dim iParam As Integer
cmd = New SqlCommand
sCmdText = "select dbo." & funcName & "("
cmd.CommandType = CommandType.Text
cmd.Connection = _sqlConn
cmd.CommandTimeout = 0
If Not params Is Nothing Then
For iParam = 1 To params.Count
param = params(iParam)
sCmdText = sCmdText & param.Value
If iParam < params.Count Then
sCmdText = sCmdText & ","
End If
Next
End If
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
'If _sqlConn.State <> ConnectionState.Open Then
_sqlConn.Open()
'End If
sRet = cmd.ExecuteScalar() & "" ' if null
_sqlConn.Close()
Return sRet
End Function
```
---
```
Friend Function execFunctionReturnsInt(ByVal funcName As String, Optional ByVal params As Collection = Nothing) As Integer
Dim cmd As SqlCommand
Dim param As SqlParameter
Dim iRet As Integer
Dim sCmdText As String
Dim iParam As Integer
cmd = New SqlCommand
sCmdText = "select dbo." & funcName & "("
cmd.CommandType = CommandType.Text
cmd.Connection = _sqlConn
cmd.CommandTimeout = 0
If Not params Is Nothing Then
For iParam = 1 To params.Count
param = params(iParam)
sCmdText = sCmdText & param.Value
If iParam < params.Count Then
sCmdText = sCmdText & ","
End If
Next
End If
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
'If _sqlConn.State <> ConnectionState.Open Then
_sqlConn.Open()
'End If
iRet = cmd.ExecuteScalar()
_sqlConn.Close()
Return iRet
End Function
```
---
here's an example of a call:
---
```
params = New Collection
params.Add(SQLClientAccess.instance.sqlParam("@setID", DbType.String, 0,
_editListSetID))
valGrid.hidePKFields = SQLClientAccess.instance.execFunctionReturnsInt
("udf_hiddenCount", params)
```
---
and here's my sqlParam code:
---
```
Friend Function sqlParam(ByVal paramName As String, ByVal dBType As System.Data.DbType, ByVal iSize As Integer, ByVal sVal As String) As SqlParameter
Dim param As SqlParameter
param = New SqlParameter
param.ParameterName = paramName
param.DbType = dBType
param.Size = iSize
param.Value = sVal
Return param
End Function
```
---
HTH |
1,300,052 | ```
Public Sub cleanTables(ByVal prOKDel As Short)
Dim sqlParams(1) As SqlParameter
Dim sqlProcName As String
sqlProcName = "db.dbo.sp_mySP"
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)
Try
dbConn.SetCommandTimeOut(0)
dbConn.ExecuteNonQuery(CommandType.StoredProcedure, sqlProcName, sqlParams)
Catch ex As Exception
Finally
End Try
End Sub
```
Is there
```
CommandType.StoredProcedure...CommandType.Function
sqlParams(1) = New SqlParameter("@OKDel", prOKDel)...
```
and finally datatable dt = dbConn.Execute(CommandType.StoredProcedure, sqlProcName, sqlParams)
Thanks | 2009/08/19 | [
"https://Stackoverflow.com/questions/1300052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Yes you can call a function directly as demonstrated below.
```
Dim dtaName As New SqlClient.SqlDataAdapter
dtaName.SelectCommand = New SqlClient.SqlCommand
With dtaName.SelectCommand
.CommandTimeout = 60
.Connection = prvcmpINC.cntINC
.CommandType = CommandType.StoredProcedure
.CommandText = "dbo.app_GetName"
.Parameters.AddWithValue("@ParamToPassIn", parstrParamToPassIn)
.Parameters.Add("@intResult", SqlDbType.Int)
.Parameters("@intResult").Direction = ParameterDirection.ReturnValue
End With
dtaName.SelectCommand.ExecuteScalar()
intRuleNo = dtaName.SelectCommand.Parameters("@intResult").Value
``` | This works for me and is based on one of the above answers using a `SqlDataAdapter` (note that you do not need to use one) and `ExecuteScalar` (can use `ExecuteNonQuery` as shown here):
```
bool res = false;
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
using (SqlCommand comm = new SqlCommand("dbo.MyFunction", conn))
{
comm.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("@MyParam", SqlDbType.Int);
// You can call the return value parameter anything, .e.g. "@Result".
SqlParameter p2 = new SqlParameter("@Result", SqlDbType.Bit);
p1.Direction = ParameterDirection.Input;
p2.Direction = ParameterDirection.ReturnValue;
p1.Value = myParamVal;
comm.Parameters.Add(p1);
comm.Parameters.Add(p2);
conn.Open();
comm.ExecuteNonQuery();
if (p2.Value != DBNull.Value)
res = (bool)p2.Value;
}
}
return res;
``` |
1,327,474 | I have executed a code
```
SELECT CASE b.ON_LOAN
when 'Y' then
'In Lib'
when 'N' then
(SELECT c.duedate from book_copy a, book b, loan c
where b.isbn = 123456
and a.isbn = b.isbn
and a.book_no = c.book_no)
END AS Availability, a.isbn, a.class_number
FROM book_copy b, book a
where a.isbn = b.isbn and a.isbn = 123456
```
it returns an error saying subquery returns more than one row . I am trying to get the availability for a book. A book can have more than one copy, that is identified by its book\_no. If a copy is available it should retrun just 'In lib' otherwise, the duedate from loan table. E.g if a book has three copies, 2 out and 1 in lib, i want my query to show all three copies. I think i am missing an outer join. Could you please clarify.
My tables that i use for this are
```
book_copy: book_no, isbn, on_loan
loan: student_id, book_no, duedate,datereturned,loan_id
fk: book_no with book_no in book_copy
book: isbn (pk), title, class
```
thanks,
rk | 2009/08/25 | [
"https://Stackoverflow.com/questions/1327474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The problem is in:
```
(SELECT c.duedate from book_copy a, book b, loan c where b.isbn = 123456 and a.isbn = b.isbn and a.book_no = c.book_no)
```
You actually only want the loan table, but use MAX to make sure it only returns one row.
```
(SELECT MAX(c.duedate) from loan c where a.book_no = c.book_no)
```
So... you can hook into the tables in the outer query - no need to use a and b again.
Rob | I would first get rid of those implied joins. Then I would use a derived table instead of a correlated subquery (Never use a correlated subquery they are performance dogs!)
```
SELECT
CASE b.ON_LOAN
WHEN 'Y' THEN 'In Lib'
WHEN 'N' THEN c.duedate END
AS Availability,
a1.isbn,
a.class_number
FROM book_copy b
JOIN book A1
ON a1.isbn = b.isbn
JOIN (SELECT MIN(c.duedate), c.isbn FROM loan c
join book a
on a.a.isbn = c.isbn
WHERE a.isbn = 123456 AND datereturned is null
GROUP BY c.isbn
) c
ON a1.isbn = c.isbn
WHERE a.isbn = 123456
```
Originally, I used max because you have given us no indciator of how to chosse which of the records in the loan table to pick when you only want one. However, I suspect there is a better way (or at least I hope your design has a better way) to find the book that is out. Maybe you have a field that indicates the book has been returned or maybe you want the date of the first book that is available to be returned not the latest date to be returned. Don't use max without thinking about how to get just one record. Otherwise you may be writing a query that works but it is incorrect in its results. Based on your comment below I have revised the query.
The key to understanding this is that the derived table should bring back the record that has not yet been returned but which should be available soonest (ie it has the earliest due date). If my query doesn't do that, then you will need to experiement until you find one that does. The final where clause may or may not be necessary, you should check that as well. It depends on whether the book numbers are unique or if they are repeated for differnt books. |
4,526,840 | the instructions say: "Consider n and $a\_1<a\_2<...<a\_n$ natural numbers, $n\ge1$. Prove that $$(\sum\_{k=1}^n a\_k)^2 \le \sum\_{k=1}^n a\_k^3$$"
this is how I proceeded:
induction base: n = 1 $\implies a\_1^2 \le a\_1^3$ which is always true, since $a\_1$ is a natural number
inductive hypothesis: I assume $(\sum\_{k=1}^n a\_k)^2 \le \sum\_{k=1}^n a\_k^3$ is true for $n\in\mathbb N$
inductive step: I verify that $(\sum\_{k=1}^{n+1} a\_k)^2 \le \sum\_{k=1}^{n+1} a\_k^3$
$(\sum\_{k=1}^n a\_k + a\_{n+1})^2 \le \sum\_{k=1}^{n} a\_k^3+a\_{n+1}^{3}$
$(\sum\_{k=1}^n a\_k)^2 + a\_{n+1}^2 +2a\_{n+1}\sum\_{k=1}^n a\_k \le \sum\_{k=1}^{n} a\_k^3+a\_{n+1}^3$
$(\sum\_{k=1}^n a\_k)^2 \le \sum\_{k=1}^n a\_k^3$ is the inductive hypothesis, therefore I only have to verify that $a\_{n+1}^2 +2a\_{n+1}\sum\_{k=1}^n a\_k \le a\_{n+1}^3$.
This is where I'm having trouble. anyways, I rewrote the this equation this way:
$2\sum\_{k=1}^n a\_k \le a\_{n+1}^2-a\_{n+1}$
since both quantities on the sides of the inequality are positive numbers, I can raise them to the square:
$(\sum\_{k=1}^n a\_k)^2 \le \frac{a\_{n+1}^4-2a\_{n+1}^3 + a\_{n+1}^2}{4}$
$(\sum\_{k=1}^n a\_k)^2 \le \frac{a\_{n+1}^2(a\_{n+1}^2 -2a\_{n+1}+1}{4}$
$(\sum\_{k=1}^n a\_k)^2 \le \frac{a\_{n+1}^2(a\_{n+1} -1)^2}{4}$
I think I have to somehow prove that
$\frac{a\_{n+1}^2(a\_{n+1} -1)^2}{4} \ge \sum\_{k=1}^n a\_k^3$
but I don't know how. thank you for the help :) | 2022/09/07 | [
"https://math.stackexchange.com/questions/4526840",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1092031/"
] | The reciprocal function $t \mapsto 1/t$ is a decreasing functions on the two separate intervals $(-\infty,0)$ and $(0,\infty$). So, you cannot take reciprocals and reverse inequality sign if your functions not entirely belongs to $(-\infty,0)$ or $(0,\infty)$. For example, it is true that $-2 < 3$ but it is false that $1/3<-1/2$.
So you must distinguish two cases: $0< \sin x \le 1$ or $-1 \le \sin x < 0$. In both cases, we can take reciprocals and get $\frac{1}{\sin x} \le -1$ or $\frac{1}{\sin x} \ge 1$. This is where the "or" come from. | $\frac{1}{\sin(x)}$ is surely not bounded between $0$ and $1$.
You are falling into a pitfall since the inverse function is undefined in $0$, you actually have to apply it twice to both inequalities $-1 \leq \sin(x) \leq 0$ and $0 \leq \sin(x) \leq 1$ to obtain $-1 \geq \frac{1}{\sin(x)} \geq -\infty$ and $1 \geq \frac{1}{\sin(x)} \geq +\infty$ and thus $ \frac{1}{\sin(x)} \in (-\infty, -1] \cup [1, +\infty)$ .
You need to be careful when manipulating inequalities, you can only apply a function on the inequalities if it's well defined on the whole interval (also note that the inverse function is not a decreasing function on $\mathbb{R}^\*$ which is basically what you tried to use). |
15,201,754 | I currently have the following code which transforms the first letter of the surname to uppercase;
```
static string UppercaseFirst(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
```
I now want to edit it so it changes all the letters in the surname to uppercase.
Should be a simple one but my ascx.cs knowledge is dire! :)
thanks | 2013/03/04 | [
"https://Stackoverflow.com/questions/15201754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1396611/"
] | Try [`return s.ToUpper();`](http://msdn.microsoft.com/en-gb/library/ewdd6aed.aspx) or a variant of, [`ToUpperInvariant()`](http://msdn.microsoft.com/en-gb/library/system.string.toupperinvariant.aspx), etc.
There are a number of ways to do this to be 'culturally safe', depending on your requirements. | try this
```
static string UppercaseFirst(string s)
{
return s.ToUpper();
}
``` |
25,147,970 | I'm setting up a PDO connection in a test script:
```
use app\SomeDAO;
class SomeTest extends \PHPUnit_Framework_TestCase
{
protected $db;
public function setUp()
{
$dsn = "mysql:host=localhost;dbname=baseball;user=root;password=root";
$this->db = new PDO($dsn);
}
```
I'm getting an error:
>
> PDOException: SQLSTATE[HY000] [2002] No such file or directory.
>
>
>
How can I use PDO here? | 2014/08/05 | [
"https://Stackoverflow.com/questions/25147970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2396237/"
] | In Unix based (like linux, bsd, or OS X) systems, with MySQL `localhost` is secret code for try-to-use-a-socket, unless a you force it via a protocol flag to not do this (and no one ever does this). Just remember `localhost` usually equals socket file.
If Mysql in your MAMP is running in non-socket mode, you can try replacing the host value with `127.0.0.1` which connects via TCP on via port to the local machine--you'll need to figure out which port it's running on if it's not the default port.
If you look at the MAMP start script
```
less /Applications/MAMP/bin/startMysql.sh
```
You can see if it's starting in socket mode, and what file it's using if it has a config param like:
```
--socket=/Applications/MAMP/tmp/mysql/mysql.sock
```
You can also investigate what open socket mysql might be using by following the answer in this question: [error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'](https://stackoverflow.com/questions/11990708/error-cant-connect-to-local-mysql-server-through-socket-var-run-mysqld-mysq/11990813#11990813)
If you're running in socket mode, you need to make sure PDO knows the path to the socket file. One way to do this is specify the `unix_socket` instead of host in the dsn:
```
$dsn = "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=baseball;user=root;password=root";
``` | I had problem like that at MAMP. My decided it, when I connected with PDO I used next line code:
```
$this->pdo = new \PDO("mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;port=8889;dbname=mydatabase;charset=utf8", 'root', 'root');
``` |
832,850 | I have some images in a Word document that I want to save. However, the 'Save as Picture' option that usually appears when you right-click on an image in Word is not available:

My images are in a table - does this make a difference? I have tried moving them out of the table but the save option still isn't there. | 2014/10/28 | [
"https://superuser.com/questions/832850",
"https://superuser.com",
"https://superuser.com/users/214995/"
] | Based on the inclusion of "Edit Points" in the context menu, I'd say that graphic is [SmartArt](http://www.gcflearnfree.org/word2013/28) and/or a form of Shape, and not just an embedded image.
>
> **Save your picture or SmartArt graphic as a .gif, .png, or .jpg file**
>
>
> You can save a picture or SmartArt graphic in a graphics file format
> such as Graphics Interchange Format (.gif), JPEG File Interchange
> Format (.jpg), or Portable Network Graphics Format (.png).
>
>
> 1. Click the picture or SmartArt graphic that you want to save in a graphics file format.
> 2. On the Home tab, in the Clipboard group, click Copy.
> 3. On the Home tab, in the Clipboard group, click the arrow under Paste, and then click Paste Special.
> 4. In the Paste Special dialog box, in the As list, click Picture (GIF), Picture (PNG), or Picture (JPEG).
> 5. Right-click the graphic, and then click Save as Picture.
> 6. Type a name for your graphic file, browse to the location where you want to save the file, and then click Save.
>
>
>
[Source](http://office.microsoft.com/client/helppreview.aspx?AssetId=HA103374159990&lcid=1033&NS=WINWORD&Version=12&respos=0&queryid=6ebbf378%2D5646%2D4532%2D85fb%2D3801437d0942#_Toc278804436) | You can also save the picture using the following basic steps:
1. Save the document as a webpage 
2. Open the webpage and save the picture,  |
832,850 | I have some images in a Word document that I want to save. However, the 'Save as Picture' option that usually appears when you right-click on an image in Word is not available:

My images are in a table - does this make a difference? I have tried moving them out of the table but the save option still isn't there. | 2014/10/28 | [
"https://superuser.com/questions/832850",
"https://superuser.com",
"https://superuser.com/users/214995/"
] | Based on the inclusion of "Edit Points" in the context menu, I'd say that graphic is [SmartArt](http://www.gcflearnfree.org/word2013/28) and/or a form of Shape, and not just an embedded image.
>
> **Save your picture or SmartArt graphic as a .gif, .png, or .jpg file**
>
>
> You can save a picture or SmartArt graphic in a graphics file format
> such as Graphics Interchange Format (.gif), JPEG File Interchange
> Format (.jpg), or Portable Network Graphics Format (.png).
>
>
> 1. Click the picture or SmartArt graphic that you want to save in a graphics file format.
> 2. On the Home tab, in the Clipboard group, click Copy.
> 3. On the Home tab, in the Clipboard group, click the arrow under Paste, and then click Paste Special.
> 4. In the Paste Special dialog box, in the As list, click Picture (GIF), Picture (PNG), or Picture (JPEG).
> 5. Right-click the graphic, and then click Save as Picture.
> 6. Type a name for your graphic file, browse to the location where you want to save the file, and then click Save.
>
>
>
[Source](http://office.microsoft.com/client/helppreview.aspx?AssetId=HA103374159990&lcid=1033&NS=WINWORD&Version=12&respos=0&queryid=6ebbf378%2D5646%2D4532%2D85fb%2D3801437d0942#_Toc278804436) | The answer provided by @Ƭᴇcʜιᴇ007 is very good, the only thing I would add is that you may also be able to:
1. Ungroup the Object - note, all parts of it will become Selected when you've done this
2. Change your selection so that only the "pure" graphic is selected - this may be awkward, welcome to Word
3. You may now be able to Save as picture - or you may find that a few levels of grouping have been done
I was going to add this as a comment but I can't atm because I don't have enough rep. |
832,850 | I have some images in a Word document that I want to save. However, the 'Save as Picture' option that usually appears when you right-click on an image in Word is not available:

My images are in a table - does this make a difference? I have tried moving them out of the table but the save option still isn't there. | 2014/10/28 | [
"https://superuser.com/questions/832850",
"https://superuser.com",
"https://superuser.com/users/214995/"
] | Based on the inclusion of "Edit Points" in the context menu, I'd say that graphic is [SmartArt](http://www.gcflearnfree.org/word2013/28) and/or a form of Shape, and not just an embedded image.
>
> **Save your picture or SmartArt graphic as a .gif, .png, or .jpg file**
>
>
> You can save a picture or SmartArt graphic in a graphics file format
> such as Graphics Interchange Format (.gif), JPEG File Interchange
> Format (.jpg), or Portable Network Graphics Format (.png).
>
>
> 1. Click the picture or SmartArt graphic that you want to save in a graphics file format.
> 2. On the Home tab, in the Clipboard group, click Copy.
> 3. On the Home tab, in the Clipboard group, click the arrow under Paste, and then click Paste Special.
> 4. In the Paste Special dialog box, in the As list, click Picture (GIF), Picture (PNG), or Picture (JPEG).
> 5. Right-click the graphic, and then click Save as Picture.
> 6. Type a name for your graphic file, browse to the location where you want to save the file, and then click Save.
>
>
>
[Source](http://office.microsoft.com/client/helppreview.aspx?AssetId=HA103374159990&lcid=1033&NS=WINWORD&Version=12&respos=0&queryid=6ebbf378%2D5646%2D4532%2D85fb%2D3801437d0942#_Toc278804436) | easy solution.... use your snipping tool to capture the image then paste it back into the same document...that will then allow you to make it a saved picture by right clicking or save it from within the snip tool to a picture. |
832,850 | I have some images in a Word document that I want to save. However, the 'Save as Picture' option that usually appears when you right-click on an image in Word is not available:

My images are in a table - does this make a difference? I have tried moving them out of the table but the save option still isn't there. | 2014/10/28 | [
"https://superuser.com/questions/832850",
"https://superuser.com",
"https://superuser.com/users/214995/"
] | You can also save the picture using the following basic steps:
1. Save the document as a webpage 
2. Open the webpage and save the picture,  | The answer provided by @Ƭᴇcʜιᴇ007 is very good, the only thing I would add is that you may also be able to:
1. Ungroup the Object - note, all parts of it will become Selected when you've done this
2. Change your selection so that only the "pure" graphic is selected - this may be awkward, welcome to Word
3. You may now be able to Save as picture - or you may find that a few levels of grouping have been done
I was going to add this as a comment but I can't atm because I don't have enough rep. |
832,850 | I have some images in a Word document that I want to save. However, the 'Save as Picture' option that usually appears when you right-click on an image in Word is not available:

My images are in a table - does this make a difference? I have tried moving them out of the table but the save option still isn't there. | 2014/10/28 | [
"https://superuser.com/questions/832850",
"https://superuser.com",
"https://superuser.com/users/214995/"
] | You can also save the picture using the following basic steps:
1. Save the document as a webpage 
2. Open the webpage and save the picture,  | easy solution.... use your snipping tool to capture the image then paste it back into the same document...that will then allow you to make it a saved picture by right clicking or save it from within the snip tool to a picture. |
832,850 | I have some images in a Word document that I want to save. However, the 'Save as Picture' option that usually appears when you right-click on an image in Word is not available:

My images are in a table - does this make a difference? I have tried moving them out of the table but the save option still isn't there. | 2014/10/28 | [
"https://superuser.com/questions/832850",
"https://superuser.com",
"https://superuser.com/users/214995/"
] | The answer provided by @Ƭᴇcʜιᴇ007 is very good, the only thing I would add is that you may also be able to:
1. Ungroup the Object - note, all parts of it will become Selected when you've done this
2. Change your selection so that only the "pure" graphic is selected - this may be awkward, welcome to Word
3. You may now be able to Save as picture - or you may find that a few levels of grouping have been done
I was going to add this as a comment but I can't atm because I don't have enough rep. | easy solution.... use your snipping tool to capture the image then paste it back into the same document...that will then allow you to make it a saved picture by right clicking or save it from within the snip tool to a picture. |
71,307,515 | ```
import Axios from "axios";
import { useEffect, useState } from "react";
function Transactions() {
const [allDetails, setAllDetails] = useState();
const userDetails = JSON.parse(localStorage.getItem('bankDetails'));
const transactons = JSON.parse(userDetails[0].transactions);
useEffect(() => {
Axios.get('http://localhost:3001/transactTo')
.then((res)=>{
setAllDetails(res.data);
})
}, []);
return (
<div className="parent">
<div className="account">
<h1>Transactions</h1>
{transactons.map((value, key1)=>{
return(
<div key={key1} className="transaction">
<div>
{allDetails.map((user, key2)=>{
user.acc_no = parseInt(user.acc_no);
if(user.acc_no === value.to){
return <div key={key2}style={{'background':`url(/${user.image}.png)`}} className="userdp"></div>;
}
})}
{value.amount}||
{value.to || value.from}
</div>
</div>
);
})}
</div>
</div>
);
}
export default Transactions;
```
I'm trying to map an array inside a mapped array and the thing is the second map shows an error `TypeError: Cannot read properties of undefined (reading 'map')`. As soon as I comment the second map of 6 lines and run the code, it runs and again if I remove the comments it again runs properly but doesn't runs in the first render.
Can anyone give a proper solution. I tried [Array.map inside Array.map is not working](https://stackoverflow.com/questions/50590382/array-map-inside-array-map-is-not-working) but it didn't helped. | 2022/03/01 | [
"https://Stackoverflow.com/questions/71307515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17510144/"
] | >
> I want it to only work upon hovering over the + not the text in my button.
>
>
>
The plus, that is actually an arrow, you mean ...?
Currently, the bubbles moving are triggered on hover over the button, by this part:
```
.button{
&_inner{
&:hover .button_spots{ ... }
```
That whole last part `&:hover .button_spots{ /*...*/ }` needs to be triggered by hovering on the `i` icon now, so it a) needs to be moved into `.button{ &_inner{ i.l{ ... }}}`, and b) the selector needs to be modified - currently it just selects `.button_spots` *ancestors* of the button itself, but these elements are not ancestors of the `i` element. So we need to target the `.b_l_quad` *sibling* of the icon first, and then the bubbles inside that:
```
&:hover ~ .b_l_quad .button_spots { ... }
```
Somehow the codepen always messes it up when I try to fork it, but here is the full modified version of your SCSS: <https://pastebin.com/8tTQw9Ru> | Here you can add class to ***svg*** and change the ***button\_inner*** class in your reference code.
or you can wrap svg in an div and trigger hover on it.
This means change ***.button\_inner:hove**r* in that code to ***.hovered:hover***
And dont forget to add ***button\_spots*** divs if you want those dots effect in background.
>
> *Add More* will not shift to side as in the refferece code downloads is in a *span* so it will not affect Add More
>
>
>
```
<button class="bubble-animation">Add more
<svg class='hovered' width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 7L14 7" stroke="#222222" stroke-opacity="0.7" stroke-width="1.5"/>
<path d="M7 14L7 -7.15256e-07" stroke="#222222" stroke-opacity="0.7" stroke-width="1.5"/>
</svg>
</button>
```
or
```
<button class="bubble-animation">Add more
<div class='hovered'>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 7L14 7" stroke="#222222" stroke-opacity="0.7" stroke-width="1.5"/>
<path d="M7 14L7 -7.15256e-07" stroke="#222222" stroke-opacity="0.7" stroke-width="1.5"/>
</svg>
<div class='b_l_quad'>
<div class='button_spots'></div>
<div class='button_spots'></div>
</div
</div>
</button>
```
*2nd option would be better* |
2,226,227 | I realize this may be subjective, so will ask a concrete question, but first, background:
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.
Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.
I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).
Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).
That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".
Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2226227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | In terms of performance, my understanding is that exceptions actually reduce the size and increase the performance of the *normal* execution paths of code, but make the exceptional/error paths more expensive. (often a *lot* more expensive).
So if your only concern is performance, I would say don't worry about later. If today's CPU can handle it, then tomorrows will as well.
*However*. In my opinion, exceptions are one of those features that require programmers to be smarter *all of the time* than programmers can be reasonably be expected to be. So I say - if you *can* stay away from exception based code. Stay away.
Have a look at Raymond Chen's [Cleaner, more elegant, and harder to recognize](https://devblogs.microsoft.com/oldnewthing/20050114-00/?p=36693). He says it better than I could. | I'd say use exceptions appropriately if the runtime environment supports them. Exceptions to handle extraordinary conditions are fine, and can cause little overhead depending on the implementation. Some environments don't support them, especially in the embedded world. If you ban them, be careful to explain why. I once had a guy that, when told not to use exceptions, did a divide by zero instead. Not exactly what we had in mind. |
2,226,227 | I realize this may be subjective, so will ask a concrete question, but first, background:
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.
Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.
I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).
Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).
That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".
Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2226227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | In terms of performance, my understanding is that exceptions actually reduce the size and increase the performance of the *normal* execution paths of code, but make the exceptional/error paths more expensive. (often a *lot* more expensive).
So if your only concern is performance, I would say don't worry about later. If today's CPU can handle it, then tomorrows will as well.
*However*. In my opinion, exceptions are one of those features that require programmers to be smarter *all of the time* than programmers can be reasonably be expected to be. So I say - if you *can* stay away from exception based code. Stay away.
Have a look at Raymond Chen's [Cleaner, more elegant, and harder to recognize](https://devblogs.microsoft.com/oldnewthing/20050114-00/?p=36693). He says it better than I could. | The choice of whether to use exceptions or not should really lie with whether they are going to fit your program's problem domain well or not.
I've used C++ exceptions extensively, both in retrofitting into old C code, and in some newer code. (HINT: Don't try to re-fit 20 year old C code that was written in a low memory environment with all manner of inconsistent exceptions. It's just a nightmare).
If your problem is one that lends itself to handling all the errors in one spot (say, a TCP/IP server of some sort, where every error condition is met with 'break down the connection and try again'), then exceptions are good - you can just throw an exception anywhere and you know where and how it will be handled.
If, on the other hand, your problem doesn't lend itself to central error handling, then exceptions are a ROYAL pain, because trying to figure out where something is (or should be) handled can easily become a Sisyphean task. And it's really hard to see the problem just by looking at the code. You instead have to look at the call trees for a given function and see where that function's exceptions are going to end up, in order to figure out if you have a problem. |
2,226,227 | I realize this may be subjective, so will ask a concrete question, but first, background:
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.
Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.
I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).
Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).
That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".
Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2226227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | In terms of performance, my understanding is that exceptions actually reduce the size and increase the performance of the *normal* execution paths of code, but make the exceptional/error paths more expensive. (often a *lot* more expensive).
So if your only concern is performance, I would say don't worry about later. If today's CPU can handle it, then tomorrows will as well.
*However*. In my opinion, exceptions are one of those features that require programmers to be smarter *all of the time* than programmers can be reasonably be expected to be. So I say - if you *can* stay away from exception based code. Stay away.
Have a look at Raymond Chen's [Cleaner, more elegant, and harder to recognize](https://devblogs.microsoft.com/oldnewthing/20050114-00/?p=36693). He says it better than I could. | The most problem with exceptions -- they don't have predictable time of execution.
Thus they are not suitable for hard real-time applications (and I guess most embedded application doesn't fall in this category).
The second is (possible) increasing of binary's size.
I would propose you reading of [Technical Report on C++ Performance](http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf) which specifically addresses topics that you are interested in: using C++ in embedded (including hard real-time systems) and how exception-handling usually implemented and which overhead it has. |
2,226,227 | I realize this may be subjective, so will ask a concrete question, but first, background:
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.
Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.
I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).
Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).
That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".
Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2226227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | In terms of performance, my understanding is that exceptions actually reduce the size and increase the performance of the *normal* execution paths of code, but make the exceptional/error paths more expensive. (often a *lot* more expensive).
So if your only concern is performance, I would say don't worry about later. If today's CPU can handle it, then tomorrows will as well.
*However*. In my opinion, exceptions are one of those features that require programmers to be smarter *all of the time* than programmers can be reasonably be expected to be. So I say - if you *can* stay away from exception based code. Stay away.
Have a look at Raymond Chen's [Cleaner, more elegant, and harder to recognize](https://devblogs.microsoft.com/oldnewthing/20050114-00/?p=36693). He says it better than I could. | I think the problem is that many people voice their opinion without having a solid understanding of how exception handling in C++ works.
I have recently started at a new company, and there is consensus that we should not use exceptions, because we can't test them, because nondeterministic behaviour, etc etc. All wrong, of course.
When we talk about the overhead of having exception handling used in the code, we need to carefully consider overhead on top of what? Granted it comes at a cost, but that is the cost of alternative? Say we are using return error codes. In such scenario HALF of the if() statements in the source code will be dedicated to testing error codes and forwarding them up the call stack. Not making this up, actual metric of the codebase I'm looking at. And most of it is to deal with a) events that can't pretty much ever happen, like not having memory at the start of an embedded application and b) events that if they actually happen, we can not do anything about anyway, other than shutdown.
In this case introduction of exception handling would significantly reduce complexity of the code, separating handling of rare events from the business as usual logic. And saves ton's of overhead, because the error code checking is happening all the time. Further, it significantly reduces the size of the code. Think how much effort is needed to propagate error codes up the stack through 10 different functions, until we get somewhere where we can officially bail. Using the exception handling you can bypass the 10 intermediary levels of functions, and go straight to where we can deal with it. |
2,226,227 | I realize this may be subjective, so will ask a concrete question, but first, background:
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.
Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.
I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).
Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).
That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".
Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2226227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | The choice of whether to use exceptions or not should really lie with whether they are going to fit your program's problem domain well or not.
I've used C++ exceptions extensively, both in retrofitting into old C code, and in some newer code. (HINT: Don't try to re-fit 20 year old C code that was written in a low memory environment with all manner of inconsistent exceptions. It's just a nightmare).
If your problem is one that lends itself to handling all the errors in one spot (say, a TCP/IP server of some sort, where every error condition is met with 'break down the connection and try again'), then exceptions are good - you can just throw an exception anywhere and you know where and how it will be handled.
If, on the other hand, your problem doesn't lend itself to central error handling, then exceptions are a ROYAL pain, because trying to figure out where something is (or should be) handled can easily become a Sisyphean task. And it's really hard to see the problem just by looking at the code. You instead have to look at the call trees for a given function and see where that function's exceptions are going to end up, in order to figure out if you have a problem. | I'd say use exceptions appropriately if the runtime environment supports them. Exceptions to handle extraordinary conditions are fine, and can cause little overhead depending on the implementation. Some environments don't support them, especially in the embedded world. If you ban them, be careful to explain why. I once had a guy that, when told not to use exceptions, did a divide by zero instead. Not exactly what we had in mind. |
2,226,227 | I realize this may be subjective, so will ask a concrete question, but first, background:
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.
Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.
I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).
Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).
That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".
Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2226227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | The most problem with exceptions -- they don't have predictable time of execution.
Thus they are not suitable for hard real-time applications (and I guess most embedded application doesn't fall in this category).
The second is (possible) increasing of binary's size.
I would propose you reading of [Technical Report on C++ Performance](http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf) which specifically addresses topics that you are interested in: using C++ in embedded (including hard real-time systems) and how exception-handling usually implemented and which overhead it has. | I'd say use exceptions appropriately if the runtime environment supports them. Exceptions to handle extraordinary conditions are fine, and can cause little overhead depending on the implementation. Some environments don't support them, especially in the embedded world. If you ban them, be careful to explain why. I once had a guy that, when told not to use exceptions, did a divide by zero instead. Not exactly what we had in mind. |
2,226,227 | I realize this may be subjective, so will ask a concrete question, but first, background:
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.
Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.
I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).
Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).
That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".
Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2226227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | The choice of whether to use exceptions or not should really lie with whether they are going to fit your program's problem domain well or not.
I've used C++ exceptions extensively, both in retrofitting into old C code, and in some newer code. (HINT: Don't try to re-fit 20 year old C code that was written in a low memory environment with all manner of inconsistent exceptions. It's just a nightmare).
If your problem is one that lends itself to handling all the errors in one spot (say, a TCP/IP server of some sort, where every error condition is met with 'break down the connection and try again'), then exceptions are good - you can just throw an exception anywhere and you know where and how it will be handled.
If, on the other hand, your problem doesn't lend itself to central error handling, then exceptions are a ROYAL pain, because trying to figure out where something is (or should be) handled can easily become a Sisyphean task. And it's really hard to see the problem just by looking at the code. You instead have to look at the call trees for a given function and see where that function's exceptions are going to end up, in order to figure out if you have a problem. | I think the problem is that many people voice their opinion without having a solid understanding of how exception handling in C++ works.
I have recently started at a new company, and there is consensus that we should not use exceptions, because we can't test them, because nondeterministic behaviour, etc etc. All wrong, of course.
When we talk about the overhead of having exception handling used in the code, we need to carefully consider overhead on top of what? Granted it comes at a cost, but that is the cost of alternative? Say we are using return error codes. In such scenario HALF of the if() statements in the source code will be dedicated to testing error codes and forwarding them up the call stack. Not making this up, actual metric of the codebase I'm looking at. And most of it is to deal with a) events that can't pretty much ever happen, like not having memory at the start of an embedded application and b) events that if they actually happen, we can not do anything about anyway, other than shutdown.
In this case introduction of exception handling would significantly reduce complexity of the code, separating handling of rare events from the business as usual logic. And saves ton's of overhead, because the error code checking is happening all the time. Further, it significantly reduces the size of the code. Think how much effort is needed to propagate error codes up the stack through 10 different functions, until we get somewhere where we can officially bail. Using the exception handling you can bypass the 10 intermediary levels of functions, and go straight to where we can deal with it. |
2,226,227 | I realize this may be subjective, so will ask a concrete question, but first, background:
I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.
Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.
I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).
Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).
That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".
Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later? | 2010/02/09 | [
"https://Stackoverflow.com/questions/2226227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | The most problem with exceptions -- they don't have predictable time of execution.
Thus they are not suitable for hard real-time applications (and I guess most embedded application doesn't fall in this category).
The second is (possible) increasing of binary's size.
I would propose you reading of [Technical Report on C++ Performance](http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf) which specifically addresses topics that you are interested in: using C++ in embedded (including hard real-time systems) and how exception-handling usually implemented and which overhead it has. | I think the problem is that many people voice their opinion without having a solid understanding of how exception handling in C++ works.
I have recently started at a new company, and there is consensus that we should not use exceptions, because we can't test them, because nondeterministic behaviour, etc etc. All wrong, of course.
When we talk about the overhead of having exception handling used in the code, we need to carefully consider overhead on top of what? Granted it comes at a cost, but that is the cost of alternative? Say we are using return error codes. In such scenario HALF of the if() statements in the source code will be dedicated to testing error codes and forwarding them up the call stack. Not making this up, actual metric of the codebase I'm looking at. And most of it is to deal with a) events that can't pretty much ever happen, like not having memory at the start of an embedded application and b) events that if they actually happen, we can not do anything about anyway, other than shutdown.
In this case introduction of exception handling would significantly reduce complexity of the code, separating handling of rare events from the business as usual logic. And saves ton's of overhead, because the error code checking is happening all the time. Further, it significantly reduces the size of the code. Think how much effort is needed to propagate error codes up the stack through 10 different functions, until we get somewhere where we can officially bail. Using the exception handling you can bypass the 10 intermediary levels of functions, and go straight to where we can deal with it. |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | If you're on SQL Server 2005 or up, you can use this `FOR XML PATH & STUFF` trick:
```
DECLARE @CodeNameString varchar(100)
SELECT
@CodeNameString = STUFF( (SELECT ',' + CodeName
FROM dbo.AccountCodes
ORDER BY Sort
FOR XML PATH('')),
1, 1, '')
```
The `FOR XML PATH('')` basically concatenates your strings together into one, long XML result (something like `,code1,code2,code3` etc.) and the `STUFF` puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.
**UPDATE:** OK - I understand the comments - if your text in the database table already contains characters like `<`, `>` or `&`, then *my current solution* will in fact encode those into `<`, `>`, and `&`.
If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of **warning** from me: this approach is **a lot more** resource and processing intensive - just so you know. | For SQL Server 2005 and above use [Coalesce](http://msdn.microsoft.com/en-us/library/ms190349.aspx) for `nulls` and I am using [Cast or Convert](http://msdn.microsoft.com/en-us/library/ms187928.aspx) if there are `numeric values` -
```
declare @CodeNameString nvarchar(max)
select @CodeNameString = COALESCE(@CodeNameString + ',', '') + Cast(CodeName as varchar) from AccountCodes ORDER BY Sort
select @CodeNameString
``` |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | ```
DECLARE @CodeNameString varchar(max)
SET @CodeNameString=''
SELECT @CodeNameString=@CodeNameString+CodeName FROM AccountCodes ORDER BY Sort
SELECT @CodeNameString
``` | Here is another real life example that works fine at least with 2008 release (and later).
This is the original query which uses simple `max()` to get at least one of the values:
```
SELECT option_name, Field_M3_name, max(Option_value) AS "Option value", max(Sorting) AS "Sorted"
FROM Value_list group by Option_name, Field_M3_name
ORDER BY option_name, Field_M3_name
```
Improved version, where the main improvement is that we show all values comma separated:
```
SELECT from1.keys, from1.option_name, from1.Field_M3_name,
Stuff((SELECT DISTINCT ', ' + [Option_value] FROM Value_list from2
WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') AS "Option values",
Stuff((SELECT DISTINCT ', ' + CAST([Sorting] AS VARCHAR) FROM Value_list from2
WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') AS "Sorting"
FROM ((SELECT DISTINCT COALESCE(Option_name,'') + '|' + COALESCE(Field_M3_name,'') AS keys, Option_name, Field_M3_name FROM Value_list)
-- WHERE
) from1
ORDER BY keys
```
Note that we have solved all possible `NULL` case issues that I can think of and also we fixed an error that we got for numeric values (field Sorting). |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | @AlexanderMP's answer is correct, but you can also consider handling nulls with `coalesce`:
```
declare @CodeNameString nvarchar(max)
set @CodeNameString = null
SELECT @CodeNameString = Coalesce(@CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes
select @CodeNameString
``` | from msdn Do not use a variable in a SELECT statement to concatenate values (that is, to compute aggregate values). Unexpected query results may occur. This is because all expressions in the SELECT list (including assignments) are not guaranteed to be executed exactly once for each output row
The above seems to say that concatenation as done above is not valid as the assignment might be done more times than there are rows returned by the select |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | For SQL Server 2005 and above use [Coalesce](http://msdn.microsoft.com/en-us/library/ms190349.aspx) for `nulls` and I am using [Cast or Convert](http://msdn.microsoft.com/en-us/library/ms187928.aspx) if there are `numeric values` -
```
declare @CodeNameString nvarchar(max)
select @CodeNameString = COALESCE(@CodeNameString + ',', '') + Cast(CodeName as varchar) from AccountCodes ORDER BY Sort
select @CodeNameString
``` | from msdn Do not use a variable in a SELECT statement to concatenate values (that is, to compute aggregate values). Unexpected query results may occur. This is because all expressions in the SELECT list (including assignments) are not guaranteed to be executed exactly once for each output row
The above seems to say that concatenation as done above is not valid as the assignment might be done more times than there are rows returned by the select |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | @AlexanderMP's answer is correct, but you can also consider handling nulls with `coalesce`:
```
declare @CodeNameString nvarchar(max)
set @CodeNameString = null
SELECT @CodeNameString = Coalesce(@CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes
select @CodeNameString
``` | For SQL Server 2005 and above use [Coalesce](http://msdn.microsoft.com/en-us/library/ms190349.aspx) for `nulls` and I am using [Cast or Convert](http://msdn.microsoft.com/en-us/library/ms187928.aspx) if there are `numeric values` -
```
declare @CodeNameString nvarchar(max)
select @CodeNameString = COALESCE(@CodeNameString + ',', '') + Cast(CodeName as varchar) from AccountCodes ORDER BY Sort
select @CodeNameString
``` |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | If you're on SQL Server 2005 or up, you can use this `FOR XML PATH & STUFF` trick:
```
DECLARE @CodeNameString varchar(100)
SELECT
@CodeNameString = STUFF( (SELECT ',' + CodeName
FROM dbo.AccountCodes
ORDER BY Sort
FOR XML PATH('')),
1, 1, '')
```
The `FOR XML PATH('')` basically concatenates your strings together into one, long XML result (something like `,code1,code2,code3` etc.) and the `STUFF` puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.
**UPDATE:** OK - I understand the comments - if your text in the database table already contains characters like `<`, `>` or `&`, then *my current solution* will in fact encode those into `<`, `>`, and `&`.
If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of **warning** from me: this approach is **a lot more** resource and processing intensive - just so you know. | from msdn Do not use a variable in a SELECT statement to concatenate values (that is, to compute aggregate values). Unexpected query results may occur. This is because all expressions in the SELECT list (including assignments) are not guaranteed to be executed exactly once for each output row
The above seems to say that concatenation as done above is not valid as the assignment might be done more times than there are rows returned by the select |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | @AlexanderMP's answer is correct, but you can also consider handling nulls with `coalesce`:
```
declare @CodeNameString nvarchar(max)
set @CodeNameString = null
SELECT @CodeNameString = Coalesce(@CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes
select @CodeNameString
``` | Here is another real life example that works fine at least with 2008 release (and later).
This is the original query which uses simple `max()` to get at least one of the values:
```
SELECT option_name, Field_M3_name, max(Option_value) AS "Option value", max(Sorting) AS "Sorted"
FROM Value_list group by Option_name, Field_M3_name
ORDER BY option_name, Field_M3_name
```
Improved version, where the main improvement is that we show all values comma separated:
```
SELECT from1.keys, from1.option_name, from1.Field_M3_name,
Stuff((SELECT DISTINCT ', ' + [Option_value] FROM Value_list from2
WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') AS "Option values",
Stuff((SELECT DISTINCT ', ' + CAST([Sorting] AS VARCHAR) FROM Value_list from2
WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') AS "Sorting"
FROM ((SELECT DISTINCT COALESCE(Option_name,'') + '|' + COALESCE(Field_M3_name,'') AS keys, Option_name, Field_M3_name FROM Value_list)
-- WHERE
) from1
ORDER BY keys
```
Note that we have solved all possible `NULL` case issues that I can think of and also we fixed an error that we got for numeric values (field Sorting). |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | ```
DECLARE @CodeNameString varchar(max)
SET @CodeNameString=''
SELECT @CodeNameString=@CodeNameString+CodeName FROM AccountCodes ORDER BY Sort
SELECT @CodeNameString
``` | from msdn Do not use a variable in a SELECT statement to concatenate values (that is, to compute aggregate values). Unexpected query results may occur. This is because all expressions in the SELECT list (including assignments) are not guaranteed to be executed exactly once for each output row
The above seems to say that concatenation as done above is not valid as the assignment might be done more times than there are rows returned by the select |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | If you're on SQL Server 2005 or up, you can use this `FOR XML PATH & STUFF` trick:
```
DECLARE @CodeNameString varchar(100)
SELECT
@CodeNameString = STUFF( (SELECT ',' + CodeName
FROM dbo.AccountCodes
ORDER BY Sort
FOR XML PATH('')),
1, 1, '')
```
The `FOR XML PATH('')` basically concatenates your strings together into one, long XML result (something like `,code1,code2,code3` etc.) and the `STUFF` puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.
**UPDATE:** OK - I understand the comments - if your text in the database table already contains characters like `<`, `>` or `&`, then *my current solution* will in fact encode those into `<`, `>`, and `&`.
If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of **warning** from me: this approach is **a lot more** resource and processing intensive - just so you know. | ```
DECLARE @CodeNameString varchar(max)
SET @CodeNameString=''
SELECT @CodeNameString=@CodeNameString+CodeName FROM AccountCodes ORDER BY Sort
SELECT @CodeNameString
``` |
5,196,371 | I have a sql function that includes this code:
```
DECLARE @CodeNameString varchar(100)
SELECT CodeName FROM AccountCodes ORDER BY Sort
```
I need to concatenate all results from the select query into CodeNameString.
Obviously a FOREACH loop in C# code would do this, but how do I do it in SQL? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5196371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106356/"
] | ```
DECLARE @CodeNameString varchar(max)
SET @CodeNameString=''
SELECT @CodeNameString=@CodeNameString+CodeName FROM AccountCodes ORDER BY Sort
SELECT @CodeNameString
``` | @AlexanderMP's answer is correct, but you can also consider handling nulls with `coalesce`:
```
declare @CodeNameString nvarchar(max)
set @CodeNameString = null
SELECT @CodeNameString = Coalesce(@CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes
select @CodeNameString
``` |
9,121,927 | I'm trying to implement a system where I'll have key-value structure pairs. They will need to be held in some sort of linear manner (that is, they can be indexed), and once given a position can't be moved, so insertions can only append (and there can't really be much sorting.) Just as an example this is what is had in mind:
```
Data list:
0: { "somekey", somevalue }
1: { "someotherkey", someothervalue }
...
n: { "justanotherkey", justanothervalue }
```
I've designed the system like this so that when a key is searched for, it's index can be cached and then accessed with constant time. Now, since I have no way to predict the order or volume of the data, and I can't sort it, I need ideas on algorithms or data structures that would be better than just a linear seach, but still keep the constraints I'd like.
Anyone got any ideas? I doubt I can speed it up much, but every little bit helps since this will be the core of my system. Thanks in advance!
**==EDIT==**
The idea of using two seperate structures (like a hash table and a dynamic array) was actually my first intention. Unfortunately, this won't work for me because I can't seperate the key and the value. The key will be used for errors and messages, so even once an index has been cached, the original key will still be needed to be accessed. Basically they have to just be an array structs, such as:
```
struct Entry {
/* Key is actually a complex struct itself with string, and params */
Key key;
Data* data;
}
``` | 2012/02/03 | [
"https://Stackoverflow.com/questions/9121927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/195701/"
] | One option would be to use a combination of a hash table and a dynamic array. The idea is as follows - whenever you insert an element into the data structure, you append it to a dynamic array, then insert the key into a hash table associated with the index into the dynamic array at which the key/value pair resides. That way, to look up by index, you can just look in the dynamic array, and to look up by name, you look up the index in the hash table, then query at that index. This takes expected O(1) time for insertion, deletion, and access, which is much faster than a linear search.
Hope this helps! | How about a hashtable key -> index in array? |
34,259,034 | I have
the struct:
```
typedef struct Rental {
int nDays;
float kmsDriven;
char carLicensePlate[LICENSE_PLATE_LENGTH+1];
char *clientName;
char chargingCategory;
} Rental;
```
Different -Rental type- structs are stored and accessed via a dynamically allocated array of pointers (here is a part of the project):
```
int main (){
Rental *rentals;
int max_num;
printf("Give a number of rentals you would like to store and manage: ");
scanf("%d", &max_num);
rentals=(Rentals *)malloc(max_num * (sizeof(Rental)))
```
This is what I have thought of so far but I can't understand it completely...so:
1. I'm having trouble understanding how `*rentals` can be an array. I mean shouldn't I declare it at least this way: `Rental *rentals[];`? I know that if I compile the above code I will see an error...but why?
2. I've read numerous posts here in Stack Overflow about doing this with double pointers (`Rental **rentals;`) but the code other people have posted is often very hard for me to read (I don't know all the functions etc. etc.)
3. Let's say I have the object `rentals[0]` which will be a pointer towards `rentals`. If I wanted to pass the struct to a function, should I write:
`variable=function(*arguments*... , Rental *rentals[0]);`? | 2015/12/14 | [
"https://Stackoverflow.com/questions/34259034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5676206/"
] | 1. `rentals` is a pointer, not an array, but it is a pointer to the first (zeroth) element of a block of `max_num` structures, so it can be treated as an array in that you can use `rentals[n]` to refer to the nth element of the array.
2. *This is not a question and hence it is unanswerable.*
>
> 3. Let's say I have the object `rentals[0]` which will be a pointer towards `rentals`. If I wanted to pass the struct to a function, should I write: `variable=function(*arguments*... , Rental *rentals[0]);`?
>
>
>
* `rentals[0]` is not a pointer; it is a `struct Rental` or `Rental`.
* If you want to pass the structure to the function, you write:
```
variable = function(…args…, rentals[0]);
```
If you want to pass a pointer to the structure to the function, you write:
```
variable = function(…args…, &rentals[0]);
```
or:
```
variable = function(…args…, rentals);
```
These pass the same address to the function.
You should be error checking the call to `scanf()` to make sure you got a number, and you should error check the number you got (it should be strictly positive, not zero or negative), and you should error check the value returned by `malloc()`. | When you declare an array (for example `char buffer[10];` the variable is actually pointing to that array. Pointers and arrays are very close together. In fact when you have a pointer where you store an array of data (just like your case with `malloc`) you can do something like `pointer[0]` and `pointer[1]` to get the correct element.
With a pointer in order to access an element you'd normally use `*(pointer +1)` to get the element on position 1, this is exactly the same as `pointer[1]`.
When you want to pass a `struct` in an array, you can either give it by value like this:
```
void function(struct mystruct var)
{
//...
}
int main()
{
struct mystruct var;
function(var);
}
```
Or by reference (passing the address instead of the data - this is ideal if your structs are big in size) :
```
void function(struct mystruct *var)
{
//...
}
int main()
{
struct mystruct var;
function(&var);
}
```
By using an array, you can do it like this (still by reference):
```
void function(struct mystruct *var)
{
//...
}
int main()
{
struct mystruct var[10];
function(&var[0]);
}
```
And using a pointer (to an array) :
```
void function(struct mystruct *var)
{
//...
}
int main()
{
struct mystruct *var;
var = malloc( sizeof(struct mystruct) *10 );
//This will pass the address of the whole array (from position 0)
function(&var);
//This will pass the address of the selected element
function(&var[0]);
}
```
As you can see, declaring an array or a pointer is almost the same, expect that you have to initialize the pointer-array yourself (with `malloc`) and as with anything created with `malloc` you have to `free` it yourself too. |
28,505,540 | A very small amount of my users get a captcha that asks them to copy and paste a code, but it always fails for them - while most of the users get the normal one (checkbox) which goes through correctly.
Googling only returned three instances of people getting that captcha none of which had any valuable information
Any ideas as to why they're getting that captcha and most importantly why does it fail? | 2015/02/13 | [
"https://Stackoverflow.com/questions/28505540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981556/"
] | Why this happens:
=================
This happens when the client has JavaScript disabled. Let's take a look at the following sample code.
### Example code from [reCAPTCHA: Tips and Guidelines](https://developers.google.com/recaptcha/old/docs/tips) API documentation:
```
<script type="text/javascript"
src="https://www.google.com/recaptcha/api/challenge?k=your_public_key">
</script>
<noscript>
<iframe src="https://www.google.com/recaptcha/api/noscript?k=your_public_key"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>
```
As we can see, there are `noscript` tags containing an `iframe`, a `textarea`, and a hidden `input`. When JavaScript is disabled, it will render the contents of the `noscript` tags and it will look something like this.

The `iframe` contains a form where a user can enter the captcha and submit the form, upon which the `iframe` will load a new page containing the response code. Since JavaScript is disabled, the only way to get that token to the parent page's form is to have the user copy-and-paste the token into the `textarea` in the example.
Workaround?:
============
So long as the user correctly copy-and-pastes the token, it should work fine. Double-check that the HTML for the captcha contains the correct fallback elements. You can also disable JavaScript in your browser to test it yourself. | OK, I've run into the same issue. It's very difficult to find any useful information about this online. I did come across this post, though: <https://community.cloudflare.com/t/urgent-problem-with-cloudflare-recaptcha-and-firefox/87307/3>
It has the info that I needed to finally repro the problem reliably: Setting your user agent string to `Firefox/24.0`. (This link tells you how to do that in your browser: <https://www.howtogeek.com/113439/how-to-change-your-browsers-user-agent-without-installing-any-extensions/>
Now the question is: How to solve the problem? When reCaptcha decides to render the "Copy this code and paste it in the empty box below" UI, it seems to deactivate all of the normal JS callbacks that it would normally invoke. It's almost as if reCaptcha "thinks" it's running in a browser that doesn't support JavaScript.
It will still render the `g-recaptcha-response` textarea in the DOM. Usually that textarea is hidden, but in this mode it's visible. It's the "box" that the user should paste the code into.
It seems to be intended to be included in whatever form data you send to your server. Since reCaptcha "thinks" that it's running in a browser that doesn't support JavaScript, it expects you to do the reCaptcha validation on the server.
However, if you still want to react to the user pasting the code into the textarea, you can simply register an event handler for the `input` event on the `g-recaptcha-response` textarea.
```
let captchaTextarea = document.querySelector("textarea[name='g-recaptcha-response']")
if (captchaTextarea) {
captchaTextarea.addEventListener("input", () => {
console.log("Received reCaptcha input: ", captchaTextarea.value)
}, false)
}
```
Something along those lines. |
50,486,175 | I have a json object as below :
```
dataset: Dataset[] = [
{
serviceType: "server Mangemanet",
serviceValues: [
"6.2",
"6.3",
"6.6"
]
},
{
serviceType: "server admin",
serviceValues: [
"4.1",
"4.2",
"4.6"
]
},
];
```
and i have two drop downs so that the value in thesecond one should be displayed based on the value selected in first dropdown . In first drop down i will select the servicetype and in the second dropdown the corresponding service values should appear. iam trying to do it this way :
```
<td>
<select [(ngModel)]="data2" placeholder="select a value" (change)="data2 = dataset[idx];" >
<option *ngFor="let data of dataset;let idx = index;" value= {{dataset[idx].serviceType}} >
{{dataset[idx].serviceType}}
</option>
</select>
</td>
<td>
<select placeholder="select a value" [(ngModel)]="data2" >
<option *ngFor="let data of data2.serviceValues;let idx = index" value= {{data}} >
{{data}}
</option>
</select>
</td>
```
But the error says : **Cannot read property 'serviceValues' of undefined at Object.eval**
I am not able to find why it not able to read service values from the array.
Thanks | 2018/05/23 | [
"https://Stackoverflow.com/questions/50486175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3942142/"
] | Here's a working example:
```
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(){}
data1: any;
data2: any;
dropdown: any[] = []; //the one which will be triggered when first dropdown is selected
dataset: any[] = [
{ serviceType: "server Mangemanet", serviceValues: ["6.2","6.3","6.6"] },
{ serviceType: "server admin", serviceValues: ["4.1","4.2","4.6"] },
];
triggerd2(event: any): void {
this.dropdown = this.dataset.find(item=>{
return item.serviceType == event;
}).serviceValues;
}
}
```
And the html part:
```
<td>
<select [(ngModel)]="data1" placeholder="select a value" (change)="triggerd2($event.target.value)" >
<option *ngFor="let data of dataset;let i = index;" value={{data.serviceType}}>
{{data.serviceType}}
</option>
</select>
</td><br />
<td>
<select placeholder="select a value" [(ngModel)]="data2" >
<option *ngFor="let data of dropdown;let idx = index" value= {{data}} >
{{data}}
</option>
</select>
</td>
```
Try on stackblitz [here](https://stackblitz.com/edit/angular-qkpfmg) | Try Using following code :
You have used `[(ngModel)]="data2"` 2 times. and I have changed `(change)` event as well.
```
<td>
<select [(ngModel)]="data1" placeholder="select a value" (change)="data2 = dataset[$event.target.value];" >
<option *ngFor="let data of dataset;let idx = index;" value= {{idx}}">
{{dataset[idx].serviceType}}
</option>
</select>
</td>
<td *ngIf="data2">
<select placeholder="select a value" [(ngModel)]="data2" >
<option *ngFor="let data of data2.serviceValues;let idx = index" value= {{data}} >
{{data}}
</option>
</select>
</td>
``` |
72,437,145 | Im trying to store/load a dictionary of name: class to/from JSON but its not storing the dictionary variable from the class, just the other ones.
My class has
```
class Test():
a = ''
b = 0.0
c = {}
```
Ive tried using
```
class MyEncoder(json.JSONEncoder):
def default(self, o):
return o.__dict__
```
to encode it but \_\_dict\_\_ only returns the a and b variables. Im essentially doing
```
testDict = {}
test = Test()
testDict['a'] = test
test. a = 'asdf'
test.b = 1.4
test.c['qwert'] = 5
with open('test.json', 'w') as outfile:
output = json.dump(testDict, outfile, indent=3, cls=MyEncoder)
```
and when I try exporting to JSON it just exports everything but the dictionary
```
{
"a": {
"a": "asdf",
"b": 1.4
}
}
```
What do I need to do to export all of each instance of the class in my dictionary? | 2022/05/30 | [
"https://Stackoverflow.com/questions/72437145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8834314/"
] | [@SilverWarior's answer](https://stackoverflow.com/a/72437597/65863) (and [@AndreasRejbrand's comment](https://stackoverflow.com/questions/72437123/72438312#comment127967059_72437597) to it) explains how to convert `TRectF` to `TRect` so you can use it with the `TForm.SetBounds()` method (or `TForm.Bounds` property).
I just want to mention that, along with the `TDisplay.BoundsRect` change from `TRect` to `TRectF`, Delphi 11 also introduced a new [`TForm.SetBoundsF()`](https://docwiki.embarcadero.com/Libraries/en/FMX.Forms.TCommonCustomForm.SetBoundsF) method, and a new [`TForm.BoundsF`](https://docwiki.embarcadero.com/Libraries/en/FMX.Forms.TCommonCustomForm.BoundsF) property, both of which take floating point coordinates via `TRectF` instead of integer coordinates via `TRect`.
So, you don't need to convert the coordinates from floating points to integers at all. You just need to update your code logic to call a different method/property instead, eg:
Pre-D11:
```
MyForm.Bounds := Screen.Displays[index].BoundsRect;
or
MyForm.SetBounds(Screen.Displays[index].BoundsRect);
```
Post-D11:
```
MyForm.BoundsF := Screen.Displays[index].BoundsRect;
or
MyForm.SetBoundsF(Screen.Displays[index].BoundsRect);
``` | The only difference between `TRect` and `TRectF` is that `TRect` is storing its coordinates as integer values while `TRectF` is storing its coordinates as floating point values. So, all you have to do is convert floating point values stored in `TRectF` into integers by doing something like this:
```
Rect.Left := Round(RectF.Left);
Rect.Right := Round(RectF.Right);
Rect.Top := Round(RectF.Top);
Rect.Bottom := Round(RectF.Bottom);
```
NOTE: Based on your case scenario, you might want to use two other rounding methods that are available in the `System.Math` unit: `Floor()` or `Ceil()`. |
25,082,577 | I installed "plugged in" Python as a plug in into Netbeans using from [here](https://blogs.oracle.com/geertjan/entry/python_in_netbeans_ide_8). I was using Eclipse, and even though it was a little wonky, it could at least find Pyserial. Now, when I try to run a project (which worked fine in Eclipse), I get the following error:
```
Traceback (most recent call last):
File "G:\Prog\PythonCurrent\RadioDB\src\radiodb.py", line 8, in <module>
import serial
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1191, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1161, in _load_backward_compatible
File "c:\Python34\lib\site-packages\pyserial-2.7-py3.4-win32.egg\serial\__init__.py", line 19, in <module>
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1191, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1161, in _load_backward_compatible
File "c:\Python34\lib\site-packages\pyserial-2.7-py3.4-win32.egg\serial\serialwin32.py", line 12, in <module>
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2222, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 2164, in _find_spec
File "<frozen importlib._bootstrap>", line 1940, in find_spec
File "<frozen importlib._bootstrap>", line 1916, in _get_spec
File "<frozen importlib._bootstrap>", line 1897, in _legacy_get_spec
File "<frozen importlib._bootstrap>", line 863, in spec_from_loader
File "<frozen importlib._bootstrap>", line 904, in spec_from_file_location
File "c:\Python34\lib\site-packages\pyserial-2.7-py3.4-win32.egg\serial\win32.py", line 196
MAXDWORD = 4294967295L # Variable c_uint
^
SyntaxError: invalid syntax
```
I don't understand why. My `python34\Lib` directory contains `searial`'s stuff, and in `python34\Lib\site-packages` I have the same folder in addition to pyserial's egg and egg-info files. Do I need to specify where these are in Netbeans or copy some folders to Netbeans?
SOLUTION:
=========
Thanks @[Padraic Cunningham](https://stackoverflow.com/users/2141635/padraic-cunningham)
I just like to make sure that the solution is clear for anyone because I have been lost before (like anyone at first).
Sooo, the solution is `use pip3 install pyserial to install for python3`...
I like to make cmd doskey macros, so I'll probably do that, but the easiest thing to install something with "pip3" is go to cmd.exe/terminal and then go to python home directory, then cd to `scripts`; type `pip3.exe install pyserial` or whatever you are installing (you can use `pip3.4.exe...` if you have it) and voila... easiest thing in the world if you know about it. | 2014/08/01 | [
"https://Stackoverflow.com/questions/25082577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3772603/"
] | @PadraicCunningham
---
use `pip3 install pyserial` to install almost major packages. | Pyserial isn't updated to Python 3 yet, it only works in Python 2. So change your interpreter to Python 2.7. |
20,970,846 | I am working with an `android` `TCP` Client `Socket` program which is not responding when it is running in the device. I couldn't find any error in this program please help me to fix this.
**code**
```
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"OOps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
try {
txtText.setText(text.get(0));
Socket client = new Socket("192.168.1.104", 4020); //connect to server
PrintWriter printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(text.get(0)); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing t\e connection
} catch (UnknownHostException e) {
System.out.println("ONE");
e.printStackTrace();
} catch (IOException e) {
System.out.println("TWO");
e.printStackTrace();
}
}
break;
}
}
}
}
```
**Logcat**
```
01-07 17:45:53.367: W/System.err(27224): java.net.SocketException: Permission denied
01-07 17:45:53.414: W/System.err(27224): at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)
01-07 17:45:53.414: W/System.err(27224): at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:335)
01-07 17:45:53.414: W/System.err(27224): at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:216)
01-07 17:45:53.414: W/System.err(27224): at java.net.Socket.startupSocket(Socket.java:717)
01-07 17:45:53.414: W/System.err(27224): at java.net.Socket.tryAllAddresses(Socket.java:150)
01-07 17:45:53.414: W/System.err(27224): at java.net.Socket.<init>(Socket.java:209)
01-07 17:45:53.414: W/System.err(27224): at java.net.Socket.<init>(Socket.java:176)
01-07 17:45:53.414: W/System.err(27224): at net.viralpatel.android.speechtotextdemo.MainActivity.onActivityResult(MainActivity.java:78)
01-07 17:45:53.414: W/System.err(27224): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
01-07 17:45:53.414: W/System.err(27224): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
01-07 17:45:53.414: W/System.err(27224): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2578)
01-07 17:45:53.414: W/System.err(27224): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
01-07 17:45:53.414: W/System.err(27224): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:965)
01-07 17:45:53.414: W/System.err(27224): at android.os.Handler.dispatchMessage(Handler.java:99)
01-07 17:45:53.414: W/System.err(27224): at android.os.Looper.loop(Looper.java:130)
01-07 17:45:53.414: W/System.err(27224): at android.app.ActivityThread.main(ActivityThread.java:3687)
01-07 17:45:53.421: W/System.err(27224): at java.lang.reflect.Method.invokeNative(Native Method)
01-07 17:45:53.421: W/System.err(27224): at java.lang.reflect.Method.invoke(Method.java:507)
01-07 17:45:53.421: W/System.err(27224): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
01-07 17:45:53.421: W/System.err(27224): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
01-07 17:45:53.421: W/System.err(27224): at dalvik.system.NativeStart.main(Native Method)
01-07 17:45:53.437: W/IME_TAG(1510): unbindCurrentClientLocked:: mCurClient.client:com.android.internal.view.IInputMethodClient$Stub$Proxy@409c6758,mCaller.obtainMessageIO(MSG_UNBIND_METHOD, mCurSeq, mCurClient.client):{ what=3000 when=-13h21m11s837ms arg1=719 obj=com.android.internal.view.IInputMethodClient$Stub$Proxy@409c6758 }
01-07 17:45:53.437: W/IME_TAG(1510): unbindCurrentClientLocked:: try
``` | 2014/01/07 | [
"https://Stackoverflow.com/questions/20970846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1611444/"
] | Include network permissions in the manifest and change the `System.out.println`s to `Log.d()` to output to the Logcat. | Better you put your network code inside a seperate thread then start a thread where you want |
8,703,860 | A user enters URLs in a box like this:
1. google.net
2. google.com
I then try to validate / check the URLs, so:
```
function check_input($data) {
$data = trim($data);
$data = mysql_real_escape_string($data);
return $data;
}
```
After validation:
```
$flr_array = explode("\n", $flr_post);
```
So, I can validate each URL. But `mysql_real_escape_string` finds spaces between URLs and adds:
```
<--print_r information-->
google.net\r\ngoogle.com
```
My URLs should and look like these:
1. google.net
2. google.com
How do I remove `\r`, because it breaks everything else?
Is there a better way to validate URLs?
Tried with `str_replace`, but no luck. | 2012/01/02 | [
"https://Stackoverflow.com/questions/8703860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608491/"
] | The best way to validate URLs is to use PHP's [`filter_var()`*docs*](http://us2.php.net/manual/en/function.filter-var.php) function like so:
```
if( ! filter_var($url, FILTER_VALIDATE_URL))) {
echo 'BAD URL';
} else {
echo 'GOOD_URL';
}
``` | Use preg\_split instead,
```
$parts = preg_split('/[\n\r]+/', $data);
```
That'll split anywhere there's one or more \n or \r.
What are you doing the mysql\_real\_escape\_string for? Is this intended for a database later on? Don't do an escaping BEFORE you do other processing. That processing can break the escaping m\_r\_e\_s() does and still leave you vulnerable to sql injection.
m\_r\_e\_s() MUST be the LAST thing you do to a string before it's used in an sql query string. |
8,703,860 | A user enters URLs in a box like this:
1. google.net
2. google.com
I then try to validate / check the URLs, so:
```
function check_input($data) {
$data = trim($data);
$data = mysql_real_escape_string($data);
return $data;
}
```
After validation:
```
$flr_array = explode("\n", $flr_post);
```
So, I can validate each URL. But `mysql_real_escape_string` finds spaces between URLs and adds:
```
<--print_r information-->
google.net\r\ngoogle.com
```
My URLs should and look like these:
1. google.net
2. google.com
How do I remove `\r`, because it breaks everything else?
Is there a better way to validate URLs?
Tried with `str_replace`, but no luck. | 2012/01/02 | [
"https://Stackoverflow.com/questions/8703860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608491/"
] | Thats where difference between single and double quotes comes into picture:
```
$flr_array = explode('\r\n', $flr_post);
``` | Use preg\_split instead,
```
$parts = preg_split('/[\n\r]+/', $data);
```
That'll split anywhere there's one or more \n or \r.
What are you doing the mysql\_real\_escape\_string for? Is this intended for a database later on? Don't do an escaping BEFORE you do other processing. That processing can break the escaping m\_r\_e\_s() does and still leave you vulnerable to sql injection.
m\_r\_e\_s() MUST be the LAST thing you do to a string before it's used in an sql query string. |
8,703,860 | A user enters URLs in a box like this:
1. google.net
2. google.com
I then try to validate / check the URLs, so:
```
function check_input($data) {
$data = trim($data);
$data = mysql_real_escape_string($data);
return $data;
}
```
After validation:
```
$flr_array = explode("\n", $flr_post);
```
So, I can validate each URL. But `mysql_real_escape_string` finds spaces between URLs and adds:
```
<--print_r information-->
google.net\r\ngoogle.com
```
My URLs should and look like these:
1. google.net
2. google.com
How do I remove `\r`, because it breaks everything else?
Is there a better way to validate URLs?
Tried with `str_replace`, but no luck. | 2012/01/02 | [
"https://Stackoverflow.com/questions/8703860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608491/"
] | The best way to validate URLs is to use PHP's [`filter_var()`*docs*](http://us2.php.net/manual/en/function.filter-var.php) function like so:
```
if( ! filter_var($url, FILTER_VALIDATE_URL))) {
echo 'BAD URL';
} else {
echo 'GOOD_URL';
}
``` | You should use regular expressions to validate URL's in your $flr\_array.
With [preg\_match()](http://php.net/manual/en/function.preg-match.php), if there is a match it it will fill the $matches variable with results (if you provided it in your function call). This is what php.net has to say about it:
"If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1](http://php.net/manual/en/function.preg-match.php) will have the text that matched the first captured parenthesized subpattern, and so on." |
8,703,860 | A user enters URLs in a box like this:
1. google.net
2. google.com
I then try to validate / check the URLs, so:
```
function check_input($data) {
$data = trim($data);
$data = mysql_real_escape_string($data);
return $data;
}
```
After validation:
```
$flr_array = explode("\n", $flr_post);
```
So, I can validate each URL. But `mysql_real_escape_string` finds spaces between URLs and adds:
```
<--print_r information-->
google.net\r\ngoogle.com
```
My URLs should and look like these:
1. google.net
2. google.com
How do I remove `\r`, because it breaks everything else?
Is there a better way to validate URLs?
Tried with `str_replace`, but no luck. | 2012/01/02 | [
"https://Stackoverflow.com/questions/8703860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608491/"
] | The best way to validate URLs is to use PHP's [`filter_var()`*docs*](http://us2.php.net/manual/en/function.filter-var.php) function like so:
```
if( ! filter_var($url, FILTER_VALIDATE_URL))) {
echo 'BAD URL';
} else {
echo 'GOOD_URL';
}
``` | You can use : nl2br() — Inserts HTML line breaks before all newlines in a string
Example :
```
<?php
echo nl2br("Welcome\r\nThis is my HTML document");
?>
```
Output :
```
Welcome<br />
This is my HTML document
```
Source : <http://php.net/manual/en/function.nl2br.php> |
8,703,860 | A user enters URLs in a box like this:
1. google.net
2. google.com
I then try to validate / check the URLs, so:
```
function check_input($data) {
$data = trim($data);
$data = mysql_real_escape_string($data);
return $data;
}
```
After validation:
```
$flr_array = explode("\n", $flr_post);
```
So, I can validate each URL. But `mysql_real_escape_string` finds spaces between URLs and adds:
```
<--print_r information-->
google.net\r\ngoogle.com
```
My URLs should and look like these:
1. google.net
2. google.com
How do I remove `\r`, because it breaks everything else?
Is there a better way to validate URLs?
Tried with `str_replace`, but no luck. | 2012/01/02 | [
"https://Stackoverflow.com/questions/8703860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608491/"
] | Thats where difference between single and double quotes comes into picture:
```
$flr_array = explode('\r\n', $flr_post);
``` | You should use regular expressions to validate URL's in your $flr\_array.
With [preg\_match()](http://php.net/manual/en/function.preg-match.php), if there is a match it it will fill the $matches variable with results (if you provided it in your function call). This is what php.net has to say about it:
"If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1](http://php.net/manual/en/function.preg-match.php) will have the text that matched the first captured parenthesized subpattern, and so on." |
8,703,860 | A user enters URLs in a box like this:
1. google.net
2. google.com
I then try to validate / check the URLs, so:
```
function check_input($data) {
$data = trim($data);
$data = mysql_real_escape_string($data);
return $data;
}
```
After validation:
```
$flr_array = explode("\n", $flr_post);
```
So, I can validate each URL. But `mysql_real_escape_string` finds spaces between URLs and adds:
```
<--print_r information-->
google.net\r\ngoogle.com
```
My URLs should and look like these:
1. google.net
2. google.com
How do I remove `\r`, because it breaks everything else?
Is there a better way to validate URLs?
Tried with `str_replace`, but no luck. | 2012/01/02 | [
"https://Stackoverflow.com/questions/8703860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608491/"
] | Thats where difference between single and double quotes comes into picture:
```
$flr_array = explode('\r\n', $flr_post);
``` | You can use : nl2br() — Inserts HTML line breaks before all newlines in a string
Example :
```
<?php
echo nl2br("Welcome\r\nThis is my HTML document");
?>
```
Output :
```
Welcome<br />
This is my HTML document
```
Source : <http://php.net/manual/en/function.nl2br.php> |
58,955,036 | I am developing an android app which is able to search for users and also restaurants. So I am using a custom adapter to handles two types of items. The objects I need to display are User and Eateries. And the objects require completely different layouts to display them.
Here is my SearchingFragment which contains the adapter:
```
public class SearchingFragment extends Fragment {
private SearchView searchView;
private RecyclerView resultList;
private RecyclerView.Adapter<RecyclerView.ViewHolder> adapter;
final int VIEW_TYPE_USER = 0;
final int VIEW_TYPE_EATERIES = 1;
private ArrayList<User> userArrayList = new ArrayList<User>();
private ArrayList<Eateries2> eateriesArrayList = new ArrayList<Eateries2>();
FirebaseFirestore db = FirebaseFirestore.getInstance();
String TAG;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void OnItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_searching, container, false);
//return inflater.inflate(R.layout.fragment_searching, container, false);
searchView = root.findViewById(R.id.searchView);
resultList = root.findViewById(R.id.resultList);
resultList.setHasFixedSize(true);
resultList.setLayoutManager(new LinearLayoutManager(getActivity()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if(newText.trim().isEmpty()){
userArrayList = new ArrayList<>();
eateriesArrayList = new ArrayList<>();
}
else {
userArrayList = new ArrayList<>();
eateriesArrayList = new ArrayList<>();
FirestoreUserSearch(newText);
}
return false;
}
});
return root;
}
private void FirestoreUserSearch(String searchText) {
db.collection("users")
.orderBy("username")
.startAt(searchText)
.endAt(searchText + "\uf8ff")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(DocumentChange document :queryDocumentSnapshots.getDocumentChanges()){
userArrayList.add(document.getDocument().toObject(User.class));
adapter.notifyDataSetChanged();
}
}
});
db.collection("eateries")
.orderBy("placeName")
.startAt(searchText)
.endAt(searchText + "\uf8ff")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()){
String placeId = doc.getDocument().getString("placeID");
String placeName = doc.getDocument().getString("placeName");
List<String> category = (List<String>)doc.getDocument().get("category");
String address = doc.getDocument().getString("address");
Double rating = doc.getDocument().getDouble("rating");
Double price_level = doc.getDocument().getDouble("price_level");
Eateries2 eateries = new Eateries2(address, category, placeId, placeName, rating, price_level);
eateriesArrayList.add(eateries);
adapter.notifyDataSetChanged();
}
}
});
adapter = new RecyclerView.Adapter<RecyclerView.ViewHolder>() {
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view;
if (viewType==VIEW_TYPE_USER){
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.user_list_layout,parent,false);
return new SearchingFragment.UserViewHolder(view);
}
if(viewType==VIEW_TYPE_EATERIES){
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.eateries_list_layout,parent,false);
return new SearchingFragment.EateriesViewHolder(view,mListener);
}
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof SearchingFragment.UserViewHolder){
((SearchingFragment.UserViewHolder) holder).userName.setText(userArrayList.get(position).getUsername());
((SearchingFragment.UserViewHolder) holder).category.setText("User");
((SearchingFragment.UserViewHolder) holder).userImage.setImageURI(null);
if(userArrayList.get(position).getPhoto()!=null){
Uri uri=Uri.parse(userArrayList.get(position).getPhoto());
Glide.with(getContext()).load(uri).into(((SearchingFragment.UserViewHolder) holder).userImage);
}
}
if(holder instanceof SearchingFragment.EateriesViewHolder){
((SearchingFragment.EateriesViewHolder) holder).placeName.setText(eateriesArrayList.get(position-userArrayList.size()).getPlaceName());
((SearchingFragment.EateriesViewHolder) holder).category.setText("Eatery\n"+eateriesArrayList.get(position-userArrayList.size()).getCategory());
((SearchingFragment.EateriesViewHolder) holder).address.setText(Html.fromHtml(eateriesArrayList.get(position-userArrayList.size()).getAddress()));
((EateriesViewHolder) holder).ratingBar.setRating(Float.parseFloat(eateriesArrayList.get(position-userArrayList.size()).getRating().toString()));
((EateriesViewHolder) holder).ratingBar.setIsIndicator(true);
((EateriesViewHolder) holder).priceRateBar.setRating(Float.parseFloat(eateriesArrayList.get(position-userArrayList.size()).getPrice_level().toString()));
List<Place.Field> fields = Arrays.asList(Place.Field.PHOTO_METADATAS);
FetchPlaceRequest placeRequest = FetchPlaceRequest.newInstance(eateriesArrayList.get(position-userArrayList.size()).getPlaceID(), fields);
String api = "AIzaSyDz5BGny6Lsp7gW-uJznoLVZS4riEdfnF0";
Places.initialize(getContext(), api);
PlacesClient placesClient = Places.createClient(getContext());
placesClient.fetchPlace(placeRequest).addOnSuccessListener((response) -> {
Place place = response.getPlace();
PhotoMetadata photoMetadata = place.getPhotoMetadatas().get(0);
String attributions = photoMetadata.getAttributions();
FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(photoMetadata)
.build();
placesClient.fetchPhoto(photoRequest).addOnSuccessListener((fetchPhotoResponse) -> {
Bitmap bitmap = fetchPhotoResponse.getBitmap();
((SearchingFragment.EateriesViewHolder) holder).eateryImage.setImageBitmap(bitmap);
// imageView.setImageBitmap(bitmap);
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
int statusCode = apiException.getStatusCode();
// Handle error with given status code.
Log.e(TAG, "Place not found: " + exception.getMessage());
}
});
});
}
}
@Override
public int getItemCount() {
return userArrayList.size()+eateriesArrayList.size();
}
@Override
public int getItemViewType(int position){
if(position<userArrayList.size()){
return VIEW_TYPE_USER;
}
if(position-userArrayList.size()<eateriesArrayList.size()){
return VIEW_TYPE_EATERIES;
}
return -1;
}
};
resultList.setAdapter(adapter);
}
private class UserViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView userImage;
TextView category;
UserViewHolder(View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.userName);
userImage = itemView.findViewById(R.id.userImage);
category = itemView.findViewById(R.id.catagory);
}
}
private class EateriesViewHolder extends RecyclerView.ViewHolder{
TextView placeName;
TextView category;
TextView address;
ImageView eateryImage;
RatingBar ratingBar,priceRateBar;
EateriesViewHolder(View itemView,OnItemClickListener listener){
super(itemView);
placeName = itemView.findViewById(R.id.placeName);
category = itemView.findViewById(R.id.catagory);
address = itemView.findViewById(R.id.address);
eateryImage = itemView.findViewById(R.id.eateryImage);
ratingBar = itemView.findViewById(R.id.ratingBar);
priceRateBar = itemView.findViewById(R.id.priceRateBar);
}
}
```
So, how can I set different OnClickListener for my adapter? Much appreciate. | 2019/11/20 | [
"https://Stackoverflow.com/questions/58955036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12403885/"
] | i : First Way
```
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if([this method is Override method]getItemViewType(position) == VIEW_TYPE_USER){
// here USER logic
}else{
// here EATERIES logic
}
}
});
```
II ) Second Way
```
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof SearchingFragment.UserViewHolder){
((SearchingFragment.UserViewHolder) holder).userName.setText(userArrayList.get(position).getUsername());
((SearchingFragment.UserViewHolder) holder).category.setText("User");
((SearchingFragment.UserViewHolder) holder).userImage.setImageURI(null);
if(userArrayList.get(position).getPhoto()!=null){
Uri uri=Uri.parse(userArrayList.get(position).getPhoto());
Glide.with(getContext()).load(uri).into(((SearchingFragment.UserViewHolder) holder).userImage);
}
((SearchingFragment.UserViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
if(holder instanceof SearchingFragment.EateriesViewHolder){
((SearchingFragment.EateriesViewHolder) holder).placeName.setText(eateriesArrayList.get(position-userArrayList.size()).getPlaceName());
((SearchingFragment.EateriesViewHolder) holder).category.setText("Eatery\n"+eateriesArrayList.get(position-userArrayList.size()).getCategory());
((SearchingFragment.EateriesViewHolder) holder).address.setText(Html.fromHtml(eateriesArrayList.get(position-userArrayList.size()).getAddress()));
((EateriesViewHolder) holder).ratingBar.setRating(Float.parseFloat(eateriesArrayList.get(position-userArrayList.size()).getRating().toString()));
((EateriesViewHolder) holder).ratingBar.setIsIndicator(true);
((EateriesViewHolder) holder).priceRateBar.setRating(Float.parseFloat(eateriesArrayList.get(position-userArrayList.size()).getPrice_level().toString()));
List<Place.Field> fields = Arrays.asList(Place.Field.PHOTO_METADATAS);
FetchPlaceRequest placeRequest = FetchPlaceRequest.newInstance(eateriesArrayList.get(position-userArrayList.size()).getPlaceID(), fields);
String api = "AIzaSyDz5BGny6Lsp7gW-uJznoLVZS4riEdfnF0";
Places.initialize(getContext(), api);
PlacesClient placesClient = Places.createClient(getContext());
placesClient.fetchPlace(placeRequest).addOnSuccessListener((response) -> {
Place place = response.getPlace();
PhotoMetadata photoMetadata = place.getPhotoMetadatas().get(0);
String attributions = photoMetadata.getAttributions();
FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(photoMetadata)
.build();
placesClient.fetchPhoto(photoRequest).addOnSuccessListener((fetchPhotoResponse) -> {
Bitmap bitmap = fetchPhotoResponse.getBitmap();
((SearchingFragment.EateriesViewHolder) holder).eateryImage.setImageBitmap(bitmap);
// imageView.setImageBitmap(bitmap);
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
int statusCode = apiException.getStatusCode();
// Handle error with given status code.
Log.e(TAG, "Place not found: " + exception.getMessage());
}
});
});
((SearchingFragment.EateriesViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
}
}
``` | **Update your ViewHolders Like given below**
```
private class UserViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView userImage;
TextView category;
UserViewHolder(View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.userName);
userImage = itemView.findViewById(R.id.userImage);
category = itemView.findViewById(R.id.catagory);
// set Click Listener of whole item view or your desired view
itemView.setOnClickListener(view -> {
User user = userArrayList.get(getAdapterPosition());
// do whatever you want to
});
}
}
private class EateriesViewHolder extends RecyclerView.ViewHolder {
TextView placeName;
TextView category;
TextView address;
ImageView eateryImage;
RatingBar ratingBar, priceRateBar;
EateriesViewHolder(View itemView) {
super(itemView);
placeName = itemView.findViewById(R.id.placeName);
category = itemView.findViewById(R.id.catagory);
address = itemView.findViewById(R.id.address);
eateryImage = itemView.findViewById(R.id.eateryImage);
ratingBar = itemView.findViewById(R.id.ratingBar);
priceRateBar = itemView.findViewById(R.id.priceRateBar);
// set Click Listener of whole item view or your desired view
itemView.setOnClickListener(view -> {
Eateries2 Eateries2 = eateriesArrayList.get(getAdapterPosition());
// do whatever you want to
});
}
}
``` |
58,955,036 | I am developing an android app which is able to search for users and also restaurants. So I am using a custom adapter to handles two types of items. The objects I need to display are User and Eateries. And the objects require completely different layouts to display them.
Here is my SearchingFragment which contains the adapter:
```
public class SearchingFragment extends Fragment {
private SearchView searchView;
private RecyclerView resultList;
private RecyclerView.Adapter<RecyclerView.ViewHolder> adapter;
final int VIEW_TYPE_USER = 0;
final int VIEW_TYPE_EATERIES = 1;
private ArrayList<User> userArrayList = new ArrayList<User>();
private ArrayList<Eateries2> eateriesArrayList = new ArrayList<Eateries2>();
FirebaseFirestore db = FirebaseFirestore.getInstance();
String TAG;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void OnItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_searching, container, false);
//return inflater.inflate(R.layout.fragment_searching, container, false);
searchView = root.findViewById(R.id.searchView);
resultList = root.findViewById(R.id.resultList);
resultList.setHasFixedSize(true);
resultList.setLayoutManager(new LinearLayoutManager(getActivity()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if(newText.trim().isEmpty()){
userArrayList = new ArrayList<>();
eateriesArrayList = new ArrayList<>();
}
else {
userArrayList = new ArrayList<>();
eateriesArrayList = new ArrayList<>();
FirestoreUserSearch(newText);
}
return false;
}
});
return root;
}
private void FirestoreUserSearch(String searchText) {
db.collection("users")
.orderBy("username")
.startAt(searchText)
.endAt(searchText + "\uf8ff")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(DocumentChange document :queryDocumentSnapshots.getDocumentChanges()){
userArrayList.add(document.getDocument().toObject(User.class));
adapter.notifyDataSetChanged();
}
}
});
db.collection("eateries")
.orderBy("placeName")
.startAt(searchText)
.endAt(searchText + "\uf8ff")
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()){
String placeId = doc.getDocument().getString("placeID");
String placeName = doc.getDocument().getString("placeName");
List<String> category = (List<String>)doc.getDocument().get("category");
String address = doc.getDocument().getString("address");
Double rating = doc.getDocument().getDouble("rating");
Double price_level = doc.getDocument().getDouble("price_level");
Eateries2 eateries = new Eateries2(address, category, placeId, placeName, rating, price_level);
eateriesArrayList.add(eateries);
adapter.notifyDataSetChanged();
}
}
});
adapter = new RecyclerView.Adapter<RecyclerView.ViewHolder>() {
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view;
if (viewType==VIEW_TYPE_USER){
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.user_list_layout,parent,false);
return new SearchingFragment.UserViewHolder(view);
}
if(viewType==VIEW_TYPE_EATERIES){
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.eateries_list_layout,parent,false);
return new SearchingFragment.EateriesViewHolder(view,mListener);
}
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof SearchingFragment.UserViewHolder){
((SearchingFragment.UserViewHolder) holder).userName.setText(userArrayList.get(position).getUsername());
((SearchingFragment.UserViewHolder) holder).category.setText("User");
((SearchingFragment.UserViewHolder) holder).userImage.setImageURI(null);
if(userArrayList.get(position).getPhoto()!=null){
Uri uri=Uri.parse(userArrayList.get(position).getPhoto());
Glide.with(getContext()).load(uri).into(((SearchingFragment.UserViewHolder) holder).userImage);
}
}
if(holder instanceof SearchingFragment.EateriesViewHolder){
((SearchingFragment.EateriesViewHolder) holder).placeName.setText(eateriesArrayList.get(position-userArrayList.size()).getPlaceName());
((SearchingFragment.EateriesViewHolder) holder).category.setText("Eatery\n"+eateriesArrayList.get(position-userArrayList.size()).getCategory());
((SearchingFragment.EateriesViewHolder) holder).address.setText(Html.fromHtml(eateriesArrayList.get(position-userArrayList.size()).getAddress()));
((EateriesViewHolder) holder).ratingBar.setRating(Float.parseFloat(eateriesArrayList.get(position-userArrayList.size()).getRating().toString()));
((EateriesViewHolder) holder).ratingBar.setIsIndicator(true);
((EateriesViewHolder) holder).priceRateBar.setRating(Float.parseFloat(eateriesArrayList.get(position-userArrayList.size()).getPrice_level().toString()));
List<Place.Field> fields = Arrays.asList(Place.Field.PHOTO_METADATAS);
FetchPlaceRequest placeRequest = FetchPlaceRequest.newInstance(eateriesArrayList.get(position-userArrayList.size()).getPlaceID(), fields);
String api = "AIzaSyDz5BGny6Lsp7gW-uJznoLVZS4riEdfnF0";
Places.initialize(getContext(), api);
PlacesClient placesClient = Places.createClient(getContext());
placesClient.fetchPlace(placeRequest).addOnSuccessListener((response) -> {
Place place = response.getPlace();
PhotoMetadata photoMetadata = place.getPhotoMetadatas().get(0);
String attributions = photoMetadata.getAttributions();
FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(photoMetadata)
.build();
placesClient.fetchPhoto(photoRequest).addOnSuccessListener((fetchPhotoResponse) -> {
Bitmap bitmap = fetchPhotoResponse.getBitmap();
((SearchingFragment.EateriesViewHolder) holder).eateryImage.setImageBitmap(bitmap);
// imageView.setImageBitmap(bitmap);
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
int statusCode = apiException.getStatusCode();
// Handle error with given status code.
Log.e(TAG, "Place not found: " + exception.getMessage());
}
});
});
}
}
@Override
public int getItemCount() {
return userArrayList.size()+eateriesArrayList.size();
}
@Override
public int getItemViewType(int position){
if(position<userArrayList.size()){
return VIEW_TYPE_USER;
}
if(position-userArrayList.size()<eateriesArrayList.size()){
return VIEW_TYPE_EATERIES;
}
return -1;
}
};
resultList.setAdapter(adapter);
}
private class UserViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView userImage;
TextView category;
UserViewHolder(View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.userName);
userImage = itemView.findViewById(R.id.userImage);
category = itemView.findViewById(R.id.catagory);
}
}
private class EateriesViewHolder extends RecyclerView.ViewHolder{
TextView placeName;
TextView category;
TextView address;
ImageView eateryImage;
RatingBar ratingBar,priceRateBar;
EateriesViewHolder(View itemView,OnItemClickListener listener){
super(itemView);
placeName = itemView.findViewById(R.id.placeName);
category = itemView.findViewById(R.id.catagory);
address = itemView.findViewById(R.id.address);
eateryImage = itemView.findViewById(R.id.eateryImage);
ratingBar = itemView.findViewById(R.id.ratingBar);
priceRateBar = itemView.findViewById(R.id.priceRateBar);
}
}
```
So, how can I set different OnClickListener for my adapter? Much appreciate. | 2019/11/20 | [
"https://Stackoverflow.com/questions/58955036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12403885/"
] | **You can use interface for different on click listener**
you can create interface class
```
public interface ICallback {
public void onItemClick(int pos);
```
}
then call interface class on adapter and click on item click
```
holder.textview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iCallback.onItemClick(position);
}
});
```
after final call interface class in activity or fragment
```
iCallback = new ICallback() {
@Override
public void onItemClick(int pos) {
Intent intent = new Intent(HomeActivity.this,SecondActivity.class);
startActivity(intent);
}
};
``` | **Update your ViewHolders Like given below**
```
private class UserViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView userImage;
TextView category;
UserViewHolder(View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.userName);
userImage = itemView.findViewById(R.id.userImage);
category = itemView.findViewById(R.id.catagory);
// set Click Listener of whole item view or your desired view
itemView.setOnClickListener(view -> {
User user = userArrayList.get(getAdapterPosition());
// do whatever you want to
});
}
}
private class EateriesViewHolder extends RecyclerView.ViewHolder {
TextView placeName;
TextView category;
TextView address;
ImageView eateryImage;
RatingBar ratingBar, priceRateBar;
EateriesViewHolder(View itemView) {
super(itemView);
placeName = itemView.findViewById(R.id.placeName);
category = itemView.findViewById(R.id.catagory);
address = itemView.findViewById(R.id.address);
eateryImage = itemView.findViewById(R.id.eateryImage);
ratingBar = itemView.findViewById(R.id.ratingBar);
priceRateBar = itemView.findViewById(R.id.priceRateBar);
// set Click Listener of whole item view or your desired view
itemView.setOnClickListener(view -> {
Eateries2 Eateries2 = eateriesArrayList.get(getAdapterPosition());
// do whatever you want to
});
}
}
``` |
19,730,773 | I've got the following code snippet which currently removes everything in my temp directory and re-adds a new temp directory.
```
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\WINDOWS\Temp\*'
remove-item $dir -force -recurse
if($?){new-item -path "\\$server\admin$\Temp" -Type Directory}
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp\*'
remove-item $dir -force -recurse
if($?){New-Item -Path "\\$server\admin$\Temp" -Type Directory}
}
```
I'm trying to slightly alter the code to where it will no longer delete the temp directory and instead simply remove all of the contents inside of temp. I added `\*` at the end of my `$dir` variable so that it tries to get all of the items inside of temp rather than deleting Temp itself. When I run this however I'm not deleting anything. What is wrong with my code? | 2013/11/01 | [
"https://Stackoverflow.com/questions/19730773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1451575/"
] | This works for me, so long as you meet the pre-reqs and have full control over all files/folders under Temp
```
# Prerequisites
# Must have the PowerShell ActiveDirectory Module installed
# Must be an admin on the target servers
#
# however if you have no permissions to some folders inside the Temp,
# then you would need to take ownship first.
#
$Server = "server Name"
$dir = "\\$Server\admin$\Temp\*"
$OS = (Get-ADComputer $Server -Properties operatingsystem).operatingSystem
IF (($os -like "*2003*") -or ($os -like "*2008*"))
{
remove-item $dir -Recurse -force
}
``` | According to the PowerShell help file for `remove-item`, the `-recurse` parameter is faulty. It recommends that you `get-childitem` and pipe to `remove-item`. See example from the help file below.
```
-------------------------- EXAMPLE 4 --------------------------
C:\PS>get-childitem * -include *.csv -recurse | remove-item
``` |
19,730,773 | I've got the following code snippet which currently removes everything in my temp directory and re-adds a new temp directory.
```
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\WINDOWS\Temp\*'
remove-item $dir -force -recurse
if($?){new-item -path "\\$server\admin$\Temp" -Type Directory}
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp\*'
remove-item $dir -force -recurse
if($?){New-Item -Path "\\$server\admin$\Temp" -Type Directory}
}
```
I'm trying to slightly alter the code to where it will no longer delete the temp directory and instead simply remove all of the contents inside of temp. I added `\*` at the end of my `$dir` variable so that it tries to get all of the items inside of temp rather than deleting Temp itself. When I run this however I'm not deleting anything. What is wrong with my code? | 2013/11/01 | [
"https://Stackoverflow.com/questions/19730773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1451575/"
] | Figured out how to do this and figure it may be useful for someone in the future.
```
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\WINDOWS\Temp'
Get-ChildItem -path $dir -Recurse | %{Remove-Item -Path $_.FullName -Force}
if($?){new-item -path "\\$server\admin$\Temp" -Type Directory}
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp'
Get-ChildItem -path $dir -Recurse | %{Remove-Item -Path $_.FullName -Force}
write-host "success?"
if($?){New-Item -Path "\\$server\admin$\Temp" -Type Directory}
}
```
Using get-childitem it will look at everything inside of Temp without deleting Temp itself. | According to the PowerShell help file for `remove-item`, the `-recurse` parameter is faulty. It recommends that you `get-childitem` and pipe to `remove-item`. See example from the help file below.
```
-------------------------- EXAMPLE 4 --------------------------
C:\PS>get-childitem * -include *.csv -recurse | remove-item
``` |
66,947,683 | I'm struggling to access some values in this nested json in python.
How can I access this ['Records'][0]['s3']['bucket']['name'] ? I did search a lot to find a simple python snippet, but no luck. Thanks in advance!
```
{
"Records": [
{
"eventName": "xxxxxxx",
"userIdentity": {
"principalId": "AWS:XXXXXXXXXXXXXX"
},
"requestParameters": {
"sourceIPAddress": "XX.XX.XX.XX"
},
"responseElements": {
"x-amz-request-id": "8CXXXXXXXXXXHRQX",
"x-amz-id-2": "doZ3+gxxxxxxx"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "X-Event",
"bucket": {
"name": "bucket-name",
"ownerIdentity": {
"principalId": "xxxxxxx"
},
"arn": "arn:aws:s3:::bucket-name"
},
"object": {
"key": "object.png",
"sequencer": "0060XXXXXXX75X"
}
}
}
]
}
``` | 2021/04/05 | [
"https://Stackoverflow.com/questions/66947683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15500282/"
] | Since this is a string, use the `json.loads` method from the inbuilt JSON library.
```
import json
json_string = # your json string
parsed_string = json.loads(json_string)
print(parsed_string) # it will be a python dict
print(parsed_string['Records'][0]['s3']['bucket']['name']) # prints the string
``` | Have you tried running your example? If you're loading the json from elsewhere, you'd need to convert it to this native dictionary object using the `json` library (as mentioned by others, `json.loads(data)`)
```
kv = {
"Records": [
{
"eventName": "xxxxxxx",
"userIdentity": {
"principalId": "AWS:XXXXXXXXXXXXXX"
},
"requestParameters": {
"sourceIPAddress": "XX.XX.XX.XX"
},
"responseElements": {
"x-amz-request-id": "8CXXXXXXXXXXHRQX",
"x-amz-id-2": "doZ3+gxxxxxxx"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "X-Event",
"bucket": {
"name": "bucket-name",
"ownerIdentity": {
"principalId": "xxxxxxx"
},
"arn": "arn:aws:s3:::bucket-name"
},
"object": {
"key": "object.png",
"sequencer": "0060XXXXXXX75X"
}
}
}
]
}
print("RESULT:",kv['Records'][0]['s3']['bucket']['name'])
RESULT: bucket-name
``` |
3,228,000 | I need to find $$S = \sum\_{n=1}^{\infty}{\frac{1}{n 2^{n-1}}}$$
**Attempt:**
$$f'(x) = \sum\_{n=1}^{\infty}\frac{x^n}{2^n} = \frac{x}{2-x}$$
Which is just evaluating geometric series
$$f(x) = \sum\_{n=1}^{\infty}\frac{x^{n+1}}{(n+1)2^{n}}$$
Now, by finding antiderivative of $\frac{x}{2-x}$
$$f(x) = -x-2\ln(x-2)$$
Finding sum should be just $$S = 1 + f(1)$$
But $f(x)$ is undefined as a real-valued function for $x \leq 2$ | 2019/05/16 | [
"https://math.stackexchange.com/questions/3228000",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/672824/"
] | Take $f(x)=\sum\_{n=1}^\infty\frac{x^n}{n}$. Then the sum that you're after is $2f\left(\frac12\right)$. | An antiderivative for $\frac x {2-x}$ for $x<2$ is $-x-2\log(2-x)$ as you can see by diffferentiation. You missed an absolute value sign when you found the antiderivative. |
3,228,000 | I need to find $$S = \sum\_{n=1}^{\infty}{\frac{1}{n 2^{n-1}}}$$
**Attempt:**
$$f'(x) = \sum\_{n=1}^{\infty}\frac{x^n}{2^n} = \frac{x}{2-x}$$
Which is just evaluating geometric series
$$f(x) = \sum\_{n=1}^{\infty}\frac{x^{n+1}}{(n+1)2^{n}}$$
Now, by finding antiderivative of $\frac{x}{2-x}$
$$f(x) = -x-2\ln(x-2)$$
Finding sum should be just $$S = 1 + f(1)$$
But $f(x)$ is undefined as a real-valued function for $x \leq 2$ | 2019/05/16 | [
"https://math.stackexchange.com/questions/3228000",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/672824/"
] | Take $f(x)=\sum\_{n=1}^\infty\frac{x^n}{n}$. Then the sum that you're after is $2f\left(\frac12\right)$. | Since $\sum\_{n\ge 1}\frac{z^n}{n}=-\ln(1-z)$, $S=-2\ln\left(1-\frac12\right)=\ln 4$. |
3,228,000 | I need to find $$S = \sum\_{n=1}^{\infty}{\frac{1}{n 2^{n-1}}}$$
**Attempt:**
$$f'(x) = \sum\_{n=1}^{\infty}\frac{x^n}{2^n} = \frac{x}{2-x}$$
Which is just evaluating geometric series
$$f(x) = \sum\_{n=1}^{\infty}\frac{x^{n+1}}{(n+1)2^{n}}$$
Now, by finding antiderivative of $\frac{x}{2-x}$
$$f(x) = -x-2\ln(x-2)$$
Finding sum should be just $$S = 1 + f(1)$$
But $f(x)$ is undefined as a real-valued function for $x \leq 2$ | 2019/05/16 | [
"https://math.stackexchange.com/questions/3228000",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/672824/"
] | Take $f(x)=\sum\_{n=1}^\infty\frac{x^n}{n}$. Then the sum that you're after is $2f\left(\frac12\right)$. | $$S=2\sum\_{n=1}^{\infty} \frac{2^{-n}}{n}=2\sum\_{k=1}^{\infty}~ 2^{-n} \int\_{0}^{1} x^{n-1} ~dx=2 \int\_{0}^{1}\sum\_{n=1}^{\infty} \frac{dx}{x}\left(\frac{x}{2}\right)^n =\int\_{0}^{1}\frac{2}{x} \frac{x/2}{1-x/2} ~dx=2 \ln 2. $$ |
26,795,363 | I am new to php and here i have a form with 2 dropdown boxes and a submit button. Value of these boxes comes from my database.
My html code is
```
<form method = "post" id = "myform" >
<select name='country'>
<option value="all" <?php if($item == 'all'): echo "selected='selected'"; endif; ?> >--Select--</option>
<option value="India" <?php if($item == 'india'): echo "selected='selected'"; endif; ?> >India</option>
<option value="USA" <?php if($item == 'USA'): echo "selected='selected'"; endif; ?> >USA/option>
</select>
<select name='code'>
<option value="all" <?php if($item == 'all'): echo "selected='selected'"; endif; ?> >--Select--</option>
<option value="12" <?php if($item == '12'): echo "selected='selected'"; endif; ?> >12</option>
<option value="345" <?php if($item == '345'): echo "selected='selected'"; endif; ?> >345</option>
</select>
<input type = "submit" name = "submit" value = "submit" >
```
With submit button i am fetching the records from my database. Its working fine now. I would like to add paging in this form and i tried something like
```
<?php
if (isset($_REQUEST['country']) )
{
// code......
//paging query**
for ($i=1; $i<=$total_pages; $i++)
{
echo "<td><a href='test.php?page=".$i."&country=$country&code=$code'>".$i."</a><td> ";
};
}
?>
```
if i try the above the values are displaying for the first page but the second page is empty. And also i would like to keep the dropdown value as selected throughout the paging. I surfed google but cannot able to find it. I followed [this](http://www.tutorialspoint.com/php/mysql_paging_php.htm) tutorial for paging. Please help me in achiving this. | 2014/11/07 | [
"https://Stackoverflow.com/questions/26795363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3985358/"
] | `itertools.groupby` can help ...
```
from itertools import groupby
def f(lst):
if_empty = ('ignored_key', ())
k, v = next(groupby(lst), if_empty)
return sum(1 for _ in v)
```
And of course we can turn this into a 1-liner (sans the import):
```
sum(1 for _ in next(groupby(lst), ('ignored', ()))[1])
```
But I wouldn't really recommend it.
---
demo:
```
>>> from itertools import groupby
>>>
>>> def f(lst):
... if_empty = ('ignored_key', ())
... k, v = next(groupby(lst), if_empty)
... return sum(1 for _ in v)
...
>>> f(x1)
2
>>> f(x2)
3
>>> f(x3)
1
>>> f([])
0
``` | You can use [`takewhile`](https://docs.python.org/3/library/itertools.html#itertools.takewhile).
```
import itertools
xs = [1, 1, 1, 3, 1, 1, 1, 8]
sum(1 for _ in itertools.takewhile(lambda x: x == xs[0], xs))
```
In a function:
```
def count_first(iterable):
i = iter(iterable)
first = next(i)
return 1 + sum(1 for _ in itertools.takewhile(lambda x: x == first, i))
``` |
26,795,363 | I am new to php and here i have a form with 2 dropdown boxes and a submit button. Value of these boxes comes from my database.
My html code is
```
<form method = "post" id = "myform" >
<select name='country'>
<option value="all" <?php if($item == 'all'): echo "selected='selected'"; endif; ?> >--Select--</option>
<option value="India" <?php if($item == 'india'): echo "selected='selected'"; endif; ?> >India</option>
<option value="USA" <?php if($item == 'USA'): echo "selected='selected'"; endif; ?> >USA/option>
</select>
<select name='code'>
<option value="all" <?php if($item == 'all'): echo "selected='selected'"; endif; ?> >--Select--</option>
<option value="12" <?php if($item == '12'): echo "selected='selected'"; endif; ?> >12</option>
<option value="345" <?php if($item == '345'): echo "selected='selected'"; endif; ?> >345</option>
</select>
<input type = "submit" name = "submit" value = "submit" >
```
With submit button i am fetching the records from my database. Its working fine now. I would like to add paging in this form and i tried something like
```
<?php
if (isset($_REQUEST['country']) )
{
// code......
//paging query**
for ($i=1; $i<=$total_pages; $i++)
{
echo "<td><a href='test.php?page=".$i."&country=$country&code=$code'>".$i."</a><td> ";
};
}
?>
```
if i try the above the values are displaying for the first page but the second page is empty. And also i would like to keep the dropdown value as selected throughout the paging. I surfed google but cannot able to find it. I followed [this](http://www.tutorialspoint.com/php/mysql_paging_php.htm) tutorial for paging. Please help me in achiving this. | 2014/11/07 | [
"https://Stackoverflow.com/questions/26795363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3985358/"
] | `itertools.groupby` can help ...
```
from itertools import groupby
def f(lst):
if_empty = ('ignored_key', ())
k, v = next(groupby(lst), if_empty)
return sum(1 for _ in v)
```
And of course we can turn this into a 1-liner (sans the import):
```
sum(1 for _ in next(groupby(lst), ('ignored', ()))[1])
```
But I wouldn't really recommend it.
---
demo:
```
>>> from itertools import groupby
>>>
>>> def f(lst):
... if_empty = ('ignored_key', ())
... k, v = next(groupby(lst), if_empty)
... return sum(1 for _ in v)
...
>>> f(x1)
2
>>> f(x2)
3
>>> f(x3)
1
>>> f([])
0
``` | Maybe is better check the first occurrence of something that is not equal to the first value:
```
x1 = ['a','a','b','c','a','a','a','c']
x2 = [1, 1, 1, 3, 1, 1, 1, 8]
x3 = ['foo','bar','foobar']
x4 = []
x5 = [1,1,1,1,1,1]
def f(x):
pos = -1
for pos,a in enumerate(x):
if a!=x[0]:
return pos
return pos+1
print(f(x1))
print(f(x2))
print(f(x3))
print(f(x4))
print(f(x5))
2
3
1
0
6
``` |
26,795,363 | I am new to php and here i have a form with 2 dropdown boxes and a submit button. Value of these boxes comes from my database.
My html code is
```
<form method = "post" id = "myform" >
<select name='country'>
<option value="all" <?php if($item == 'all'): echo "selected='selected'"; endif; ?> >--Select--</option>
<option value="India" <?php if($item == 'india'): echo "selected='selected'"; endif; ?> >India</option>
<option value="USA" <?php if($item == 'USA'): echo "selected='selected'"; endif; ?> >USA/option>
</select>
<select name='code'>
<option value="all" <?php if($item == 'all'): echo "selected='selected'"; endif; ?> >--Select--</option>
<option value="12" <?php if($item == '12'): echo "selected='selected'"; endif; ?> >12</option>
<option value="345" <?php if($item == '345'): echo "selected='selected'"; endif; ?> >345</option>
</select>
<input type = "submit" name = "submit" value = "submit" >
```
With submit button i am fetching the records from my database. Its working fine now. I would like to add paging in this form and i tried something like
```
<?php
if (isset($_REQUEST['country']) )
{
// code......
//paging query**
for ($i=1; $i<=$total_pages; $i++)
{
echo "<td><a href='test.php?page=".$i."&country=$country&code=$code'>".$i."</a><td> ";
};
}
?>
```
if i try the above the values are displaying for the first page but the second page is empty. And also i would like to keep the dropdown value as selected throughout the paging. I surfed google but cannot able to find it. I followed [this](http://www.tutorialspoint.com/php/mysql_paging_php.htm) tutorial for paging. Please help me in achiving this. | 2014/11/07 | [
"https://Stackoverflow.com/questions/26795363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3985358/"
] | You can use [`takewhile`](https://docs.python.org/3/library/itertools.html#itertools.takewhile).
```
import itertools
xs = [1, 1, 1, 3, 1, 1, 1, 8]
sum(1 for _ in itertools.takewhile(lambda x: x == xs[0], xs))
```
In a function:
```
def count_first(iterable):
i = iter(iterable)
first = next(i)
return 1 + sum(1 for _ in itertools.takewhile(lambda x: x == first, i))
``` | Maybe is better check the first occurrence of something that is not equal to the first value:
```
x1 = ['a','a','b','c','a','a','a','c']
x2 = [1, 1, 1, 3, 1, 1, 1, 8]
x3 = ['foo','bar','foobar']
x4 = []
x5 = [1,1,1,1,1,1]
def f(x):
pos = -1
for pos,a in enumerate(x):
if a!=x[0]:
return pos
return pos+1
print(f(x1))
print(f(x2))
print(f(x3))
print(f(x4))
print(f(x5))
2
3
1
0
6
``` |
25,509,272 | I have create my report in visual studio and i can't deploy it;
I have deploy my report by 3 different ways : Through AOT,Through Visual Studio,Through PowerShell ; but i have the same issue
i have this error message:
```
The deployment was canceled due to an error. On the report server, make sure:
- SQL Server Reporting Services service is running.
- SQL Server Reporting Services service is configured according to the instructions in the manual installation of Microsoft Dynamics AX (http://go.microsoft.com/fwlink/?LinkID=163796).
- The remote administration functionality is allowed to communicate through the Windows Firewall.
```
I have Run this command `Test-AXReportServerConfiguration` in AX power shell and this is the message in screen shot
```
IsAOSRunning : True
IsCurrentUserAdminOnAOSServer : True
IsCurrentUserAdminOnSRSServer : True
IsReportManagerRunning : True
IsReportServerRunning : False
IsUACDisabledOnAOSServer : True
IsUACDisabledOnSRSServer : True
Testing the report server configurations completed.
```
Can anyone help me? | 2014/08/26 | [
"https://Stackoverflow.com/questions/25509272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3668738/"
] | >
> I am also ready to convert this file to a java script file, if any body can suggest how would I
> achieve that for about 3000 lines of code.
>
>
>
Using any editor worth its salt you can just append `",` to every line, and replace `=` with `:"`. This would give you:
```
404: "The requested resource could not be found",
500: "Internal server error",
1001: "No message body found",
1002: "No message header found",
```
Then replace the last comma in the file with `};`, and add `var myObject = {` in the beginning, and you're done. | Do what Niels or meagar said, then get your file using (jquery)
```
var codes;
$.get(FILEURL, function(res){ codes = res; });
function getMessageFromCode(code){
return codes[code];
}
```
Or, simply use `codes[500]`, a function is really not needed there.
**EDIT**
If you need it to be synchronous, **which would be wise**, then just include the file (after having made the edits suggested by Niels) in your `<head>`. You'll be able to to use `myObject[500]` then. |
25,509,272 | I have create my report in visual studio and i can't deploy it;
I have deploy my report by 3 different ways : Through AOT,Through Visual Studio,Through PowerShell ; but i have the same issue
i have this error message:
```
The deployment was canceled due to an error. On the report server, make sure:
- SQL Server Reporting Services service is running.
- SQL Server Reporting Services service is configured according to the instructions in the manual installation of Microsoft Dynamics AX (http://go.microsoft.com/fwlink/?LinkID=163796).
- The remote administration functionality is allowed to communicate through the Windows Firewall.
```
I have Run this command `Test-AXReportServerConfiguration` in AX power shell and this is the message in screen shot
```
IsAOSRunning : True
IsCurrentUserAdminOnAOSServer : True
IsCurrentUserAdminOnSRSServer : True
IsReportManagerRunning : True
IsReportServerRunning : False
IsUACDisabledOnAOSServer : True
IsUACDisabledOnSRSServer : True
Testing the report server configurations completed.
```
Can anyone help me? | 2014/08/26 | [
"https://Stackoverflow.com/questions/25509272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3668738/"
] | >
> I am also ready to convert this file to a java script file, if any body can suggest how would I
> achieve that for about 3000 lines of code.
>
>
>
Using any editor worth its salt you can just append `",` to every line, and replace `=` with `:"`. This would give you:
```
404: "The requested resource could not be found",
500: "Internal server error",
1001: "No message body found",
1002: "No message header found",
```
Then replace the last comma in the file with `};`, and add `var myObject = {` in the beginning, and you're done. | If you can't change file type or content, you can try to parse it and fit it in a dict at load event of your page, this way you create dict once and will be available for all your functions
```
var url='URL-TO-YOUR-FILE'
messages = {} //global scope, messages will be available for all your functions
parse_messages().done(function(r) {
messages = r
})
.fail(function(x) {
//messages doesn't load well, show the error
console.log(x)
});
function parse_messages(){
return $.get(url, function(html){
lines = html.split(/\n/)
lines.forEach(function(line){
var splitted_line = line.split("=")
if (splitted_line && splitted_line.length == 2){
var code = splitted_line[0].trim()
//check if code is valid
if(!isNaN(code)){
messages[code] = splitted_line[1].trim()
}
}
})
})
}
```
Here is the output
```
>>>> messages
>>>> Object {404: "The requested resource could not be found", 500: "Internal server error", 1001: "No message body found", 1002: "No message header foundvar codes;"}
``` |
25,509,272 | I have create my report in visual studio and i can't deploy it;
I have deploy my report by 3 different ways : Through AOT,Through Visual Studio,Through PowerShell ; but i have the same issue
i have this error message:
```
The deployment was canceled due to an error. On the report server, make sure:
- SQL Server Reporting Services service is running.
- SQL Server Reporting Services service is configured according to the instructions in the manual installation of Microsoft Dynamics AX (http://go.microsoft.com/fwlink/?LinkID=163796).
- The remote administration functionality is allowed to communicate through the Windows Firewall.
```
I have Run this command `Test-AXReportServerConfiguration` in AX power shell and this is the message in screen shot
```
IsAOSRunning : True
IsCurrentUserAdminOnAOSServer : True
IsCurrentUserAdminOnSRSServer : True
IsReportManagerRunning : True
IsReportServerRunning : False
IsUACDisabledOnAOSServer : True
IsUACDisabledOnSRSServer : True
Testing the report server configurations completed.
```
Can anyone help me? | 2014/08/26 | [
"https://Stackoverflow.com/questions/25509272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3668738/"
] | If you can't change file type or content, you can try to parse it and fit it in a dict at load event of your page, this way you create dict once and will be available for all your functions
```
var url='URL-TO-YOUR-FILE'
messages = {} //global scope, messages will be available for all your functions
parse_messages().done(function(r) {
messages = r
})
.fail(function(x) {
//messages doesn't load well, show the error
console.log(x)
});
function parse_messages(){
return $.get(url, function(html){
lines = html.split(/\n/)
lines.forEach(function(line){
var splitted_line = line.split("=")
if (splitted_line && splitted_line.length == 2){
var code = splitted_line[0].trim()
//check if code is valid
if(!isNaN(code)){
messages[code] = splitted_line[1].trim()
}
}
})
})
}
```
Here is the output
```
>>>> messages
>>>> Object {404: "The requested resource could not be found", 500: "Internal server error", 1001: "No message body found", 1002: "No message header foundvar codes;"}
``` | Do what Niels or meagar said, then get your file using (jquery)
```
var codes;
$.get(FILEURL, function(res){ codes = res; });
function getMessageFromCode(code){
return codes[code];
}
```
Or, simply use `codes[500]`, a function is really not needed there.
**EDIT**
If you need it to be synchronous, **which would be wise**, then just include the file (after having made the edits suggested by Niels) in your `<head>`. You'll be able to to use `myObject[500]` then. |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | The body is pretty bad at repairing fine structure. When you remove lobes of the liver, the lobes don't recover, the cells just replicate and fill the gaps. Because the cells just all filter blood it doesn't matter so much that they lack much structure.
That's pretty useless for the heart. The heart has a fine structure, and it doesn't work well if you just fill it with lots of cells. It's pretty useless for the brain, which relies on a precise structure to function.
So, it would probably do more harm than help, since most organs don't function well with cells just generating to fill all the gaps. | Short answer, no.
There is a new process being looked into that links DNA to aging. A component of our genes, [telomere](https://en.wikipedia.org/wiki/Telomere) is the genetic end caps of our genes and act as a type of internal clock in the body. Each time cells in the body divide, ie replace other old and dying cells, these telomere's get shorter.
Over time, these telomere will shorten to nothing and the cell could no longer reliably duplicate itself without errors. This does not happen across the body all at once, but eventually, there will be a significant number of cells through out the body that it could not repair damage, cannot duplicate itself or are creating erroneous copies of itself at a quick pace (cancer). |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | **Most death is not from cellular wear and tear.**
Joints wear out. But it is unusual for wear and tear to be a cause of death. For orientation: causes of death in the US.
<https://www.statista.com/statistics/248622/rates-of-leading-causes-of-death-in-the-us/>
[](https://i.stack.imgur.com/SG4Kl.png)
#1 and #2 are heart disease and cancer.
It is not clear to me that cardiovascular disease (and death from heart attack or stroke) is related to the self-renewal ability of cells in the arteries. I do not think making those cells turn over like epithelial linings will reduce plaque. But maybe.
If heart disease incidence falls, cancer becomes #1. As is the case in Japan where people live 10-15 years longer and die of cancer.
Self-renewal for all cells will increase cancer risk. A look at cancer mortality shows that common cancers arise in epithelial linings that are renewing themselves. Cancers can arise in non-renewing tissues (brain, bone, muscle) but those cancers are rare and do not make the list. Expanding the pool of cells which are renewing themselves will increase cancer rates for those cancer types.
<https://gco.iarc.fr/today/data/factsheets/cancers/40-All-cancers-excluding-non-melanoma-skin-cancer-fact-sheet.pdf>
[](https://i.stack.imgur.com/NSRwV.png)
--
I am not sure about dementia and not sure about kidney disease. Kidney disease might actually be from wear. Maybe a self-renewing kidney will take kidney diseases out of the running for mortality risk.
Dementia has not historically been considered a cause of death because it is usually something else that strikes the final blow. I am not sure if self renewing brain cells would sidestep dementia.
---
For a fiction you could have self renewing artery, kidney and brain cells get rid of cardiovascular disease, renal failure and dementia. You could have improvements in cancer detection and then immunotherapy and other cancer treatments to nip cancer in the bud. | The body is pretty bad at repairing fine structure. When you remove lobes of the liver, the lobes don't recover, the cells just replicate and fill the gaps. Because the cells just all filter blood it doesn't matter so much that they lack much structure.
That's pretty useless for the heart. The heart has a fine structure, and it doesn't work well if you just fill it with lots of cells. It's pretty useless for the brain, which relies on a precise structure to function.
So, it would probably do more harm than help, since most organs don't function well with cells just generating to fill all the gaps. |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | The body is pretty bad at repairing fine structure. When you remove lobes of the liver, the lobes don't recover, the cells just replicate and fill the gaps. Because the cells just all filter blood it doesn't matter so much that they lack much structure.
That's pretty useless for the heart. The heart has a fine structure, and it doesn't work well if you just fill it with lots of cells. It's pretty useless for the brain, which relies on a precise structure to function.
So, it would probably do more harm than help, since most organs don't function well with cells just generating to fill all the gaps. | Really good regeneration is what axolotls do and they live [about 20 years](https://axolotlnerd.com/axolotls-lifespan/), which is pretty much the same as [other salamanders](https://www.animalspot.net/salamander) (and much less than the [really, really long-lived species](https://www.nbcnews.com/id/wbna38334490) but those are typically metabolically slower). So the "natural experiment" does not support an increase in lifespan, although regeneration has other advantages.
As others have pointed out, the principal causes of death for humans aren't necessarily going to be improved by better cellular/organ repair, and at least one (cancer) is probably going to get worse, nullifying any gains from limiting the damage from cardiovascular events. You may however see an increase in [healthy life expectancy](https://en.wikipedia.org/wiki/Life_expectancy#Healthy_life_expectancy) or "healthspan", as in the fraction of one's life unencumbered by age-related health problems. Joint pain, osteoporosis, muscle loss, cataracts/loss of visual acuity, hair loss, all could be improved resulting in a more youthful-looking (and feeling) population (see AlexP's similar comment above). |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | The body is pretty bad at repairing fine structure. When you remove lobes of the liver, the lobes don't recover, the cells just replicate and fill the gaps. Because the cells just all filter blood it doesn't matter so much that they lack much structure.
That's pretty useless for the heart. The heart has a fine structure, and it doesn't work well if you just fill it with lots of cells. It's pretty useless for the brain, which relies on a precise structure to function.
So, it would probably do more harm than help, since most organs don't function well with cells just generating to fill all the gaps. | Coupled with Modern Society, it Would Increase Life Expectancy
--------------------------------------------------------------
When you look at [Willk's answer](https://worldbuilding.stackexchange.com/a/218845/57832), you see that the 2 leading causes of death are by far heart disease and cancer with heart disease exceeding all forms of cancer combined. It is true that the heart is the 3rd most resistant organ in the human body to cancer; so, making it regenerative would increase the rate of heart cancer pushing the cancer death rate up a notch ... but this could also massively reduce deaths from heart disease. While cholesterol buildup is often blamed for pulmonary illness, various studies over the past couple decades suggest that this is probably a symptom, not a cause. When an artery becomes weakened or damaged, our bodies coat our arteries with cholesterol on purpose to reinforce and protect it, but our heart and arteries have limited actual healing capabilities due to poor regeneration. If the pulmonary system could better heal itself, then our bodies would not need to respond with cholesterol buildup which means that heart disease as we know it could be all but eliminated. So, you could trade a lot of prevented heart disease for a little bit of heart cancer.
Then you look at the next 3 lowest things: Accidents, Chronic Lower Respiratory, & Stroke. Many accidents cause chronic, unrecoverable injuries. With our current bodies, most major accidents end not with instant death, but being put on various types of life support and waiting to see if the body can heal itself. Many people who go onto life support never recover, but with better regeneration, life-support would become far more successful at saving lives and allowing a person to return to full health. Chronic Lower Respiratory diseases are normally caused by scaring of the lower lungs from smoking or major infections. With better regeneration, your lungs could fully heal following these events making later life respiratory issues far less common. Strokes would also not necessarily become less common, but making full recoveries would become more common.
But the biggest life saver of all here is improved quality of life. People who are not in chronic pain live happier lives. Of all health factors that determine how long you will live, happiness is probably the most important due to its direct relationship with pulmonary heath and your immune system, and better regeneration helps you maintain better happiness as you age.
So what does this all have to do with Modern Society?
-----------------------------------------------------
Human biology is designed to optimize our survival to how our ancestors lived.
Our medial pulmonary systems don't regenerate very well because physically active humans living off of a natural diet can live a very long time as is; so, no need for better regeneration there. But now that we are living longer and eating worse, a regenerative heart would become more practical. Modern medical interventions also mean that we are MUCH better at stopping a simple wound from killing you quickly. If getting a leg cut off is rapidly fatal to pre-modern man, then there is no reason to care if your body has a long-term plan for recovery, but if you can consistently stop the fast death, then better regeneration helps prevent slow death.
We are also a lot better now at treating cancer than our ancestors were. To premodern man, cancer was an absolute death sentence; so, our biology tries to avoid it by reducing cell divisions to minimal requirements. But with modern medicine, we can cut it out, irradiate it, chemo it, etc. Ironically, better regeneration may actually decrease the chance of dyeing of cancer despite higher cancer rates because more invasive treatment options would open up.
So, if you went back to 50,000BCE and made humans super regenerative, it would not be very beneficial, but do it today, I am pretty sure it would help a lot. |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | **Most death is not from cellular wear and tear.**
Joints wear out. But it is unusual for wear and tear to be a cause of death. For orientation: causes of death in the US.
<https://www.statista.com/statistics/248622/rates-of-leading-causes-of-death-in-the-us/>
[](https://i.stack.imgur.com/SG4Kl.png)
#1 and #2 are heart disease and cancer.
It is not clear to me that cardiovascular disease (and death from heart attack or stroke) is related to the self-renewal ability of cells in the arteries. I do not think making those cells turn over like epithelial linings will reduce plaque. But maybe.
If heart disease incidence falls, cancer becomes #1. As is the case in Japan where people live 10-15 years longer and die of cancer.
Self-renewal for all cells will increase cancer risk. A look at cancer mortality shows that common cancers arise in epithelial linings that are renewing themselves. Cancers can arise in non-renewing tissues (brain, bone, muscle) but those cancers are rare and do not make the list. Expanding the pool of cells which are renewing themselves will increase cancer rates for those cancer types.
<https://gco.iarc.fr/today/data/factsheets/cancers/40-All-cancers-excluding-non-melanoma-skin-cancer-fact-sheet.pdf>
[](https://i.stack.imgur.com/NSRwV.png)
--
I am not sure about dementia and not sure about kidney disease. Kidney disease might actually be from wear. Maybe a self-renewing kidney will take kidney diseases out of the running for mortality risk.
Dementia has not historically been considered a cause of death because it is usually something else that strikes the final blow. I am not sure if self renewing brain cells would sidestep dementia.
---
For a fiction you could have self renewing artery, kidney and brain cells get rid of cardiovascular disease, renal failure and dementia. You could have improvements in cancer detection and then immunotherapy and other cancer treatments to nip cancer in the bud. | Short answer, no.
There is a new process being looked into that links DNA to aging. A component of our genes, [telomere](https://en.wikipedia.org/wiki/Telomere) is the genetic end caps of our genes and act as a type of internal clock in the body. Each time cells in the body divide, ie replace other old and dying cells, these telomere's get shorter.
Over time, these telomere will shorten to nothing and the cell could no longer reliably duplicate itself without errors. This does not happen across the body all at once, but eventually, there will be a significant number of cells through out the body that it could not repair damage, cannot duplicate itself or are creating erroneous copies of itself at a quick pace (cancer). |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | Short answer, no.
There is a new process being looked into that links DNA to aging. A component of our genes, [telomere](https://en.wikipedia.org/wiki/Telomere) is the genetic end caps of our genes and act as a type of internal clock in the body. Each time cells in the body divide, ie replace other old and dying cells, these telomere's get shorter.
Over time, these telomere will shorten to nothing and the cell could no longer reliably duplicate itself without errors. This does not happen across the body all at once, but eventually, there will be a significant number of cells through out the body that it could not repair damage, cannot duplicate itself or are creating erroneous copies of itself at a quick pace (cancer). | Really good regeneration is what axolotls do and they live [about 20 years](https://axolotlnerd.com/axolotls-lifespan/), which is pretty much the same as [other salamanders](https://www.animalspot.net/salamander) (and much less than the [really, really long-lived species](https://www.nbcnews.com/id/wbna38334490) but those are typically metabolically slower). So the "natural experiment" does not support an increase in lifespan, although regeneration has other advantages.
As others have pointed out, the principal causes of death for humans aren't necessarily going to be improved by better cellular/organ repair, and at least one (cancer) is probably going to get worse, nullifying any gains from limiting the damage from cardiovascular events. You may however see an increase in [healthy life expectancy](https://en.wikipedia.org/wiki/Life_expectancy#Healthy_life_expectancy) or "healthspan", as in the fraction of one's life unencumbered by age-related health problems. Joint pain, osteoporosis, muscle loss, cataracts/loss of visual acuity, hair loss, all could be improved resulting in a more youthful-looking (and feeling) population (see AlexP's similar comment above). |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | Short answer, no.
There is a new process being looked into that links DNA to aging. A component of our genes, [telomere](https://en.wikipedia.org/wiki/Telomere) is the genetic end caps of our genes and act as a type of internal clock in the body. Each time cells in the body divide, ie replace other old and dying cells, these telomere's get shorter.
Over time, these telomere will shorten to nothing and the cell could no longer reliably duplicate itself without errors. This does not happen across the body all at once, but eventually, there will be a significant number of cells through out the body that it could not repair damage, cannot duplicate itself or are creating erroneous copies of itself at a quick pace (cancer). | Coupled with Modern Society, it Would Increase Life Expectancy
--------------------------------------------------------------
When you look at [Willk's answer](https://worldbuilding.stackexchange.com/a/218845/57832), you see that the 2 leading causes of death are by far heart disease and cancer with heart disease exceeding all forms of cancer combined. It is true that the heart is the 3rd most resistant organ in the human body to cancer; so, making it regenerative would increase the rate of heart cancer pushing the cancer death rate up a notch ... but this could also massively reduce deaths from heart disease. While cholesterol buildup is often blamed for pulmonary illness, various studies over the past couple decades suggest that this is probably a symptom, not a cause. When an artery becomes weakened or damaged, our bodies coat our arteries with cholesterol on purpose to reinforce and protect it, but our heart and arteries have limited actual healing capabilities due to poor regeneration. If the pulmonary system could better heal itself, then our bodies would not need to respond with cholesterol buildup which means that heart disease as we know it could be all but eliminated. So, you could trade a lot of prevented heart disease for a little bit of heart cancer.
Then you look at the next 3 lowest things: Accidents, Chronic Lower Respiratory, & Stroke. Many accidents cause chronic, unrecoverable injuries. With our current bodies, most major accidents end not with instant death, but being put on various types of life support and waiting to see if the body can heal itself. Many people who go onto life support never recover, but with better regeneration, life-support would become far more successful at saving lives and allowing a person to return to full health. Chronic Lower Respiratory diseases are normally caused by scaring of the lower lungs from smoking or major infections. With better regeneration, your lungs could fully heal following these events making later life respiratory issues far less common. Strokes would also not necessarily become less common, but making full recoveries would become more common.
But the biggest life saver of all here is improved quality of life. People who are not in chronic pain live happier lives. Of all health factors that determine how long you will live, happiness is probably the most important due to its direct relationship with pulmonary heath and your immune system, and better regeneration helps you maintain better happiness as you age.
So what does this all have to do with Modern Society?
-----------------------------------------------------
Human biology is designed to optimize our survival to how our ancestors lived.
Our medial pulmonary systems don't regenerate very well because physically active humans living off of a natural diet can live a very long time as is; so, no need for better regeneration there. But now that we are living longer and eating worse, a regenerative heart would become more practical. Modern medical interventions also mean that we are MUCH better at stopping a simple wound from killing you quickly. If getting a leg cut off is rapidly fatal to pre-modern man, then there is no reason to care if your body has a long-term plan for recovery, but if you can consistently stop the fast death, then better regeneration helps prevent slow death.
We are also a lot better now at treating cancer than our ancestors were. To premodern man, cancer was an absolute death sentence; so, our biology tries to avoid it by reducing cell divisions to minimal requirements. But with modern medicine, we can cut it out, irradiate it, chemo it, etc. Ironically, better regeneration may actually decrease the chance of dyeing of cancer despite higher cancer rates because more invasive treatment options would open up.
So, if you went back to 50,000BCE and made humans super regenerative, it would not be very beneficial, but do it today, I am pretty sure it would help a lot. |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | **Most death is not from cellular wear and tear.**
Joints wear out. But it is unusual for wear and tear to be a cause of death. For orientation: causes of death in the US.
<https://www.statista.com/statistics/248622/rates-of-leading-causes-of-death-in-the-us/>
[](https://i.stack.imgur.com/SG4Kl.png)
#1 and #2 are heart disease and cancer.
It is not clear to me that cardiovascular disease (and death from heart attack or stroke) is related to the self-renewal ability of cells in the arteries. I do not think making those cells turn over like epithelial linings will reduce plaque. But maybe.
If heart disease incidence falls, cancer becomes #1. As is the case in Japan where people live 10-15 years longer and die of cancer.
Self-renewal for all cells will increase cancer risk. A look at cancer mortality shows that common cancers arise in epithelial linings that are renewing themselves. Cancers can arise in non-renewing tissues (brain, bone, muscle) but those cancers are rare and do not make the list. Expanding the pool of cells which are renewing themselves will increase cancer rates for those cancer types.
<https://gco.iarc.fr/today/data/factsheets/cancers/40-All-cancers-excluding-non-melanoma-skin-cancer-fact-sheet.pdf>
[](https://i.stack.imgur.com/NSRwV.png)
--
I am not sure about dementia and not sure about kidney disease. Kidney disease might actually be from wear. Maybe a self-renewing kidney will take kidney diseases out of the running for mortality risk.
Dementia has not historically been considered a cause of death because it is usually something else that strikes the final blow. I am not sure if self renewing brain cells would sidestep dementia.
---
For a fiction you could have self renewing artery, kidney and brain cells get rid of cardiovascular disease, renal failure and dementia. You could have improvements in cancer detection and then immunotherapy and other cancer treatments to nip cancer in the bud. | Really good regeneration is what axolotls do and they live [about 20 years](https://axolotlnerd.com/axolotls-lifespan/), which is pretty much the same as [other salamanders](https://www.animalspot.net/salamander) (and much less than the [really, really long-lived species](https://www.nbcnews.com/id/wbna38334490) but those are typically metabolically slower). So the "natural experiment" does not support an increase in lifespan, although regeneration has other advantages.
As others have pointed out, the principal causes of death for humans aren't necessarily going to be improved by better cellular/organ repair, and at least one (cancer) is probably going to get worse, nullifying any gains from limiting the damage from cardiovascular events. You may however see an increase in [healthy life expectancy](https://en.wikipedia.org/wiki/Life_expectancy#Healthy_life_expectancy) or "healthspan", as in the fraction of one's life unencumbered by age-related health problems. Joint pain, osteoporosis, muscle loss, cataracts/loss of visual acuity, hair loss, all could be improved resulting in a more youthful-looking (and feeling) population (see AlexP's similar comment above). |
218,839 | The world has come to regularly use genetic modification for cosmetic purposes, hair colour, eye colour, height, etc, relatively useless stuff. A breakthrough has been made that has produced the first functionally useful genetic modification, one that extends the repair/regeneration ability of the liver in the event of physical damage to the rest of your vital organs.
A far cry from immortality, since people still age, but it's a start and might do more for a person's total years of life than most current practices are capable of. Some people doubt its ability to extend a person's life on its own precisely because people still age despite it, but it might end up proving extremely effective once mods(the genetically modified) eventually prove to live longer than normal people.
**Would human life expectancy increase by a significant amount due to this or would it prove to not be that effective in the end?** | 2021/12/08 | [
"https://worldbuilding.stackexchange.com/questions/218839",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/90904/"
] | **Most death is not from cellular wear and tear.**
Joints wear out. But it is unusual for wear and tear to be a cause of death. For orientation: causes of death in the US.
<https://www.statista.com/statistics/248622/rates-of-leading-causes-of-death-in-the-us/>
[](https://i.stack.imgur.com/SG4Kl.png)
#1 and #2 are heart disease and cancer.
It is not clear to me that cardiovascular disease (and death from heart attack or stroke) is related to the self-renewal ability of cells in the arteries. I do not think making those cells turn over like epithelial linings will reduce plaque. But maybe.
If heart disease incidence falls, cancer becomes #1. As is the case in Japan where people live 10-15 years longer and die of cancer.
Self-renewal for all cells will increase cancer risk. A look at cancer mortality shows that common cancers arise in epithelial linings that are renewing themselves. Cancers can arise in non-renewing tissues (brain, bone, muscle) but those cancers are rare and do not make the list. Expanding the pool of cells which are renewing themselves will increase cancer rates for those cancer types.
<https://gco.iarc.fr/today/data/factsheets/cancers/40-All-cancers-excluding-non-melanoma-skin-cancer-fact-sheet.pdf>
[](https://i.stack.imgur.com/NSRwV.png)
--
I am not sure about dementia and not sure about kidney disease. Kidney disease might actually be from wear. Maybe a self-renewing kidney will take kidney diseases out of the running for mortality risk.
Dementia has not historically been considered a cause of death because it is usually something else that strikes the final blow. I am not sure if self renewing brain cells would sidestep dementia.
---
For a fiction you could have self renewing artery, kidney and brain cells get rid of cardiovascular disease, renal failure and dementia. You could have improvements in cancer detection and then immunotherapy and other cancer treatments to nip cancer in the bud. | Coupled with Modern Society, it Would Increase Life Expectancy
--------------------------------------------------------------
When you look at [Willk's answer](https://worldbuilding.stackexchange.com/a/218845/57832), you see that the 2 leading causes of death are by far heart disease and cancer with heart disease exceeding all forms of cancer combined. It is true that the heart is the 3rd most resistant organ in the human body to cancer; so, making it regenerative would increase the rate of heart cancer pushing the cancer death rate up a notch ... but this could also massively reduce deaths from heart disease. While cholesterol buildup is often blamed for pulmonary illness, various studies over the past couple decades suggest that this is probably a symptom, not a cause. When an artery becomes weakened or damaged, our bodies coat our arteries with cholesterol on purpose to reinforce and protect it, but our heart and arteries have limited actual healing capabilities due to poor regeneration. If the pulmonary system could better heal itself, then our bodies would not need to respond with cholesterol buildup which means that heart disease as we know it could be all but eliminated. So, you could trade a lot of prevented heart disease for a little bit of heart cancer.
Then you look at the next 3 lowest things: Accidents, Chronic Lower Respiratory, & Stroke. Many accidents cause chronic, unrecoverable injuries. With our current bodies, most major accidents end not with instant death, but being put on various types of life support and waiting to see if the body can heal itself. Many people who go onto life support never recover, but with better regeneration, life-support would become far more successful at saving lives and allowing a person to return to full health. Chronic Lower Respiratory diseases are normally caused by scaring of the lower lungs from smoking or major infections. With better regeneration, your lungs could fully heal following these events making later life respiratory issues far less common. Strokes would also not necessarily become less common, but making full recoveries would become more common.
But the biggest life saver of all here is improved quality of life. People who are not in chronic pain live happier lives. Of all health factors that determine how long you will live, happiness is probably the most important due to its direct relationship with pulmonary heath and your immune system, and better regeneration helps you maintain better happiness as you age.
So what does this all have to do with Modern Society?
-----------------------------------------------------
Human biology is designed to optimize our survival to how our ancestors lived.
Our medial pulmonary systems don't regenerate very well because physically active humans living off of a natural diet can live a very long time as is; so, no need for better regeneration there. But now that we are living longer and eating worse, a regenerative heart would become more practical. Modern medical interventions also mean that we are MUCH better at stopping a simple wound from killing you quickly. If getting a leg cut off is rapidly fatal to pre-modern man, then there is no reason to care if your body has a long-term plan for recovery, but if you can consistently stop the fast death, then better regeneration helps prevent slow death.
We are also a lot better now at treating cancer than our ancestors were. To premodern man, cancer was an absolute death sentence; so, our biology tries to avoid it by reducing cell divisions to minimal requirements. But with modern medicine, we can cut it out, irradiate it, chemo it, etc. Ironically, better regeneration may actually decrease the chance of dyeing of cancer despite higher cancer rates because more invasive treatment options would open up.
So, if you went back to 50,000BCE and made humans super regenerative, it would not be very beneficial, but do it today, I am pretty sure it would help a lot. |
7,389,329 | As part of debugging an application, I noticed that `Field.getDeclaredFields()` returns some synthetic fields, including a `serialVersionUID` field in a class extending an interface, although none extend `Serializable`.
Why does the compiler add such fields?
**UPDATE**
In fact, there is also a `$VRc` synthetic field created. | 2011/09/12 | [
"https://Stackoverflow.com/questions/7389329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/520957/"
] | The Java compiler/runtime will not automatically create a serialVersionUID field. I suspect that you are using some form of bytecode enchancement framework under the hood that is being instructed to add the synthetic fields either at runtime, or during compilation.
The `$VRc` field is produced by the Emma instrumentation framework, so that would be the reason for at least one of the synthetic fields.
The `serialVersionUID` field is also [added by Emma](http://emma.sourceforge.net/reference/ch03s02.html#prop-ref.instr.do_suid_compensation), when the `instr.do_suid_compensation` property is set to true. | This field is essential for Java [serialization](http://java.sun.com/developer/technicalArticles/Programming/serialization/). In short: it allows the JVM to discover that the class that was serialized (e.g. saved on disk) has been changed afterwards and cannot be safely deserialized back to object.
Have a look at **Version Control** chapter in the document quoted above, it explains how `serialVersionUID` is used.
UPDATE: just noticed your class does not implement `Serializable`. Are you sure none of super classes or implemented interfaces aren't extending `Serializable`? |
33,553,060 | I am writing a code to deallocate a char \* from struct in C.
The code will be like
```
struct Name{
char *p;
};
struct Name *name = malloc(sizeof(struct Name));
name->p = malloc(50);
```
Now I am deallocating the entire struct:
free(name);
But I want to deallocate the char pointer i.e p.
How can I do that? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33553060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5523171/"
] | First you have to deallocate name->p before deallocating name.
```
free(name->p);
free(name);
``` | Especially if you are using pointers in a struct you should always memset it to 0 or call calloc. You should also check the return value of malloc. If it returns NULL then it failed to allocate.
```
struct Name {
char *p;
};
//allocate
struct Name *name = malloc(sizeof *name);
memset(name, 0, sizeof *name);
name->p = malloc(50 * sizeof *name->p);
//deallocate
free(name->p);
free(name);
``` |
166,448 | Okay, so I am reading a book, *"The Elegant Universe"* by Brian Greene, which talks about motion and its effect on time.
Greene makes the point that time changes with motion by saying that if you have two mirrors and bounce a photon off of them it will have bounced off them very very often during a second. But, if you have the mirrors moving you must shoot the photon at an angle so it will be able to hit the mirrors and not miss and fly off. Since you are shooting diagonally it takes the photon more time to hit each mirror. So it's basically saying that time changes the closer you come to light speed.
Why? Why does this hold true for all matter? How does bouncing a photon around prove anything? | 2015/02/22 | [
"https://physics.stackexchange.com/questions/166448",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/73749/"
] | This is an effect known as *time dilation*. In this post, I will be taking material from the excellent book, *Einstein Gravity in a Nutshell*, by A. Zee.
Figure 1 will be the basis for the argument.

We bounce a photon around to create a *clock*. It is postulated that the speed of light is the same in all frames. In the rest frame, the time it takes for light to make a round trip is
$$\Delta t=\frac{2L}{c}$$
In the moving frame we have a (relative) velocity $u$. Using a little geometry, we find that
$$c\Delta t'=2\sqrt{(\tfrac{1}{2}u\Delta t')^2+L^2}$$
You can easily solve this to obtain
$$\Delta t'=\gamma\Delta t,\quad \gamma=(1-u^2/c^2)^{-1/2}$$
which is the basic equation for time dilation. | You do not have to shoot the photon at an angle in your example, this is a result of the principle of relativity. The photon *appears* to travel diagonally to an outside observer (an observer at rest relative to the moving mirrors). If you move along with the mirrors the photon will still appear to move perpendicular to the mirrors.
You can also imagine throwing a ball up in the air while riding on a train. From your perspective (on the train) the ball will go straight up and come down again. An observer standing still beside the tracks will observe the ball to travel in a parabola though.
What the example in the book is trying to convey is that the passage of time depends on the frame of reference. Moving clocks seem to slow down when viewed from a position relative at rest to the moving system (and, by the principle of relativity, you can reverse that position and claim that the moving clock is at rest and everything else is moving). |
3,116 | So, I want to ignore questions for certain users from my Questions/Unanswered feed. How do I do that?
The main reason for this kind of feature is that not everything that annoys *me* is against the rules, and I don't want to punish other people for me getting annoyed at them.
But, if I can't ignore annoying people, I am less likely to contribute *at all*, because why would I come back to place that annoys me, to do free work?
I have been fairly active in EVE Rookie Help and from that experience I know the ability to focus on the people *I* feel like helping and ignoring the rest is what helps to maintain my sanity and willingness to help *anyone at all*.
And on the other hand, I strongly dislike the idea of preventing *others* helping someone just because *I* am annoyed by him. This kind of environment leads into people getting banned/downvoted by random just because some higher-up had a bad day. Which is plain wrong. | 2011/08/10 | [
"https://meta.superuser.com/questions/3116",
"https://meta.superuser.com",
"https://meta.superuser.com/users/93168/"
] | The Stack Exchange platform does not currently provide this functionality. There is an old [feature request](https://meta.stackexchange.com/questions/3353/ "MSO: add the ability to ignore users") on MSO is currently deferred, which means the team didn't explicitly say no, but also didn't see it a something that needed doing immediately.
Personally, I hope it *doesn't* get implemented, because I'm not sure why it's necessary...
If there is a *serious* problem with another user that would warrant ignoring them, just flag a post of theirs to get a moderator to have a look - we can clean up and take action as necessary.
If there *isn't* a serious problem, well, then why do you need to ignore them? | In general if there are problems with members of our community, we like to intervene to fix it directly. Hiding someone is sweeping an issue under the rug and we would prefer to take a more proactive approach.
So please, flag posts and explain what the issue is and our crack moderators will assist. |
3,116 | So, I want to ignore questions for certain users from my Questions/Unanswered feed. How do I do that?
The main reason for this kind of feature is that not everything that annoys *me* is against the rules, and I don't want to punish other people for me getting annoyed at them.
But, if I can't ignore annoying people, I am less likely to contribute *at all*, because why would I come back to place that annoys me, to do free work?
I have been fairly active in EVE Rookie Help and from that experience I know the ability to focus on the people *I* feel like helping and ignoring the rest is what helps to maintain my sanity and willingness to help *anyone at all*.
And on the other hand, I strongly dislike the idea of preventing *others* helping someone just because *I* am annoyed by him. This kind of environment leads into people getting banned/downvoted by random just because some higher-up had a bad day. Which is plain wrong. | 2011/08/10 | [
"https://meta.superuser.com/questions/3116",
"https://meta.superuser.com",
"https://meta.superuser.com/users/93168/"
] | The Stack Exchange platform does not currently provide this functionality. There is an old [feature request](https://meta.stackexchange.com/questions/3353/ "MSO: add the ability to ignore users") on MSO is currently deferred, which means the team didn't explicitly say no, but also didn't see it a something that needed doing immediately.
Personally, I hope it *doesn't* get implemented, because I'm not sure why it's necessary...
If there is a *serious* problem with another user that would warrant ignoring them, just flag a post of theirs to get a moderator to have a look - we can clean up and take action as necessary.
If there *isn't* a serious problem, well, then why do you need to ignore them? | >
> But, if I can't ignore annoying people, I am less likely to contribute at all, because why would I come back to place that annoys me, to do free work?
>
>
>
This is really a personality thing. One of our top contributors over the last two months left because they were annoyed by a rather small thing (maybe one particular person). This is not what we want, of course. However, from my personal experience, things like these don't happen too often, therefore such a feature would introduce a social component that goes way beyond the scope of Super User (which is, asking and answering questions).
Are there users who really post so many questions that they need to be ignored?
>
> I know the ability to focus on the people I feel like helping and ignoring the rest is what helps to maintain my sanity and willingness to help anyone at all.
>
>
>
Focusing on the important stuff can be achieved by browsing through the tags you're interested in or sorting questions by votes. If the user who annoys you asks questions under a tag that doesn't interest you, add it to the "ignored tags" list. If on the other hand their questions are within your scope of interest, why not answer them?
You still haven't given us enough information to actually help you out. If there is one person **posting stuff you feel doesn't belong on the site, flag or downvote them**. This would include rants, off-topic matter, personal attacks, poor questions, et cetera.
>
> And on the other hand, I strongly dislike the idea of preventing others helping someone just because I am annoyed by him. This kind of environment leads into people getting banned/downvoted by random just because some higher-up had a bad day. Which is plain wrong.
>
>
>
This would again mean that the questions or answers posted by this person are objectively still a good fit for the site and not necessarily bad. If you say "preventing others", that would imply you **flagging a post for closing or deletion for the wrong reasons**. If that were to happen only because you are annoyed by the person, you're abusing the system. |
1,912,391 | The sum of $1+2+3+ . . . +n = n(n+1)/2$, as I have checked carefully, but how can you prove this? I am determining the dimension of the space of $n x n$ matrices in the upper triangular form, and it is clear to me that the number of basis matrices has to be $1 + 2 + 3 + . . . +n$. I found in a book that the number of basis matrices for a U.T. matrix is $n(n+1)/2$, which matches my idea but it is certainly a much more elegant way to put it. But how do you go from one to the other? | 2016/09/02 | [
"https://math.stackexchange.com/questions/1912391",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/361001/"
] | First, you can use simple induction, or else the following trick with a slighly concealed induction too:
$$\begin{align\*}&S=1&+&2&+&3&+\ldots&+&(n-1)&+&n\\&S=n&+&(n-1)&+&(n-2)&+\ldots&+&2&+&1\end{align\*}$$
Sum up both expressions above summandwise and get:
$$2S=(n+1) + (n+1)+\ldots+(n+1)=n(n+1)$$
and we're done. Perhaps the last form is something similar to what legend has said about Gauss solving this as an elementary school pupil. | The sum $1+2+3+4+5+\dots+n$, when $n$ is even, can be written as
```
1 + 2 + 3 + ... + (n/2)
+ n + (n-1) + (n-2) + ... + (n/2 + 1)
```
The sum of each column is $n+1$. The there are $n/2$ columns. So the total is
$(n+1) \times \frac{n}{2} = \frac{n(n+1)}{2}$ |
1,912,391 | The sum of $1+2+3+ . . . +n = n(n+1)/2$, as I have checked carefully, but how can you prove this? I am determining the dimension of the space of $n x n$ matrices in the upper triangular form, and it is clear to me that the number of basis matrices has to be $1 + 2 + 3 + . . . +n$. I found in a book that the number of basis matrices for a U.T. matrix is $n(n+1)/2$, which matches my idea but it is certainly a much more elegant way to put it. But how do you go from one to the other? | 2016/09/02 | [
"https://math.stackexchange.com/questions/1912391",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/361001/"
] | First, you can use simple induction, or else the following trick with a slighly concealed induction too:
$$\begin{align\*}&S=1&+&2&+&3&+\ldots&+&(n-1)&+&n\\&S=n&+&(n-1)&+&(n-2)&+\ldots&+&2&+&1\end{align\*}$$
Sum up both expressions above summandwise and get:
$$2S=(n+1) + (n+1)+\ldots+(n+1)=n(n+1)$$
and we're done. Perhaps the last form is something similar to what legend has said about Gauss solving this as an elementary school pupil. | In grade school they study math mountains.The bottom row of the **seven math mountain** is 1+6. Above this is 2+5 and above this is 3+4.. There are two ways to add the numbers in the seven math mountain: go up one side and down the other ((1+2+3 + 4+5+6) or realize that each layer of the mountain adds to 7, which is why it is called the 7 math mountain, and the count that there are three layers. Thus, the seven math mountain provides a wonderful opportunity for an elementary-school teacher to let the students make a discovery and to teach an elementary principle of mathematics: you can often learn something by doing something (in this case adding) in two different ways. |
2,962,203 | In my template I have a loop like this:
```
{% for member in blog.members.all %}
{{ member.first_name }}
{% endfor %}
```
Is there a way to retrieve only the first 10 members and not all the members ? | 2010/06/02 | [
"https://Stackoverflow.com/questions/2962203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244413/"
] | >
> is there a way I can detect this
> without writing any data?
>
>
>
No because there isn't a way in TCP/IP to detect it without writing any data.
Don't worry about it. Just complete the request actions and write the response. If the client has disappeared, that will cause an IOException: connection reset, which will be thrown into the servlet container. Nothing you have to do about that. | >
> *I need to actually detect when the client disconnects because I have some cleanup I have to do at that point (resources to release, etcetera).*
>
>
>
There the `finally` block is for. It will be executed regardless of the outcome. E.g.
```
OutputStream output = null;
try {
output = response.getOutputStream();
// ...
output.flush();
// ...
} finally {
// Do your cleanup here.
}
```
>
> *If I have the HttpServletRequest available, will trying to read from that throw an IOException if the client disconnects?*
>
>
>
Depends on how you're reading from it and how much of request body is already in server memory. In case of normal form encoded requests, whenever you call `getParameter()` beforehand, it will usually be fully parsed and stored in server memory. Calling the `getInputStream()` won't be useful at all. Better do it on the response instead. |
2,962,203 | In my template I have a loop like this:
```
{% for member in blog.members.all %}
{{ member.first_name }}
{% endfor %}
```
Is there a way to retrieve only the first 10 members and not all the members ? | 2010/06/02 | [
"https://Stackoverflow.com/questions/2962203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244413/"
] | >
> is there a way I can detect this
> without writing any data?
>
>
>
No because there isn't a way in TCP/IP to detect it without writing any data.
Don't worry about it. Just complete the request actions and write the response. If the client has disappeared, that will cause an IOException: connection reset, which will be thrown into the servlet container. Nothing you have to do about that. | Have you tried to flush the buffer of the response:
response.flushBuffer();
Seems to throw an IOException when the client disconnected. |
2,962,203 | In my template I have a loop like this:
```
{% for member in blog.members.all %}
{{ member.first_name }}
{% endfor %}
```
Is there a way to retrieve only the first 10 members and not all the members ? | 2010/06/02 | [
"https://Stackoverflow.com/questions/2962203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244413/"
] | >
> *I need to actually detect when the client disconnects because I have some cleanup I have to do at that point (resources to release, etcetera).*
>
>
>
There the `finally` block is for. It will be executed regardless of the outcome. E.g.
```
OutputStream output = null;
try {
output = response.getOutputStream();
// ...
output.flush();
// ...
} finally {
// Do your cleanup here.
}
```
>
> *If I have the HttpServletRequest available, will trying to read from that throw an IOException if the client disconnects?*
>
>
>
Depends on how you're reading from it and how much of request body is already in server memory. In case of normal form encoded requests, whenever you call `getParameter()` beforehand, it will usually be fully parsed and stored in server memory. Calling the `getInputStream()` won't be useful at all. Better do it on the response instead. | Have you tried to flush the buffer of the response:
response.flushBuffer();
Seems to throw an IOException when the client disconnected. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.