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... | 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 s... | 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;
... |
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... | 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 s... | 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... |
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... | 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;
... | 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... |
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 C... | 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-wr... | 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... |
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 day... | 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 n... | 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... |
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 ... | 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... |
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 ... | 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 *u... |
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 ... | 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... | 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 *u... |
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 ... | 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(... |
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 ... | 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='+',
o... | 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";
prope... | 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 **... |
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='+',
o... | 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 properD... | 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 **... |
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='+',
o... | 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 properD... | 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";
prope... |
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... | 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... | 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... |
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, s... | 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... | [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, s... | 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... |
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, s... | 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... | [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, s... | 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 SqlCom... | [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, s... | 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... | 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... |
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, s... | 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... | 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... |
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, s... | 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... | 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 SqlCom... |
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, s... | 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... | 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... |
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, s... | 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 SqlCom... | 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... |
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, s... | 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... | 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 SqlCom... |
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
FR... | 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...... | 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,
... |
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... | 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 ... | $\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 \fra... |
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 no... | 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... | 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 r... | 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 movin... | 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 graphi... | 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 movin... | 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 graphi... | 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... |
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 movin... | 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 graphi... | 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 movin... | 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... |
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 movin... | 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 movin... | 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... | 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.ge... | 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 ... | 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 i... |
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 some... | 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. ... | 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... |
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 some... | 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. ... | 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 mem... |
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 some... | 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. ... | 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... |
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 some... | 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. ... | 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... |
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 some... | 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 mem... | 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... |
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 some... | 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... | 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... |
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 some... | 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 mem... | 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... |
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 some... | 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... | 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... |
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 PA... | 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(@CodeNa... |
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, F... |
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 th... |
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(@CodeNa... | 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 th... |
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(@CodeNa... |
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 PA... | 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 th... |
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, F... |
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 th... |
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 PA... | ```
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 ... | 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. Tha... | 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 proje... | 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 t... | 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 ... |
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 ... | 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:/... | 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 you... |
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 ... | 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 trigg... | 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}}">
... |
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.__... | 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).
... | 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... |
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 followin... | 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... | 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 c... | 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 escapin... |
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 c... | 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 escapin... |
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 c... | 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 ... |
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 c... | 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 c... | 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 ... |
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 c... | 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 th... | 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{
... | **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.user... |
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 th... | 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
... | **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.user... |
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}... | 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 n... | 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 | remov... |
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}... | 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}
}
... | 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 | remov... |
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":... | 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": "A... |
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)$... | 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)$... | 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)$... | 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>
<o... | 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])
```... | 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 ... |
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>
<o... | 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])
```... | 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... |
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>
<o... | 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 ... | 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... |
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 Repo... | 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... | 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 ... |
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 Repo... | 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... | 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().d... |
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 Repo... | 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().d... | 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 ... |
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... | 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 structu... | 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... |
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... | 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/>
[, 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 th... |
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... | 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 structu... | 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 exce... |
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... | 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/>
[ 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... |
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... | 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... | 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 th... |
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... | 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... | 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 exce... |
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... | 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/>
[, 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 th... |
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... | 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/>
[, you see that the 2 leading causes of death are by far heart disease and cancer with heart disease exce... |
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... | 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 instrumentat... | 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 **Ve... |
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... | 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-... |
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 yo... | 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*. ... | 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 t... |
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... | 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 ... | 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... | 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 ... | >
> 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... |
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 b... | 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. ... | 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 b... | 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. ... | 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 wh... |
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, whi... | >
> *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.getOutputStr... |
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, whi... | 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.getOutputStr... | 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.